p_mysql.go 5.0 KB

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