p_mysql.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  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/response"
  9. "runtime/debug"
  10. )
  11. // ----------------------------------------------------------------------------------
  12. // Processor Name: mysql
  13. // ----------------------------------------------------------------------------------
  14. // Description : Saves the e.Data (email data) and e.DeliveryHeader together in mysql
  15. // : using the hash generated by the "hash" processor and stored in
  16. // : e.Hashes
  17. // ----------------------------------------------------------------------------------
  18. // Config Options: mail_table string - mysql table name
  19. // : mysql_db string - mysql database name
  20. // : mysql_host string - mysql host name, eg. 127.0.0.1
  21. // : mysql_pass string - mysql password
  22. // : mysql_user string - mysql username
  23. // : primary_mail_host string - primary host name
  24. // --------------:-------------------------------------------------------------------
  25. // Input : e.Data
  26. // : e.DeliveryHeader generated by ParseHeader() processor
  27. // : e.MailFrom
  28. // : e.Subject - generated by by ParseHeader() processor
  29. // ----------------------------------------------------------------------------------
  30. // Output : Sets e.QueuedId with the first item fromHashes[0]
  31. // ----------------------------------------------------------------------------------
  32. func init() {
  33. processors["mysql"] = func() Decorator {
  34. return MySql()
  35. }
  36. }
  37. type MysqlProcessorConfig struct {
  38. MysqlTable string `json:"mail_table"`
  39. MysqlDB string `json:"mysql_db"`
  40. MysqlHost string `json:"mysql_host"`
  41. MysqlPass string `json:"mysql_pass"`
  42. MysqlUser string `json:"mysql_user"`
  43. PrimaryHost string `json:"primary_mail_host"`
  44. }
  45. type MysqlProcessor struct {
  46. cache stmtCache
  47. config *MysqlProcessorConfig
  48. }
  49. func (m *MysqlProcessor) connect(config *MysqlProcessorConfig) (*sql.DB, error) {
  50. var db *sql.DB
  51. var err error
  52. conf := mysql.Config{
  53. User: config.MysqlUser,
  54. Passwd: config.MysqlPass,
  55. DBName: config.MysqlDB,
  56. Net: "tcp",
  57. Addr: config.MysqlHost,
  58. ReadTimeout: GuerrillaDBAndRedisBatchTimeout + (time.Second * 10),
  59. WriteTimeout: GuerrillaDBAndRedisBatchTimeout + (time.Second * 10),
  60. Params: map[string]string{"collation": "utf8_general_ci"},
  61. }
  62. if db, err = sql.Open("mysql", conf.FormatDSN()); err != nil {
  63. Log().Error("cannot open mysql", err)
  64. return nil, err
  65. }
  66. Log().Info("connected to mysql on tcp ", config.MysqlHost)
  67. return db, err
  68. }
  69. // prepares the sql query with the number of rows that can be batched with it
  70. func (g *MysqlProcessor) prepareInsertQuery(rows int, db *sql.DB) *sql.Stmt {
  71. if rows == 0 {
  72. panic("rows argument cannot be 0")
  73. }
  74. if g.cache[rows-1] != nil {
  75. return g.cache[rows-1]
  76. }
  77. sqlstr := "INSERT INTO " + g.config.MysqlTable + " "
  78. sqlstr += "(`date`, `to`, `from`, `subject`, `body`, `charset`, `mail`, `spam_score`, `hash`, `content_type`, `recipient`, `has_attach`, `ip_addr`, `return_path`, `is_tls`)"
  79. sqlstr += " values "
  80. values := "(NOW(), ?, ?, ?, ? , 'UTF-8' , ?, 0, ?, '', ?, 0, ?, ?, ?)"
  81. // add more rows
  82. comma := ""
  83. for i := 0; i < rows; i++ {
  84. sqlstr += comma + values
  85. if comma == "" {
  86. comma = ","
  87. }
  88. }
  89. stmt, sqlErr := db.Prepare(sqlstr)
  90. if sqlErr != nil {
  91. Log().WithError(sqlErr).Panic("failed while db.Prepare(INSERT...)")
  92. }
  93. // cache it
  94. g.cache[rows-1] = stmt
  95. return stmt
  96. }
  97. func (g *MysqlProcessor) doQuery(c int, db *sql.DB, insertStmt *sql.Stmt, vals *[]interface{}) {
  98. var execErr error
  99. defer func() {
  100. if r := recover(); r != nil {
  101. Log().Error("Recovered form panic:", r, string(debug.Stack()))
  102. sum := 0
  103. for _, v := range *vals {
  104. if str, ok := v.(string); ok {
  105. sum = sum + len(str)
  106. }
  107. }
  108. Log().Errorf("panic while inserting query [%s] size:%d, err %v", r, sum, execErr)
  109. panic("query failed")
  110. }
  111. }()
  112. // prepare the query used to insert when rows reaches batchMax
  113. insertStmt = g.prepareInsertQuery(c, db)
  114. _, execErr = insertStmt.Exec(*vals...)
  115. if execErr != nil {
  116. Log().WithError(execErr).Error("There was a problem the insert")
  117. }
  118. }
  119. func MySql() Decorator {
  120. var config *MysqlProcessorConfig
  121. var vals []interface{}
  122. var db *sql.DB
  123. mp := &MysqlProcessor{}
  124. Svc.AddInitializer(Initialize(func(backendConfig BackendConfig) error {
  125. configType := BaseConfig(&MysqlProcessorConfig{})
  126. bcfg, err := Svc.ExtractConfig(backendConfig, configType)
  127. if err != nil {
  128. return err
  129. }
  130. config = bcfg.(*MysqlProcessorConfig)
  131. mp.config = config
  132. db, err = mp.connect(config)
  133. if err != nil {
  134. Log().Error("cannot open mysql: %s", err)
  135. return err
  136. }
  137. return nil
  138. }))
  139. // shutdown
  140. Svc.AddShutdowner(Shutdown(func() error {
  141. if db != nil {
  142. return db.Close()
  143. }
  144. return nil
  145. }))
  146. return func(c Processor) Processor {
  147. return ProcessWith(func(e *envelope.Envelope, task SelectTask) (Result, error) {
  148. if task == TaskSaveMail {
  149. var to, body string
  150. to = trimToLimit(strings.TrimSpace(e.RcptTo[0].User)+"@"+config.PrimaryHost, 255)
  151. hash := ""
  152. if len(e.Hashes) > 0 {
  153. hash = e.Hashes[0]
  154. e.QueuedId = e.Hashes[0]
  155. }
  156. var co *compressor
  157. // a compressor was set
  158. if c, ok := e.Values["zlib-compressor"]; ok {
  159. body = "gzip"
  160. co = c.(*compressor)
  161. }
  162. // was saved in redis
  163. if _, ok := e.Values["redis"]; ok {
  164. body = "redis"
  165. }
  166. // build the values for the query
  167. vals = []interface{}{} // clear the vals
  168. vals = append(vals,
  169. to,
  170. trimToLimit(e.MailFrom.String(), 255),
  171. trimToLimit(e.Subject, 255),
  172. body)
  173. if body == "redis" {
  174. // data already saved in redis
  175. vals = append(vals, "")
  176. } else if co != nil {
  177. // use a compressor (automatically adds e.DeliveryHeader)
  178. vals = append(vals, co.String())
  179. } else {
  180. vals = append(vals, e.String())
  181. }
  182. vals = append(vals,
  183. hash,
  184. to,
  185. e.RemoteAddress,
  186. trimToLimit(e.MailFrom.String(), 255),
  187. e.TLS)
  188. stmt := mp.prepareInsertQuery(1, db)
  189. mp.doQuery(1, db, stmt, &vals)
  190. // continue to the next Processor in the decorator chain
  191. return c.Process(e, task)
  192. } else if task == TaskValidateRcpt {
  193. // if you need to validate the e.Rcpt then change to:
  194. if len(e.RcptTo) > 0 {
  195. // since this is called each time a recipient is added
  196. // validate only the _last_ recipient that was appended
  197. last := e.RcptTo[len(e.RcptTo)-1]
  198. if len(last.User) > 255 {
  199. // TODO what kind of response to send?
  200. return NewResult(response.Canned.FailNoSenderDataCmd), NoSuchUser
  201. }
  202. }
  203. return c.Process(e, task)
  204. } else {
  205. return c.Process(e, task)
  206. }
  207. })
  208. }
  209. }