p_mysql.go 5.0 KB

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