p_guerrilla_db_redis.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. package backends
  2. import (
  3. "bytes"
  4. "compress/zlib"
  5. "database/sql"
  6. "fmt"
  7. "io"
  8. "math/rand"
  9. "runtime/debug"
  10. "strings"
  11. "sync"
  12. "time"
  13. "github.com/flashmob/go-guerrilla/mail"
  14. )
  15. // ----------------------------------------------------------------------------------
  16. // Processor Name: GuerrillaRedisDB
  17. // ----------------------------------------------------------------------------------
  18. // Description : Saves the body to redis, meta data to SQL. Example only.
  19. // : Limitation: it doesn't save multiple recipients or validate them
  20. // ----------------------------------------------------------------------------------
  21. // Config Options: ...
  22. // --------------:-------------------------------------------------------------------
  23. // Input : envelope
  24. // ----------------------------------------------------------------------------------
  25. // Output :
  26. // ----------------------------------------------------------------------------------
  27. func init() {
  28. processors["guerrillaredisdb"] = func() Decorator {
  29. return GuerrillaDbRedis()
  30. }
  31. }
  32. var queryBatcherId = 0
  33. // how many rows to batch at a time
  34. const GuerrillaDBAndRedisBatchMax = 50
  35. // tick on every...
  36. const GuerrillaDBAndRedisBatchTimeout = time.Second * 3
  37. type GuerrillaDBAndRedisBackend struct {
  38. config *guerrillaDBAndRedisConfig
  39. batcherWg sync.WaitGroup
  40. // cache prepared queries
  41. cache stmtCache
  42. batcherStoppers []chan bool
  43. }
  44. // statement cache. It's an array, not slice
  45. type stmtCache [GuerrillaDBAndRedisBatchMax]*sql.Stmt
  46. type guerrillaDBAndRedisConfig struct {
  47. NumberOfWorkers int `json:"save_workers_size"`
  48. Table string `json:"mail_table"`
  49. Driver string `json:"sql_driver"`
  50. DSN string `json:"sql_dsn"`
  51. RedisExpireSeconds int `json:"redis_expire_seconds"`
  52. RedisInterface string `json:"redis_interface"`
  53. PrimaryHost string `json:"primary_mail_host"`
  54. BatchTimeout int `json:"redis_sql_batch_timeout,omitempty"`
  55. }
  56. // Load the backend config for the backend. It has already been unmarshalled
  57. // from the main config file 'backend' config "backend_config"
  58. // Now we need to convert each type and copy into the guerrillaDBAndRedisConfig struct
  59. func (g *GuerrillaDBAndRedisBackend) loadConfig(backendConfig BackendConfig) (err error) {
  60. configType := BaseConfig(&guerrillaDBAndRedisConfig{})
  61. bcfg, err := Svc.ExtractConfig(backendConfig, configType)
  62. if err != nil {
  63. return err
  64. }
  65. m := bcfg.(*guerrillaDBAndRedisConfig)
  66. g.config = m
  67. return nil
  68. }
  69. func (g *GuerrillaDBAndRedisBackend) getNumberOfWorkers() int {
  70. return g.config.NumberOfWorkers
  71. }
  72. type redisClient struct {
  73. isConnected bool
  74. conn RedisConn
  75. time int
  76. }
  77. // compressedData struct will be compressed using zlib when printed via fmt
  78. type compressedData struct {
  79. extraHeaders []byte
  80. data *bytes.Buffer
  81. pool *sync.Pool
  82. }
  83. // newCompressedData returns a new CompressedData
  84. func newCompressedData() *compressedData {
  85. var p = sync.Pool{
  86. New: func() interface{} {
  87. var b bytes.Buffer
  88. return &b
  89. },
  90. }
  91. return &compressedData{
  92. pool: &p,
  93. }
  94. }
  95. // Set the extraheaders and buffer of data to compress
  96. func (c *compressedData) set(b []byte, d *bytes.Buffer) {
  97. c.extraHeaders = b
  98. c.data = d
  99. }
  100. // implement Stringer interface
  101. func (c *compressedData) String() string {
  102. if c.data == nil {
  103. return ""
  104. }
  105. //borrow a buffer form the pool
  106. b := c.pool.Get().(*bytes.Buffer)
  107. // put back in the pool
  108. defer func() {
  109. b.Reset()
  110. c.pool.Put(b)
  111. }()
  112. var r *bytes.Reader
  113. w, _ := zlib.NewWriterLevel(b, zlib.BestSpeed)
  114. r = bytes.NewReader(c.extraHeaders)
  115. io.Copy(w, r)
  116. io.Copy(w, c.data)
  117. w.Close()
  118. return b.String()
  119. }
  120. // clear it, without clearing the pool
  121. func (c *compressedData) clear() {
  122. c.extraHeaders = []byte{}
  123. c.data = nil
  124. }
  125. // prepares the sql query with the number of rows that can be batched with it
  126. func (g *GuerrillaDBAndRedisBackend) prepareInsertQuery(rows int, db *sql.DB) *sql.Stmt {
  127. if rows == 0 {
  128. panic("rows argument cannot be 0")
  129. }
  130. if g.cache[rows-1] != nil {
  131. return g.cache[rows-1]
  132. }
  133. sqlstr := "INSERT INTO " + g.config.Table + " "
  134. sqlstr += "(`date`, `to`, `from`, `subject`, `body`, `charset`, `mail`, `spam_score`, `hash`, `content_type`, `recipient`, `has_attach`, `ip_addr`, `return_path`, `is_tls`)"
  135. sqlstr += " values "
  136. values := "(NOW(), ?, ?, ?, ? , 'UTF-8' , ?, 0, ?, '', ?, 0, ?, ?, ?)"
  137. // add more rows
  138. comma := ""
  139. for i := 0; i < rows; i++ {
  140. sqlstr += comma + values
  141. if comma == "" {
  142. comma = ","
  143. }
  144. }
  145. stmt, sqlErr := db.Prepare(sqlstr)
  146. if sqlErr != nil {
  147. Log().WithError(sqlErr).Fatalf("failed while db.Prepare(INSERT...)")
  148. }
  149. // cache it
  150. g.cache[rows-1] = stmt
  151. return stmt
  152. }
  153. func (g *GuerrillaDBAndRedisBackend) doQuery(c int, db *sql.DB, insertStmt *sql.Stmt, vals *[]interface{}) error {
  154. var execErr error
  155. defer func() {
  156. if r := recover(); r != nil {
  157. //logln(1, fmt.Sprintf("Recovered in %v", r))
  158. Log().Error("Recovered form panic:", r, string(debug.Stack()))
  159. sum := 0
  160. for _, v := range *vals {
  161. if str, ok := v.(string); ok {
  162. sum = sum + len(str)
  163. }
  164. }
  165. Log().Errorf("panic while inserting query [%s] size:%d, err %v", r, sum, execErr)
  166. panic("query failed")
  167. }
  168. }()
  169. // prepare the query used to insert when rows reaches batchMax
  170. insertStmt = g.prepareInsertQuery(c, db)
  171. _, execErr = insertStmt.Exec(*vals...)
  172. //if rand.Intn(2) == 1 {
  173. // return errors.New("uggabooka")
  174. //}
  175. if execErr != nil {
  176. Log().WithError(execErr).Error("There was a problem the insert")
  177. }
  178. return execErr
  179. }
  180. // Batches the rows from the feeder chan in to a single INSERT statement.
  181. // Execute the batches query when:
  182. // - number of batched rows reaches a threshold, i.e. count n = threshold
  183. // - or, no new rows within a certain time, i.e. times out
  184. // The goroutine can either exit if there's a panic or feeder channel closes
  185. // it returns feederOk which signals if the feeder chanel was ok (still open) while returning
  186. // if it feederOk is false, then it means the feeder chanel is closed
  187. func (g *GuerrillaDBAndRedisBackend) insertQueryBatcher(
  188. feeder feedChan,
  189. db *sql.DB,
  190. batcherId int,
  191. stop chan bool) (feederOk bool) {
  192. // controls shutdown
  193. defer g.batcherWg.Done()
  194. g.batcherWg.Add(1)
  195. // vals is where values are batched to
  196. var vals []interface{}
  197. // how many rows were batched
  198. count := 0
  199. // The timer will tick x seconds.
  200. // Interrupting the select clause when there's no data on the feeder channel
  201. timeo := GuerrillaDBAndRedisBatchTimeout
  202. if g.config.BatchTimeout > 0 {
  203. timeo = time.Duration(g.config.BatchTimeout)
  204. }
  205. t := time.NewTimer(timeo)
  206. // prepare the query used to insert when rows reaches batchMax
  207. insertStmt := g.prepareInsertQuery(GuerrillaDBAndRedisBatchMax, db)
  208. // inserts executes a batched insert query, clears the vals and resets the count
  209. inserter := func(c int) {
  210. if c > 0 {
  211. err := g.doQuery(c, db, insertStmt, &vals)
  212. if err != nil {
  213. // maybe connection prob?
  214. // retry the sql query
  215. attempts := 3
  216. for i := 0; i < attempts; i++ {
  217. Log().Infof("retrying query query rows[%c] ", c)
  218. time.Sleep(time.Second)
  219. err = g.doQuery(c, db, insertStmt, &vals)
  220. if err == nil {
  221. continue
  222. }
  223. }
  224. }
  225. }
  226. vals = nil
  227. count = 0
  228. }
  229. rand.Seed(time.Now().UnixNano())
  230. defer func() {
  231. if r := recover(); r != nil {
  232. Log().Error("insertQueryBatcher caught a panic", r, string(debug.Stack()))
  233. }
  234. }()
  235. // Keep getting values from feeder and add to batch.
  236. // if feeder times out, execute the batched query
  237. // otherwise, execute the batched query once it reaches the GuerrillaDBAndRedisBatchMax threshold
  238. feederOk = true
  239. for {
  240. select {
  241. // it may panic when reading on a closed feeder channel. feederOK detects if it was closed
  242. case <-stop:
  243. Log().Infof("MySQL query batcher stopped (#%d)", batcherId)
  244. // Insert any remaining rows
  245. inserter(count)
  246. feederOk = false
  247. close(feeder)
  248. return
  249. case row := <-feeder:
  250. vals = append(vals, row...)
  251. count++
  252. Log().Debug("new feeder row:", row, " cols:", len(row), " count:", count, " worker", batcherId)
  253. if count >= GuerrillaDBAndRedisBatchMax {
  254. inserter(GuerrillaDBAndRedisBatchMax)
  255. }
  256. // stop timer from firing (reset the interrupt)
  257. if !t.Stop() {
  258. // darin the timer
  259. <-t.C
  260. }
  261. t.Reset(timeo)
  262. case <-t.C:
  263. // anything to insert?
  264. if n := len(vals); n > 0 {
  265. inserter(count)
  266. }
  267. t.Reset(timeo)
  268. }
  269. }
  270. }
  271. func trimToLimit(str string, limit int) string {
  272. ret := strings.TrimSpace(str)
  273. if len(str) > limit {
  274. ret = str[:limit]
  275. }
  276. return ret
  277. }
  278. func (g *GuerrillaDBAndRedisBackend) sqlConnect() (*sql.DB, error) {
  279. tOut := GuerrillaDBAndRedisBatchTimeout
  280. if g.config.BatchTimeout > 0 {
  281. tOut = time.Duration(g.config.BatchTimeout)
  282. }
  283. tOut += 10
  284. // don't go to 30 sec or more
  285. if tOut >= 30 {
  286. tOut = 29
  287. }
  288. if db, err := sql.Open(g.config.Driver, g.config.DSN); err != nil {
  289. Log().Error("cannot open database", err, "]")
  290. return nil, err
  291. } else {
  292. // do we have access?
  293. _, err = db.Query("SELECT mail_id FROM " + g.config.Table + " LIMIT 1")
  294. if err != nil {
  295. Log().Error("cannot select table:", err)
  296. return nil, err
  297. }
  298. return db, nil
  299. }
  300. }
  301. func (c *redisClient) redisConnection(redisInterface string) (err error) {
  302. if c.isConnected == false {
  303. c.conn, err = RedisDialer("tcp", redisInterface)
  304. if err != nil {
  305. // handle error
  306. return err
  307. }
  308. c.isConnected = true
  309. }
  310. return nil
  311. }
  312. type feedChan chan []interface{}
  313. // GuerrillaDbRedis is a specialized processor for Guerrilla mail. It is here as an example.
  314. // It's an example of a 'monolithic' processor.
  315. func GuerrillaDbRedis() Decorator {
  316. g := GuerrillaDBAndRedisBackend{}
  317. redisClient := &redisClient{}
  318. var db *sql.DB
  319. var to, body string
  320. var redisErr error
  321. var feeders []feedChan
  322. g.batcherStoppers = make([]chan bool, 0)
  323. Svc.AddInitializer(InitializeWith(func(backendConfig BackendConfig) error {
  324. configType := BaseConfig(&guerrillaDBAndRedisConfig{})
  325. bcfg, err := Svc.ExtractConfig(backendConfig, configType)
  326. if err != nil {
  327. return err
  328. }
  329. g.config = bcfg.(*guerrillaDBAndRedisConfig)
  330. db, err = g.sqlConnect()
  331. if err != nil {
  332. return err
  333. }
  334. queryBatcherId++
  335. // start the query SQL batching where we will send data via the feeder channel
  336. stop := make(chan bool)
  337. feeder := make(feedChan, 1)
  338. go func(qbID int, stop chan bool) {
  339. // we loop so that if insertQueryBatcher panics, it can recover and go in again
  340. for {
  341. if feederOK := g.insertQueryBatcher(feeder, db, qbID, stop); !feederOK {
  342. Log().Debugf("insertQueryBatcher exited (#%d)", qbID)
  343. return
  344. }
  345. Log().Debug("resuming insertQueryBatcher")
  346. }
  347. }(queryBatcherId, stop)
  348. g.batcherStoppers = append(g.batcherStoppers, stop)
  349. feeders = append(feeders, feeder)
  350. return nil
  351. }))
  352. Svc.AddShutdowner(ShutdownWith(func() error {
  353. db.Close()
  354. Log().Infof("closed sql")
  355. if redisClient.conn != nil {
  356. Log().Infof("closed redis")
  357. redisClient.conn.Close()
  358. }
  359. // send a close signal to all query batchers to exit.
  360. for i := range g.batcherStoppers {
  361. g.batcherStoppers[i] <- true
  362. }
  363. g.batcherWg.Wait()
  364. return nil
  365. }))
  366. var vals []interface{}
  367. data := newCompressedData()
  368. return func(p Processor) Processor {
  369. return ProcessWith(func(e *mail.Envelope, task SelectTask) (Result, error) {
  370. if task == TaskSaveMail {
  371. Log().Debug("Got mail from chan,", e.RemoteIP)
  372. to = trimToLimit(strings.TrimSpace(e.RcptTo[0].User)+"@"+g.config.PrimaryHost, 255)
  373. e.Helo = trimToLimit(e.Helo, 255)
  374. e.RcptTo[0].Host = trimToLimit(e.RcptTo[0].Host, 255)
  375. ts := fmt.Sprintf("%d", time.Now().UnixNano())
  376. e.ParseHeaders()
  377. hash := MD5Hex(
  378. to,
  379. e.MailFrom.String(),
  380. e.Subject,
  381. ts)
  382. e.QueuedId = hash
  383. // Add extra headers
  384. var addHead string
  385. addHead += "Delivered-To: " + to + "\r\n"
  386. addHead += "Received: from " + e.Helo + " (" + e.Helo + " [" + e.RemoteIP + "])\r\n"
  387. addHead += " by " + e.RcptTo[0].Host + " with SMTP id " + hash + "@" + e.RcptTo[0].Host + ";\r\n"
  388. addHead += " " + time.Now().Format(time.RFC1123Z) + "\r\n"
  389. // data will be compressed when printed, with addHead added to beginning
  390. data.set([]byte(addHead), &e.Data)
  391. body = "gzencode"
  392. // data will be written to redis - it implements the Stringer interface, redigo uses fmt to
  393. // print the data to redis.
  394. redisErr = redisClient.redisConnection(g.config.RedisInterface)
  395. if redisErr == nil {
  396. _, doErr := redisClient.conn.Do("SETEX", hash, g.config.RedisExpireSeconds, data)
  397. if doErr == nil {
  398. body = "redis" // the backend system will know to look in redis for the message data
  399. data.clear() // blank
  400. }
  401. } else {
  402. Log().WithError(redisErr).Warn("Error while connecting redis")
  403. }
  404. vals = []interface{}{} // clear the vals
  405. vals = append(vals,
  406. trimToLimit(to, 255),
  407. trimToLimit(e.MailFrom.String(), 255),
  408. trimToLimit(e.Subject, 255),
  409. body,
  410. data.String(),
  411. hash,
  412. trimToLimit(to, 255),
  413. e.RemoteIP,
  414. trimToLimit(e.MailFrom.String(), 255),
  415. e.TLS)
  416. // give the values to a random query batcher
  417. feeders[rand.Intn(len(feeders))] <- vals
  418. return p.Process(e, task)
  419. } else {
  420. return p.Process(e, task)
  421. }
  422. })
  423. }
  424. }