p_guerrilla_db_redis.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. package backends
  2. import (
  3. "bytes"
  4. "compress/zlib"
  5. "database/sql"
  6. "fmt"
  7. "github.com/flashmob/go-guerrilla/mail"
  8. "github.com/garyburd/redigo/redis"
  9. "github.com/go-sql-driver/mysql"
  10. "io"
  11. "runtime/debug"
  12. "strings"
  13. "sync"
  14. "time"
  15. )
  16. // ----------------------------------------------------------------------------------
  17. // Processor Name: Guerrilla-reds-db
  18. // ----------------------------------------------------------------------------------
  19. // Description : Saves the body to redis, meta data to mysql. Example
  20. // ----------------------------------------------------------------------------------
  21. // Config Options: ...
  22. // --------------:-------------------------------------------------------------------
  23. // Input : envelope
  24. // ----------------------------------------------------------------------------------
  25. // Output :
  26. // ----------------------------------------------------------------------------------
  27. func init() {
  28. processors["GuerrillaRedisDB"] = func() Decorator {
  29. return GuerrillaDbReddis()
  30. }
  31. }
  32. // how many rows to batch at a time
  33. const GuerrillaDBAndRedisBatchMax = 2
  34. // tick on every...
  35. const GuerrillaDBAndRedisBatchTimeout = time.Second * 3
  36. type GuerrillaDBAndRedisBackend struct {
  37. config *guerrillaDBAndRedisConfig
  38. batcherWg sync.WaitGroup
  39. // cache prepared queries
  40. cache stmtCache
  41. }
  42. // statement cache. It's an array, not slice
  43. type stmtCache [GuerrillaDBAndRedisBatchMax]*sql.Stmt
  44. type guerrillaDBAndRedisConfig struct {
  45. NumberOfWorkers int `json:"save_workers_size"`
  46. MysqlTable string `json:"mail_table"`
  47. MysqlDB string `json:"mysql_db"`
  48. MysqlHost string `json:"mysql_host"`
  49. MysqlPass string `json:"mysql_pass"`
  50. MysqlUser string `json:"mysql_user"`
  51. RedisExpireSeconds int `json:"redis_expire_seconds"`
  52. RedisInterface string `json:"redis_interface"`
  53. PrimaryHost string `json:"primary_mail_host"`
  54. }
  55. // Load the backend config for the backend. It has already been unmarshalled
  56. // from the main config file 'backend' config "backend_config"
  57. // Now we need to convert each type and copy into the guerrillaDBAndRedisConfig struct
  58. func (g *GuerrillaDBAndRedisBackend) loadConfig(backendConfig BackendConfig) (err error) {
  59. configType := BaseConfig(&guerrillaDBAndRedisConfig{})
  60. bcfg, err := Svc.ExtractConfig(backendConfig, configType)
  61. if err != nil {
  62. return err
  63. }
  64. m := bcfg.(*guerrillaDBAndRedisConfig)
  65. g.config = m
  66. return nil
  67. }
  68. func (g *GuerrillaDBAndRedisBackend) getNumberOfWorkers() int {
  69. return g.config.NumberOfWorkers
  70. }
  71. type redisClient struct {
  72. isConnected bool
  73. conn redis.Conn
  74. time int
  75. }
  76. // compressedData struct will be compressed using zlib when printed via fmt
  77. type compressedData struct {
  78. extraHeaders []byte
  79. data *bytes.Buffer
  80. pool *sync.Pool
  81. }
  82. // newCompressedData returns a new CompressedData
  83. func newCompressedData() *compressedData {
  84. var p = sync.Pool{
  85. New: func() interface{} {
  86. var b bytes.Buffer
  87. return &b
  88. },
  89. }
  90. return &compressedData{
  91. pool: &p,
  92. }
  93. }
  94. // Set the extraheaders and buffer of data to compress
  95. func (c *compressedData) set(b []byte, d *bytes.Buffer) {
  96. c.extraHeaders = b
  97. c.data = d
  98. }
  99. // implement Stringer interface
  100. func (c *compressedData) String() string {
  101. if c.data == nil {
  102. return ""
  103. }
  104. //borrow a buffer form the pool
  105. b := c.pool.Get().(*bytes.Buffer)
  106. // put back in the pool
  107. defer func() {
  108. b.Reset()
  109. c.pool.Put(b)
  110. }()
  111. var r *bytes.Reader
  112. w, _ := zlib.NewWriterLevel(b, zlib.BestSpeed)
  113. r = bytes.NewReader(c.extraHeaders)
  114. io.Copy(w, r)
  115. io.Copy(w, c.data)
  116. w.Close()
  117. return b.String()
  118. }
  119. // clear it, without clearing the pool
  120. func (c *compressedData) clear() {
  121. c.extraHeaders = []byte{}
  122. c.data = nil
  123. }
  124. // prepares the sql query with the number of rows that can be batched with it
  125. func (g *GuerrillaDBAndRedisBackend) prepareInsertQuery(rows int, db *sql.DB) *sql.Stmt {
  126. if rows == 0 {
  127. panic("rows argument cannot be 0")
  128. }
  129. if g.cache[rows-1] != nil {
  130. return g.cache[rows-1]
  131. }
  132. sqlstr := "INSERT INTO " + g.config.MysqlTable + " "
  133. sqlstr += "(`date`, `to`, `from`, `subject`, `body`, `charset`, `mail`, `spam_score`, `hash`, `content_type`, `recipient`, `has_attach`, `ip_addr`, `return_path`, `is_tls`)"
  134. sqlstr += " values "
  135. values := "(NOW(), ?, ?, ?, ? , 'UTF-8' , ?, 0, ?, '', ?, 0, ?, ?, ?)"
  136. // add more rows
  137. comma := ""
  138. for i := 0; i < rows; i++ {
  139. sqlstr += comma + values
  140. if comma == "" {
  141. comma = ","
  142. }
  143. }
  144. stmt, sqlErr := db.Prepare(sqlstr)
  145. if sqlErr != nil {
  146. Log().WithError(sqlErr).Fatalf("failed while db.Prepare(INSERT...)")
  147. }
  148. // cache it
  149. g.cache[rows-1] = stmt
  150. return stmt
  151. }
  152. func (g *GuerrillaDBAndRedisBackend) doQuery(c int, db *sql.DB, insertStmt *sql.Stmt, vals *[]interface{}) {
  153. var execErr error
  154. defer func() {
  155. if r := recover(); r != nil {
  156. //logln(1, fmt.Sprintf("Recovered in %v", r))
  157. Log().Error("Recovered form panic:", r, string(debug.Stack()))
  158. sum := 0
  159. for _, v := range *vals {
  160. if str, ok := v.(string); ok {
  161. sum = sum + len(str)
  162. }
  163. }
  164. Log().Errorf("panic while inserting query [%s] size:%d, err %v", r, sum, execErr)
  165. panic("query failed")
  166. }
  167. }()
  168. // prepare the query used to insert when rows reaches batchMax
  169. insertStmt = g.prepareInsertQuery(c, db)
  170. _, execErr = insertStmt.Exec(*vals...)
  171. if execErr != nil {
  172. Log().WithError(execErr).Error("There was a problem the insert")
  173. }
  174. }
  175. // Batches the rows from the feeder chan in to a single INSERT statement.
  176. // Execute the batches query when:
  177. // - number of batched rows reaches a threshold, i.e. count n = threshold
  178. // - or, no new rows within a certain time, i.e. times out
  179. // The goroutine can either exit if there's a panic or feeder channel closes
  180. // it returns feederOk which signals if the feeder chanel was ok (still open) while returning
  181. // if it feederOk is false, then it means the feeder chanel is closed
  182. func (g *GuerrillaDBAndRedisBackend) insertQueryBatcher(feeder chan []interface{}, db *sql.DB) (feederOk bool) {
  183. // controls shutdown
  184. defer g.batcherWg.Done()
  185. g.batcherWg.Add(1)
  186. // vals is where values are batched to
  187. var vals []interface{}
  188. // how many rows were batched
  189. count := 0
  190. // The timer will tick every second.
  191. // Interrupting the select clause when there's no data on the feeder channel
  192. t := time.NewTimer(GuerrillaDBAndRedisBatchTimeout)
  193. // prepare the query used to insert when rows reaches batchMax
  194. insertStmt := g.prepareInsertQuery(GuerrillaDBAndRedisBatchMax, db)
  195. // inserts executes a batched insert query, clears the vals and resets the count
  196. insert := func(c int) {
  197. if c > 0 {
  198. g.doQuery(c, db, insertStmt, &vals)
  199. }
  200. vals = nil
  201. count = 0
  202. }
  203. defer func() {
  204. if r := recover(); r != nil {
  205. Log().Error("insertQueryBatcher caught a panic", r)
  206. }
  207. }()
  208. // Keep getting values from feeder and add to batch.
  209. // if feeder times out, execute the batched query
  210. // otherwise, execute the batched query once it reaches the GuerrillaDBAndRedisBatchMax threshold
  211. feederOk = true
  212. for {
  213. select {
  214. // it may panic when reading on a closed feeder channel. feederOK detects if it was closed
  215. case row, feederOk := <-feeder:
  216. if row == nil {
  217. Log().Info("Query batchaer exiting")
  218. // Insert any remaining rows
  219. insert(count)
  220. return feederOk
  221. }
  222. vals = append(vals, row...)
  223. count++
  224. Log().Debug("new feeder row:", row, " cols:", len(row), " count:", count, " worker", workerId)
  225. if count >= GuerrillaDBAndRedisBatchMax {
  226. insert(GuerrillaDBAndRedisBatchMax)
  227. }
  228. // stop timer from firing (reset the interrupt)
  229. if !t.Stop() {
  230. <-t.C
  231. }
  232. t.Reset(GuerrillaDBAndRedisBatchTimeout)
  233. case <-t.C:
  234. // anything to insert?
  235. if n := len(vals); n > 0 {
  236. insert(count)
  237. }
  238. t.Reset(GuerrillaDBAndRedisBatchTimeout)
  239. }
  240. }
  241. }
  242. func trimToLimit(str string, limit int) string {
  243. ret := strings.TrimSpace(str)
  244. if len(str) > limit {
  245. ret = str[:limit]
  246. }
  247. return ret
  248. }
  249. func (g *GuerrillaDBAndRedisBackend) mysqlConnect() (*sql.DB, error) {
  250. conf := mysql.Config{
  251. User: g.config.MysqlUser,
  252. Passwd: g.config.MysqlPass,
  253. DBName: g.config.MysqlDB,
  254. Net: "tcp",
  255. Addr: g.config.MysqlHost,
  256. ReadTimeout: GuerrillaDBAndRedisBatchTimeout + (time.Second * 10),
  257. WriteTimeout: GuerrillaDBAndRedisBatchTimeout + (time.Second * 10),
  258. Params: map[string]string{"collation": "utf8_general_ci"},
  259. }
  260. if db, err := sql.Open("mysql", conf.FormatDSN()); err != nil {
  261. Log().Error("cannot open mysql", err)
  262. return nil, err
  263. } else {
  264. return db, nil
  265. }
  266. }
  267. func (c *redisClient) redisConnection(redisInterface string) (err error) {
  268. if c.isConnected == false {
  269. c.conn, err = redis.Dial("tcp", redisInterface)
  270. if err != nil {
  271. // handle error
  272. return err
  273. }
  274. c.isConnected = true
  275. }
  276. return nil
  277. }
  278. var workerId = 0
  279. // GuerrillaDbReddis is a specialized processor for Guerrilla mail. It is here as an example.
  280. // It's an example of a 'monolithic' processor.
  281. func GuerrillaDbReddis() Decorator {
  282. g := GuerrillaDBAndRedisBackend{}
  283. redisClient := &redisClient{}
  284. var db *sql.DB
  285. var to, body string
  286. var redisErr error
  287. Svc.AddInitializer(InitializeWith(func(backendConfig BackendConfig) error {
  288. configType := BaseConfig(&guerrillaDBAndRedisConfig{})
  289. bcfg, err := Svc.ExtractConfig(backendConfig, configType)
  290. if err != nil {
  291. return err
  292. }
  293. g.config = bcfg.(*guerrillaDBAndRedisConfig)
  294. db, err = g.mysqlConnect()
  295. if err != nil {
  296. Log().Fatalf("cannot open mysql: %s", err)
  297. }
  298. return nil
  299. }))
  300. workerId++
  301. // start the query SQL batching where we will send data via the feeder channel
  302. feeder := make(chan []interface{}, 1)
  303. go func() {
  304. for {
  305. if feederOK := g.insertQueryBatcher(feeder, db); !feederOK {
  306. Log().Debug("insertQueryBatcher exited")
  307. return
  308. }
  309. // if insertQueryBatcher panics, it can recover and go in again
  310. Log().Debug("resuming insertQueryBatcher")
  311. }
  312. }()
  313. defer func() {
  314. if r := recover(); r != nil {
  315. //recover form closed channel
  316. Log().Error("panic recovered in saveMailWorker", r)
  317. }
  318. db.Close()
  319. if redisClient.conn != nil {
  320. Log().Infof("closed redis")
  321. redisClient.conn.Close()
  322. }
  323. // close the feeder & wait for query batcher to exit.
  324. close(feeder)
  325. g.batcherWg.Wait()
  326. }()
  327. var vals []interface{}
  328. data := newCompressedData()
  329. return func(c Processor) Processor {
  330. return ProcessWith(func(e *mail.Envelope, task SelectTask) (Result, error) {
  331. if task == TaskSaveMail {
  332. Log().Debug("Got mail from chan", e.RemoteIP)
  333. to = trimToLimit(strings.TrimSpace(e.RcptTo[0].User)+"@"+g.config.PrimaryHost, 255)
  334. e.Helo = trimToLimit(e.Helo, 255)
  335. e.RcptTo[0].Host = trimToLimit(e.RcptTo[0].Host, 255)
  336. ts := fmt.Sprintf("%d", time.Now().UnixNano())
  337. e.ParseHeaders()
  338. hash := MD5Hex(
  339. to,
  340. e.MailFrom.String(),
  341. e.Subject,
  342. ts)
  343. // Add extra headers
  344. var addHead string
  345. addHead += "Delivered-To: " + to + "\r\n"
  346. addHead += "Received: from " + e.Helo + " (" + e.Helo + " [" + e.RemoteIP + "])\r\n"
  347. addHead += " by " + e.RcptTo[0].Host + " with SMTP id " + hash + "@" + e.RcptTo[0].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), &e.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(e.MailFrom.String(), 255),
  368. trimToLimit(e.Subject, 255),
  369. body,
  370. data.String(),
  371. hash,
  372. trimToLimit(to, 255),
  373. e.RemoteIP,
  374. trimToLimit(e.MailFrom.String(), 255),
  375. e.TLS)
  376. return c.Process(e, task)
  377. } else {
  378. return c.Process(e, task)
  379. }
  380. })
  381. }
  382. }