p_mysql.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. package backends
  2. import (
  3. "database/sql"
  4. "strings"
  5. "time"
  6. "github.com/flashmob/go-guerrilla/envelope"
  7. "github.com/go-sql-driver/mysql"
  8. "runtime/debug"
  9. )
  10. type MysqlProcessorConfig struct {
  11. NumberOfWorkers int `json:"save_workers_size"`
  12. MysqlTable string `json:"mail_table"`
  13. MysqlDB string `json:"mysql_db"`
  14. MysqlHost string `json:"mysql_host"`
  15. MysqlPass string `json:"mysql_pass"`
  16. MysqlUser string `json:"mysql_user"`
  17. RedisExpireSeconds int `json:"redis_expire_seconds"`
  18. RedisInterface string `json:"redis_interface"`
  19. PrimaryHost string `json:"primary_mail_host"`
  20. }
  21. type MysqlProcessor struct {
  22. cache stmtCache
  23. config *MysqlProcessorConfig
  24. }
  25. func (m *MysqlProcessor) connect(config *MysqlProcessorConfig) (*sql.DB, error) {
  26. var db *sql.DB
  27. var err error
  28. conf := mysql.Config{
  29. User: config.MysqlUser,
  30. Passwd: config.MysqlPass,
  31. DBName: config.MysqlDB,
  32. Net: "tcp",
  33. Addr: config.MysqlHost,
  34. ReadTimeout: GuerrillaDBAndRedisBatchTimeout + (time.Second * 10),
  35. WriteTimeout: GuerrillaDBAndRedisBatchTimeout + (time.Second * 10),
  36. Params: map[string]string{"collation": "utf8_general_ci"},
  37. }
  38. if db, err = sql.Open("mysql", conf.FormatDSN()); err != nil {
  39. mainlog.Error("cannot open mysql", err)
  40. return nil, err
  41. }
  42. mainlog.Info("connected to mysql on tcp ", config.MysqlHost)
  43. return db, err
  44. }
  45. // prepares the sql query with the number of rows that can be batched with it
  46. func (g *MysqlProcessor) prepareInsertQuery(rows int, db *sql.DB) *sql.Stmt {
  47. if rows == 0 {
  48. panic("rows argument cannot be 0")
  49. }
  50. if g.cache[rows-1] != nil {
  51. return g.cache[rows-1]
  52. }
  53. sqlstr := "INSERT INTO " + g.config.MysqlTable + " "
  54. sqlstr += "(`date`, `to`, `from`, `subject`, `body`, `charset`, `mail`, `spam_score`, `hash`, `content_type`, `recipient`, `has_attach`, `ip_addr`, `return_path`, `is_tls`)"
  55. sqlstr += " values "
  56. values := "(NOW(), ?, ?, ?, ? , 'UTF-8' , ?, 0, ?, '', ?, 0, ?, ?, ?)"
  57. // add more rows
  58. comma := ""
  59. for i := 0; i < rows; i++ {
  60. sqlstr += comma + values
  61. if comma == "" {
  62. comma = ","
  63. }
  64. }
  65. stmt, sqlErr := db.Prepare(sqlstr)
  66. if sqlErr != nil {
  67. mainlog.WithError(sqlErr).Fatalf("failed while db.Prepare(INSERT...)")
  68. }
  69. // cache it
  70. g.cache[rows-1] = stmt
  71. return stmt
  72. }
  73. func (g *MysqlProcessor) doQuery(c int, db *sql.DB, insertStmt *sql.Stmt, vals *[]interface{}) {
  74. var execErr error
  75. defer func() {
  76. if r := recover(); r != nil {
  77. //logln(1, fmt.Sprintf("Recovered in %v", r))
  78. mainlog.Error("Recovered form panic:", r, string(debug.Stack()))
  79. sum := 0
  80. for _, v := range *vals {
  81. if str, ok := v.(string); ok {
  82. sum = sum + len(str)
  83. }
  84. }
  85. mainlog.Errorf("panic while inserting query [%s] size:%d, err %v", r, sum, execErr)
  86. panic("query failed")
  87. }
  88. }()
  89. // prepare the query used to insert when rows reaches batchMax
  90. insertStmt = g.prepareInsertQuery(c, db)
  91. _, execErr = insertStmt.Exec(*vals...)
  92. if execErr != nil {
  93. mainlog.WithError(execErr).Error("There was a problem the insert")
  94. }
  95. }
  96. func MySql() Decorator {
  97. var config *MysqlProcessorConfig
  98. var vals []interface{}
  99. var db *sql.DB
  100. mp := &MysqlProcessor{}
  101. Service.AddInitializer(Initialize(func(backendConfig BackendConfig) error {
  102. configType := baseConfig(&MysqlProcessorConfig{})
  103. bcfg, err := ab.extractConfig(backendConfig, configType)
  104. if err != nil {
  105. return err
  106. }
  107. config = bcfg.(*MysqlProcessorConfig)
  108. mp.config = config
  109. db, err = mp.connect(config)
  110. if err != nil {
  111. mainlog.Fatalf("cannot open mysql: %s", err)
  112. return err
  113. }
  114. return nil
  115. }))
  116. // shutdown
  117. Service.AddShutdowner(Shutdown(func() error {
  118. if db != nil {
  119. db.Close()
  120. }
  121. return nil
  122. }))
  123. return func(c Processor) Processor {
  124. return ProcessorFunc(func(e *envelope.Envelope) (BackendResult, error) {
  125. var to, body string
  126. to = trimToLimit(strings.TrimSpace(e.RcptTo[0].User)+"@"+config.PrimaryHost, 255)
  127. hash := ""
  128. if len(e.Hashes) > 0 {
  129. hash = e.Hashes[0]
  130. }
  131. var co *compressor
  132. // a compressor was set
  133. if e.Meta != nil {
  134. if c, ok := e.Meta["zlib-compressor"]; ok {
  135. body = "gzip"
  136. co = c.(*compressor)
  137. }
  138. // was saved in redis
  139. if _, ok := e.Meta["redis"]; ok {
  140. body = "redis"
  141. }
  142. }
  143. // build the values for the query
  144. vals = []interface{}{} // clear the vals
  145. vals = append(vals,
  146. to,
  147. trimToLimit(e.MailFrom.String(), 255),
  148. trimToLimit(e.Subject, 255),
  149. body)
  150. if body == "redis" {
  151. // data already saved in redis
  152. vals = append(vals, "")
  153. } else if co != nil {
  154. // use a compressor (automatically adds e.DeliveryHeader)
  155. vals = append(vals, co.String())
  156. //co.clear()
  157. } else {
  158. vals = append(vals, e.DeliveryHeader+e.Data.String())
  159. }
  160. vals = append(vals,
  161. hash,
  162. to,
  163. e.RemoteAddress,
  164. trimToLimit(e.MailFrom.String(), 255),
  165. e.TLS)
  166. stmt := mp.prepareInsertQuery(1, db)
  167. mp.doQuery(1, db, stmt, &vals)
  168. // continue to the next Processor in the decorator chain
  169. return c.Process(e)
  170. })
  171. }
  172. }