guerrilla_db_redis.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. package backends
  2. // This backend is presented here as an example only, please modify it to your needs.
  3. //
  4. // Deprecated: as of 14th Feb 2017, backends are composed via config, by chaining Processors (files prefixed with p_*)
  5. //
  6. // The backend stores the email data in Redis.
  7. // Other meta-information is stored in MySQL to be joined later.
  8. // A lot of email gets discarded without viewing on Guerrilla Mail,
  9. // so it's much faster to put in Redis, where other programs can
  10. // process it later, without touching the disk.
  11. //
  12. // Some features:
  13. // - It batches the SQL inserts into a single query and inserts either after a time threshold or if the batch is full
  14. // - If the mysql driver crashes, it's able to recover, log the incident and resume again.
  15. // - It also does a clean shutdown - it tries to save everything before returning
  16. //
  17. // Short history:
  18. // Started with issuing an insert query for each single email and another query to update the tally
  19. // Then applied the following optimizations:
  20. // - Moved tally updates to another background process which does the tallying in a single query
  21. // - Changed the MySQL queries to insert in batch
  22. // - Made a Compressor that recycles buffers using sync.Pool
  23. // The result was around 400% speed improvement. If you know of any more improvements, please share!
  24. // - Added the recovery mechanism,
  25. import (
  26. "fmt"
  27. "time"
  28. "github.com/garyburd/redigo/redis"
  29. "bytes"
  30. "compress/zlib"
  31. "database/sql"
  32. "github.com/flashmob/go-guerrilla/envelope"
  33. "github.com/go-sql-driver/mysql"
  34. "io"
  35. "runtime/debug"
  36. "strings"
  37. "sync"
  38. )
  39. // how many rows to batch at a time
  40. const GuerrillaDBAndRedisBatchMax = 2
  41. // tick on every...
  42. const GuerrillaDBAndRedisBatchTimeout = time.Second * 3
  43. func init() {
  44. backends["guerrilla-db-redis"] = &ProxyBackend{
  45. extend: &GuerrillaDBAndRedisBackend{}}
  46. }
  47. type GuerrillaDBAndRedisBackend struct {
  48. config guerrillaDBAndRedisConfig
  49. batcherWg sync.WaitGroup
  50. // cache prepared queries
  51. cache stmtCache
  52. }
  53. // statement cache. It's an array, not slice
  54. type stmtCache [GuerrillaDBAndRedisBatchMax]*sql.Stmt
  55. type guerrillaDBAndRedisConfig struct {
  56. NumberOfWorkers int `json:"save_workers_size"`
  57. MysqlTable string `json:"mail_table"`
  58. MysqlDB string `json:"mysql_db"`
  59. MysqlHost string `json:"mysql_host"`
  60. MysqlPass string `json:"mysql_pass"`
  61. MysqlUser string `json:"mysql_user"`
  62. RedisExpireSeconds int `json:"redis_expire_seconds"`
  63. RedisInterface string `json:"redis_interface"`
  64. PrimaryHost string `json:"primary_mail_host"`
  65. }
  66. func convertError(name string) error {
  67. return fmt.Errorf("failed to load backend config (%s)", name)
  68. }
  69. // Load the backend config for the backend. It has already been unmarshalled
  70. // from the main config file 'backend' config "backend_config"
  71. // Now we need to convert each type and copy into the guerrillaDBAndRedisConfig struct
  72. func (g *GuerrillaDBAndRedisBackend) loadConfig(backendConfig BackendConfig) (err error) {
  73. configType := BaseConfig(&guerrillaDBAndRedisConfig{})
  74. bcfg, err := Svc.ExtractConfig(backendConfig, configType)
  75. if err != nil {
  76. return err
  77. }
  78. m := bcfg.(*guerrillaDBAndRedisConfig)
  79. g.config = *m
  80. return nil
  81. }
  82. func (g *GuerrillaDBAndRedisBackend) getNumberOfWorkers() int {
  83. return g.config.NumberOfWorkers
  84. }
  85. // ValidateRcpt not implemented
  86. func (g *GuerrillaDBAndRedisBackend) ValidateRcpt(e *envelope.Envelope) RcptError {
  87. return nil
  88. }
  89. type redisClient struct {
  90. isConnected bool
  91. conn redis.Conn
  92. time int
  93. }
  94. // compressedData struct will be compressed using zlib when printed via fmt
  95. type compressedData struct {
  96. extraHeaders []byte
  97. data *bytes.Buffer
  98. pool *sync.Pool
  99. }
  100. // newCompressedData returns a new CompressedData
  101. func newCompressedData() *compressedData {
  102. var p = sync.Pool{
  103. New: func() interface{} {
  104. var b bytes.Buffer
  105. return &b
  106. },
  107. }
  108. return &compressedData{
  109. pool: &p,
  110. }
  111. }
  112. // Set the extraheaders and buffer of data to compress
  113. func (c *compressedData) set(b []byte, d *bytes.Buffer) {
  114. c.extraHeaders = b
  115. c.data = d
  116. }
  117. // implement Stringer interface
  118. func (c *compressedData) String() string {
  119. if c.data == nil {
  120. return ""
  121. }
  122. //borrow a buffer form the pool
  123. b := c.pool.Get().(*bytes.Buffer)
  124. // put back in the pool
  125. defer func() {
  126. b.Reset()
  127. c.pool.Put(b)
  128. }()
  129. var r *bytes.Reader
  130. w, _ := zlib.NewWriterLevel(b, zlib.BestSpeed)
  131. r = bytes.NewReader(c.extraHeaders)
  132. io.Copy(w, r)
  133. io.Copy(w, c.data)
  134. w.Close()
  135. return b.String()
  136. }
  137. // clear it, without clearing the pool
  138. func (c *compressedData) clear() {
  139. c.extraHeaders = []byte{}
  140. c.data = nil
  141. }
  142. // prepares the sql query with the number of rows that can be batched with it
  143. func (g *GuerrillaDBAndRedisBackend) prepareInsertQuery(rows int, db *sql.DB) *sql.Stmt {
  144. if rows == 0 {
  145. panic("rows argument cannot be 0")
  146. }
  147. if g.cache[rows-1] != nil {
  148. return g.cache[rows-1]
  149. }
  150. sqlstr := "INSERT INTO " + g.config.MysqlTable + " "
  151. sqlstr += "(`date`, `to`, `from`, `subject`, `body`, `charset`, `mail`, `spam_score`, `hash`, `content_type`, `recipient`, `has_attach`, `ip_addr`, `return_path`, `is_tls`)"
  152. sqlstr += " values "
  153. values := "(NOW(), ?, ?, ?, ? , 'UTF-8' , ?, 0, ?, '', ?, 0, ?, ?, ?)"
  154. // add more rows
  155. comma := ""
  156. for i := 0; i < rows; i++ {
  157. sqlstr += comma + values
  158. if comma == "" {
  159. comma = ","
  160. }
  161. }
  162. stmt, sqlErr := db.Prepare(sqlstr)
  163. if sqlErr != nil {
  164. Log().WithError(sqlErr).Fatalf("failed while db.Prepare(INSERT...)")
  165. }
  166. // cache it
  167. g.cache[rows-1] = stmt
  168. return stmt
  169. }
  170. func (g *GuerrillaDBAndRedisBackend) doQuery(c int, db *sql.DB, insertStmt *sql.Stmt, vals *[]interface{}) {
  171. var execErr error
  172. defer func() {
  173. if r := recover(); r != nil {
  174. //logln(1, fmt.Sprintf("Recovered in %v", r))
  175. Log().Error("Recovered form panic:", r, string(debug.Stack()))
  176. sum := 0
  177. for _, v := range *vals {
  178. if str, ok := v.(string); ok {
  179. sum = sum + len(str)
  180. }
  181. }
  182. Log().Errorf("panic while inserting query [%s] size:%d, err %v", r, sum, execErr)
  183. panic("query failed")
  184. }
  185. }()
  186. // prepare the query used to insert when rows reaches batchMax
  187. insertStmt = g.prepareInsertQuery(c, db)
  188. _, execErr = insertStmt.Exec(*vals...)
  189. if execErr != nil {
  190. Log().WithError(execErr).Error("There was a problem the insert")
  191. }
  192. }
  193. // Batches the rows from the feeder chan in to a single INSERT statement.
  194. // Execute the batches query when:
  195. // - number of batched rows reaches a threshold, i.e. count n = threshold
  196. // - or, no new rows within a certain time, i.e. times out
  197. // The goroutine can either exit if there's a panic or feeder channel closes
  198. // it returns feederOk which signals if the feeder chanel was ok (still open) while returning
  199. // if it feederOk is false, then it means the feeder chanel is closed
  200. func (g *GuerrillaDBAndRedisBackend) insertQueryBatcher(feeder chan []interface{}, db *sql.DB) (feederOk bool) {
  201. // controls shutdown
  202. defer g.batcherWg.Done()
  203. g.batcherWg.Add(1)
  204. // vals is where values are batched to
  205. var vals []interface{}
  206. // how many rows were batched
  207. count := 0
  208. // The timer will tick every second.
  209. // Interrupting the select clause when there's no data on the feeder channel
  210. t := time.NewTimer(GuerrillaDBAndRedisBatchTimeout)
  211. // prepare the query used to insert when rows reaches batchMax
  212. insertStmt := g.prepareInsertQuery(GuerrillaDBAndRedisBatchMax, db)
  213. // inserts executes a batched insert query, clears the vals and resets the count
  214. insert := func(c int) {
  215. if c > 0 {
  216. g.doQuery(c, db, insertStmt, &vals)
  217. }
  218. vals = nil
  219. count = 0
  220. }
  221. defer func() {
  222. if r := recover(); r != nil {
  223. Log().Error("insertQueryBatcher caught a panic", r)
  224. }
  225. }()
  226. // Keep getting values from feeder and add to batch.
  227. // if feeder times out, execute the batched query
  228. // otherwise, execute the batched query once it reaches the GuerrillaDBAndRedisBatchMax threshold
  229. feederOk = true
  230. for {
  231. select {
  232. // it may panic when reading on a closed feeder channel. feederOK detects if it was closed
  233. case row, feederOk := <-feeder:
  234. if row == nil {
  235. Log().Info("Query batchaer exiting")
  236. // Insert any remaining rows
  237. insert(count)
  238. return feederOk
  239. }
  240. vals = append(vals, row...)
  241. count++
  242. Log().Debug("new feeder row:", row, " cols:", len(row), " count:", count, " worker", workerId)
  243. if count >= GuerrillaDBAndRedisBatchMax {
  244. insert(GuerrillaDBAndRedisBatchMax)
  245. }
  246. // stop timer from firing (reset the interrupt)
  247. if !t.Stop() {
  248. <-t.C
  249. }
  250. t.Reset(GuerrillaDBAndRedisBatchTimeout)
  251. case <-t.C:
  252. // anything to insert?
  253. if n := len(vals); n > 0 {
  254. insert(count)
  255. }
  256. t.Reset(GuerrillaDBAndRedisBatchTimeout)
  257. }
  258. }
  259. }
  260. func trimToLimit(str string, limit int) string {
  261. ret := strings.TrimSpace(str)
  262. if len(str) > limit {
  263. ret = str[:limit]
  264. }
  265. return ret
  266. }
  267. var workerId = 0
  268. func (g *GuerrillaDBAndRedisBackend) mysqlConnect() (*sql.DB, error) {
  269. conf := mysql.Config{
  270. User: g.config.MysqlUser,
  271. Passwd: g.config.MysqlPass,
  272. DBName: g.config.MysqlDB,
  273. Net: "tcp",
  274. Addr: g.config.MysqlHost,
  275. ReadTimeout: GuerrillaDBAndRedisBatchTimeout + (time.Second * 10),
  276. WriteTimeout: GuerrillaDBAndRedisBatchTimeout + (time.Second * 10),
  277. Params: map[string]string{"collation": "utf8_general_ci"},
  278. }
  279. if db, err := sql.Open("mysql", conf.FormatDSN()); err != nil {
  280. Log().Error("cannot open mysql", err)
  281. return nil, err
  282. } else {
  283. return db, nil
  284. }
  285. }
  286. func (g *GuerrillaDBAndRedisBackend) saveMailWorker(saveMailChan chan *workerMsg) {
  287. var to, body string
  288. var redisErr error
  289. workerId++
  290. redisClient := &redisClient{}
  291. var db *sql.DB
  292. var err error
  293. db, err = g.mysqlConnect()
  294. if err != nil {
  295. Log().Fatalf("cannot open mysql: %s", err)
  296. }
  297. // start the query SQL batching where we will send data via the feeder channel
  298. feeder := make(chan []interface{}, 1)
  299. go func() {
  300. for {
  301. if feederOK := g.insertQueryBatcher(feeder, db); !feederOK {
  302. Log().Debug("insertQueryBatcher exited")
  303. return
  304. }
  305. // if insertQueryBatcher panics, it can recover and go in again
  306. Log().Debug("resuming insertQueryBatcher")
  307. }
  308. }()
  309. defer func() {
  310. if r := recover(); r != nil {
  311. //recover form closed channel
  312. Log().Error("panic recovered in saveMailWorker", r)
  313. }
  314. db.Close()
  315. if redisClient.conn != nil {
  316. Log().Infof("closed redis")
  317. redisClient.conn.Close()
  318. }
  319. // close the feeder & wait for query batcher to exit.
  320. close(feeder)
  321. g.batcherWg.Wait()
  322. }()
  323. var vals []interface{}
  324. data := newCompressedData()
  325. // receives values from the channel repeatedly until it is closed.
  326. for {
  327. payload := <-saveMailChan
  328. if payload == nil {
  329. Log().Debug("No more saveMailChan payload")
  330. return
  331. }
  332. Log().Debug("Got mail from chan", payload.mail.RemoteAddress)
  333. to = trimToLimit(strings.TrimSpace(payload.mail.RcptTo[0].User)+"@"+g.config.PrimaryHost, 255)
  334. payload.mail.Helo = trimToLimit(payload.mail.Helo, 255)
  335. host := trimToLimit(payload.mail.RcptTo[0].Host, 255)
  336. ts := fmt.Sprintf("%d", time.Now().UnixNano())
  337. payload.mail.ParseHeaders()
  338. hash := MD5Hex(
  339. to,
  340. payload.mail.MailFrom.String(),
  341. payload.mail.Subject,
  342. ts)
  343. // Add extra headers
  344. var addHead string
  345. addHead += "Delivered-To: " + to + "\r\n"
  346. addHead += "Received: from " + payload.mail.Helo + " (" + payload.mail.Helo + " [" + payload.mail.RemoteAddress + "])\r\n"
  347. addHead += " by " + host + " with SMTP id " + hash + "@" + host + ";\r\n"
  348. addHead += " " + time.Now().Format(time.RFC1123Z) + "\r\n"
  349. // data will be compressed when printed, with addHead added to beginning
  350. data.set([]byte(addHead), &payload.mail.Data)
  351. body = "gzencode"
  352. // data will be written to redis - it implements the Stringer interface, redigo uses fmt to
  353. // print the data to redis.
  354. redisErr = redisClient.redisConnection(g.config.RedisInterface)
  355. if redisErr == nil {
  356. _, doErr := redisClient.conn.Do("SETEX", hash, g.config.RedisExpireSeconds, data)
  357. if doErr == nil {
  358. body = "redis" // the backend system will know to look in redis for the message data
  359. data.clear() // blank
  360. }
  361. } else {
  362. Log().WithError(redisErr).Warn("Error while connecting redis")
  363. }
  364. vals = []interface{}{} // clear the vals
  365. vals = append(vals,
  366. trimToLimit(to, 255),
  367. trimToLimit(payload.mail.MailFrom.String(), 255),
  368. trimToLimit(payload.mail.Subject, 255),
  369. body,
  370. data.String(),
  371. hash,
  372. trimToLimit(to, 255),
  373. payload.mail.RemoteAddress,
  374. trimToLimit(payload.mail.MailFrom.String(), 255),
  375. payload.mail.TLS)
  376. feeder <- vals
  377. payload.notifyMe <- &notifyMsg{nil, hash}
  378. }
  379. }
  380. func (c *redisClient) redisConnection(redisInterface string) (err error) {
  381. if c.isConnected == false {
  382. c.conn, err = redis.Dial("tcp", redisInterface)
  383. if err != nil {
  384. // handle error
  385. return err
  386. }
  387. c.isConnected = true
  388. }
  389. return nil
  390. }
  391. // test database connection settings
  392. func (g *GuerrillaDBAndRedisBackend) testSettings() (err error) {
  393. var db *sql.DB
  394. if db, err = g.mysqlConnect(); err != nil {
  395. err = fmt.Errorf("MySql cannot connect, check your settings: %s", err)
  396. } else {
  397. db.Close()
  398. }
  399. redisClient := &redisClient{}
  400. if redisErr := redisClient.redisConnection(g.config.RedisInterface); redisErr != nil {
  401. err = fmt.Errorf("Redis cannot connect, check your settings: %s", redisErr)
  402. }
  403. return
  404. }