p_mysql.go 7.0 KB

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