guerrilla_db_redis.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. package backends
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "sync"
  7. "time"
  8. log "github.com/Sirupsen/logrus"
  9. "github.com/flashmob/go-guerrilla"
  10. "github.com/garyburd/redigo/redis"
  11. "github.com/ziutek/mymysql/autorc"
  12. _ "github.com/ziutek/mymysql/godrv"
  13. )
  14. type GuerrillaDBAndRedisBackend struct {
  15. config guerrillaDBAndRedisConfig
  16. saveMailChan chan *savePayload
  17. wg sync.WaitGroup
  18. }
  19. type guerrillaDBAndRedisConfig struct {
  20. NumberOfWorkers int `json:"save_workers_size"`
  21. MysqlTable string `json:"mail_table"`
  22. MysqlDB string `json:"mysql_db"`
  23. MysqlHost string `json:"mysql_host"`
  24. MysqlPass string `json:"mysql_pass"`
  25. MysqlUser string `json:"mysql_user"`
  26. RedisExpireSeconds int `json:"redis_expire_seconds"`
  27. RedisInterface string `json:"redis_interface"`
  28. PrimaryHost string `json:"primary_mail_host"`
  29. }
  30. func convertError(name string) error {
  31. return fmt.Errorf("failed to load backend config (%s)", name)
  32. }
  33. // Load the backend config for the backend. It has already been unmarshalled
  34. // from the main config file 'backend' config "backend_config"
  35. // Now we need to convert each type and copy into the guerrillaDBAndRedisConfig struct
  36. func (g *GuerrillaDBAndRedisBackend) loadConfig(backendConfig map[string]interface{}) error {
  37. data, err := json.Marshal(backendConfig)
  38. if err != nil {
  39. return err
  40. }
  41. err = json.Unmarshal(data, &g.config)
  42. if g.config.NumberOfWorkers < 1 {
  43. return errors.New("Must have more than 1 worker")
  44. }
  45. return err
  46. }
  47. func (g *GuerrillaDBAndRedisBackend) Initialize(backendConfig map[string]interface{}) error {
  48. err := g.loadConfig(backendConfig)
  49. if err != nil {
  50. return err
  51. }
  52. if err := g.testDbConnections(); err != nil {
  53. return err
  54. }
  55. g.saveMailChan = make(chan *savePayload, g.config.NumberOfWorkers)
  56. // start some savemail workers
  57. g.wg.Add(g.config.NumberOfWorkers)
  58. for i := 0; i < g.config.NumberOfWorkers; i++ {
  59. go g.saveMail()
  60. }
  61. return nil
  62. }
  63. func (g *GuerrillaDBAndRedisBackend) Shutdown() error {
  64. close(g.saveMailChan) // workers will stop
  65. g.wg.Wait()
  66. return nil
  67. }
  68. func (g *GuerrillaDBAndRedisBackend) Process(mail *guerrilla.Envelope) guerrilla.BackendResult {
  69. to := mail.RcptTo
  70. from := mail.MailFrom
  71. if len(to) == 0 {
  72. return guerrilla.NewBackendResult("554 Error: no recipient")
  73. }
  74. // to do: timeout when adding to SaveMailChan
  75. // place on the channel so that one of the save mail workers can pick it up
  76. // TODO: support multiple recipients
  77. savedNotify := make(chan *saveStatus)
  78. g.saveMailChan <- &savePayload{mail, from, to[0], savedNotify}
  79. // wait for the save to complete
  80. // or timeout
  81. select {
  82. case status := <-savedNotify:
  83. if status.err != nil {
  84. return guerrilla.NewBackendResult("554 Error: " + status.err.Error())
  85. }
  86. return guerrilla.NewBackendResult(fmt.Sprintf("250 OK : queued as %s", status.hash))
  87. case <-time.After(time.Second * 30):
  88. log.Debug("timeout")
  89. return guerrilla.NewBackendResult("554 Error: transaction timeout")
  90. }
  91. }
  92. type savePayload struct {
  93. mail *guerrilla.Envelope
  94. from *guerrilla.EmailAddress
  95. recipient *guerrilla.EmailAddress
  96. savedNotify chan *saveStatus
  97. }
  98. type saveStatus struct {
  99. err error
  100. hash string
  101. }
  102. type redisClient struct {
  103. isConnected bool
  104. conn redis.Conn
  105. time int
  106. }
  107. func (g *GuerrillaDBAndRedisBackend) saveMail() {
  108. var to, body string
  109. var err error
  110. var redisErr error
  111. var length int
  112. redisClient := &redisClient{}
  113. db := autorc.New(
  114. "tcp",
  115. "",
  116. g.config.MysqlHost,
  117. g.config.MysqlUser,
  118. g.config.MysqlPass,
  119. g.config.MysqlDB)
  120. db.Register("set names utf8")
  121. sql := "INSERT INTO " + g.config.MysqlTable + " "
  122. sql += "(`date`, `to`, `from`, `subject`, `body`, `charset`, `mail`, `spam_score`, `hash`, `content_type`, `recipient`, `has_attach`, `ip_addr`, `return_path`, `is_tls`)"
  123. sql += " values (NOW(), ?, ?, ?, ? , 'UTF-8' , ?, 0, ?, '', ?, 0, ?, ?, ?)"
  124. ins, sqlErr := db.Prepare(sql)
  125. if sqlErr != nil {
  126. log.WithError(sqlErr).Fatalf("failed while db.Prepare(INSERT...)")
  127. }
  128. sql = "UPDATE gm2_setting SET `setting_value` = `setting_value`+1 WHERE `setting_name`='received_emails' LIMIT 1"
  129. incr, sqlErr := db.Prepare(sql)
  130. if sqlErr != nil {
  131. log.WithError(sqlErr).Fatalf("failed while db.Prepare(UPDATE...)")
  132. }
  133. defer func() {
  134. if r := recover(); r != nil {
  135. // recover form closed channel
  136. fmt.Println("Recovered in f", r)
  137. }
  138. if db.Raw != nil {
  139. db.Raw.Close()
  140. }
  141. if redisClient.conn != nil {
  142. log.Infof("closed redis")
  143. redisClient.conn.Close()
  144. }
  145. g.wg.Done()
  146. }()
  147. // receives values from the channel repeatedly until it is closed.
  148. for {
  149. payload := <-g.saveMailChan
  150. if payload == nil {
  151. log.Debug("No more saveMailChan payload")
  152. return
  153. }
  154. to = payload.recipient.User + "@" + g.config.PrimaryHost
  155. length = len(payload.mail.Data)
  156. ts := fmt.Sprintf("%d", time.Now().UnixNano())
  157. payload.mail.Subject = MimeHeaderDecode(payload.mail.Subject)
  158. hash := MD5Hex(
  159. to,
  160. payload.mail.MailFrom.String(),
  161. payload.mail.Subject,
  162. ts)
  163. // Add extra headers
  164. var addHead string
  165. addHead += "Delivered-To: " + to + "\r\n"
  166. addHead += "Received: from " + payload.mail.Helo + " (" + payload.mail.Helo + " [" + payload.mail.RemoteAddress + "])\r\n"
  167. addHead += " by " + payload.recipient.Host + " with SMTP id " + hash + "@" + payload.recipient.Host + ";\r\n"
  168. addHead += " " + time.Now().Format(time.RFC1123Z) + "\r\n"
  169. // compress to save space
  170. payload.mail.Data = Compress(addHead, payload.mail.Data)
  171. body = "gzencode"
  172. redisErr = redisClient.redisConnection(g.config.RedisInterface)
  173. if redisErr == nil {
  174. _, doErr := redisClient.conn.Do("SETEX", hash, g.config.RedisExpireSeconds, payload.mail.Data)
  175. if doErr == nil {
  176. payload.mail.Data = ""
  177. body = "redis"
  178. }
  179. } else {
  180. log.WithError(redisErr).Warn("Error while SETEX on redis")
  181. }
  182. // bind data to cursor
  183. ins.Bind(
  184. to,
  185. payload.mail.MailFrom.String(),
  186. payload.mail.Subject,
  187. body,
  188. payload.mail.Data,
  189. hash,
  190. to,
  191. payload.mail.RemoteAddress,
  192. payload.mail.MailFrom.String(),
  193. payload.mail.TLS,
  194. )
  195. // save, discard result
  196. _, _, err = ins.Exec()
  197. if err != nil {
  198. errMsg := "Database error while inserting"
  199. log.WithError(err).Warn(errMsg)
  200. payload.savedNotify <- &saveStatus{errors.New(errMsg), hash}
  201. } else {
  202. log.Debugf("Email saved %s (len=%d)", hash, length)
  203. _, _, err = incr.Exec()
  204. if err != nil {
  205. log.WithError(err).Warn("Database error while incr count")
  206. }
  207. payload.savedNotify <- &saveStatus{nil, hash}
  208. }
  209. }
  210. }
  211. func (c *redisClient) redisConnection(redisInterface string) (err error) {
  212. if c.isConnected == false {
  213. c.conn, err = redis.Dial("tcp", redisInterface)
  214. if err != nil {
  215. // handle error
  216. return err
  217. }
  218. c.isConnected = true
  219. }
  220. return nil
  221. }
  222. // test database connection settings
  223. func (g *GuerrillaDBAndRedisBackend) testDbConnections() (err error) {
  224. db := autorc.New(
  225. "tcp",
  226. "",
  227. g.config.MysqlHost,
  228. g.config.MysqlUser,
  229. g.config.MysqlPass,
  230. g.config.MysqlDB)
  231. if mysqlErr := db.Raw.Connect(); mysqlErr != nil {
  232. err = fmt.Errorf("MySql cannot connect, check your settings: %s", mysqlErr)
  233. } else {
  234. db.Raw.Close()
  235. }
  236. redisClient := &redisClient{}
  237. if redisErr := redisClient.redisConnection(g.config.RedisInterface); redisErr != nil {
  238. err = fmt.Errorf("Redis cannot connect, check your settings: %s", redisErr)
  239. }
  240. return
  241. }