gateway.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  1. package backends
  2. import (
  3. "errors"
  4. "fmt"
  5. "io"
  6. "strconv"
  7. "sync"
  8. "time"
  9. "github.com/flashmob/go-guerrilla/log"
  10. "github.com/flashmob/go-guerrilla/mail"
  11. "github.com/flashmob/go-guerrilla/response"
  12. "runtime/debug"
  13. "strings"
  14. )
  15. var ErrProcessorNotFound error
  16. // A backend gateway is a proxy that implements the Backend interface.
  17. // It is used to start multiple goroutine workers for saving mail, and then distribute email saving to the workers
  18. // via a channel. Shutting down via Shutdown() will stop all workers.
  19. // The rest of this program always talks to the backend via this gateway.
  20. type BackendGateway struct {
  21. // channel for distributing envelopes to workers
  22. conveyor chan *workerMsg
  23. // waits for backend workers to start/stop
  24. wg sync.WaitGroup
  25. workStoppers []chan bool
  26. processors []Processor
  27. validators []Processor
  28. streamers []streamer
  29. // controls access to state
  30. sync.Mutex
  31. State backendState
  32. config BackendConfig
  33. gwConfig *GatewayConfig
  34. }
  35. type GatewayConfig struct {
  36. // WorkersSize controls how many concurrent workers to start. Defaults to 1
  37. WorkersSize int `json:"save_workers_size,omitempty"`
  38. // SaveProcess controls which processors to chain in a stack for saving email tasks
  39. SaveProcess string `json:"save_process,omitempty"`
  40. // ValidateProcess is like ProcessorStack, but for recipient validation tasks
  41. ValidateProcess string `json:"validate_process,omitempty"`
  42. // TimeoutSave is duration before timeout when saving an email, eg "29s"
  43. TimeoutSave string `json:"gw_save_timeout,omitempty"`
  44. // TimeoutValidateRcpt duration before timeout when validating a recipient, eg "1s"
  45. TimeoutValidateRcpt string `json:"gw_val_rcpt_timeout,omitempty"`
  46. // StreamSaveProcess is same as a ProcessorStack, but reads from an io.Reader to write email data
  47. StreamSaveProcess string `json:"stream_save_process,omitempty"`
  48. }
  49. // workerMsg is what get placed on the BackendGateway.saveMailChan channel
  50. type workerMsg struct {
  51. // The email data
  52. e *mail.Envelope
  53. // notifyMe is used to notify the gateway of workers finishing their processing
  54. notifyMe chan *notifyMsg
  55. // select the task type
  56. task SelectTask
  57. // io.Reader for streamed processor
  58. r io.Reader
  59. }
  60. type streamer struct {
  61. // StreamProcessor is a chain of StreamProcessor
  62. sp StreamProcessor
  63. // so that we can call Open and Close
  64. d []StreamDecorator
  65. }
  66. func (s streamer) Write(p []byte) (n int, err error) {
  67. return s.sp.Write(p)
  68. }
  69. func (s *streamer) open(e *mail.Envelope) Errors {
  70. var err Errors
  71. for i := range s.d {
  72. if s.d[i].Open != nil {
  73. if e := s.d[i].Open(e); e != nil {
  74. err = append(err, e)
  75. }
  76. }
  77. }
  78. return err
  79. }
  80. func (s *streamer) close() Errors {
  81. var err Errors
  82. for i := range s.d {
  83. if s.d[i].Close != nil {
  84. if e := s.d[i].Close(); e != nil {
  85. err = append(err, e)
  86. }
  87. }
  88. }
  89. return err
  90. }
  91. type backendState int
  92. // possible values for state
  93. const (
  94. BackendStateNew backendState = iota
  95. BackendStateRunning
  96. BackendStateShuttered
  97. BackendStateError
  98. BackendStateInitialized
  99. // default timeout for saving email, if 'gw_save_timeout' not present in config
  100. saveTimeout = time.Second * 30
  101. // default timeout for validating rcpt to, if 'gw_val_rcpt_timeout' not present in config
  102. validateRcptTimeout = time.Second * 5
  103. defaultProcessor = "Debugger"
  104. )
  105. func (s backendState) String() string {
  106. switch s {
  107. case BackendStateNew:
  108. return "NewState"
  109. case BackendStateRunning:
  110. return "RunningState"
  111. case BackendStateShuttered:
  112. return "ShutteredState"
  113. case BackendStateError:
  114. return "ErrorSate"
  115. case BackendStateInitialized:
  116. return "InitializedState"
  117. }
  118. return strconv.Itoa(int(s))
  119. }
  120. // New makes a new default BackendGateway backend, and initializes it using
  121. // backendConfig and stores the logger
  122. func New(backendConfig BackendConfig, l log.Logger) (Backend, error) {
  123. Svc.SetMainlog(l)
  124. gateway := &BackendGateway{}
  125. err := gateway.Initialize(backendConfig)
  126. if err != nil {
  127. return nil, fmt.Errorf("error while initializing the backend: %s", err)
  128. }
  129. // keep the config known to be good.
  130. gateway.config = backendConfig
  131. b = Backend(gateway)
  132. return b, nil
  133. }
  134. var workerMsgPool = sync.Pool{
  135. // if not available, then create a new one
  136. New: func() interface{} {
  137. return &workerMsg{}
  138. },
  139. }
  140. // reset resets a workerMsg that has been borrowed from the pool
  141. func (w *workerMsg) reset(e *mail.Envelope, task SelectTask) {
  142. if w.notifyMe == nil {
  143. w.notifyMe = make(chan *notifyMsg)
  144. }
  145. w.e = e
  146. w.task = task
  147. }
  148. // Process distributes an envelope to one of the backend workers with a TaskSaveMail task
  149. func (gw *BackendGateway) Process(e *mail.Envelope) Result {
  150. if gw.State != BackendStateRunning {
  151. return NewResult(response.Canned.FailBackendNotRunning, response.SP, gw.State)
  152. }
  153. // borrow a workerMsg from the pool
  154. workerMsg := workerMsgPool.Get().(*workerMsg)
  155. defer workerMsgPool.Put(workerMsg)
  156. workerMsg.reset(e, TaskSaveMail)
  157. // place on the channel so that one of the save mail workers can pick it up
  158. gw.conveyor <- workerMsg
  159. // wait for the save to complete
  160. // or timeout
  161. select {
  162. case status := <-workerMsg.notifyMe:
  163. // email saving transaction completed
  164. if status.result == BackendResultOK && status.queuedID != "" {
  165. return NewResult(response.Canned.SuccessMessageQueued, response.SP, status.queuedID)
  166. }
  167. // A custom result, there was probably an error, if so, log it
  168. if status.result != nil {
  169. if status.err != nil {
  170. Log().Error(status.err)
  171. }
  172. return status.result
  173. }
  174. // if there was no result, but there's an error, then make a new result from the error
  175. if status.err != nil {
  176. if _, err := strconv.Atoi(status.err.Error()[:3]); err != nil {
  177. return NewResult(response.Canned.FailBackendTransaction, response.SP, status.err)
  178. }
  179. return NewResult(status.err)
  180. }
  181. // both result & error are nil (should not happen)
  182. err := errors.New("no response from backend - processor did not return a result or an error")
  183. Log().Error(err)
  184. return NewResult(response.Canned.FailBackendTransaction, response.SP, err)
  185. case <-time.After(gw.saveTimeout()):
  186. Log().Error("Backend has timed out while saving email")
  187. e.Lock() // lock the envelope - it's still processing here, we don't want the server to recycle it
  188. go func() {
  189. // keep waiting for the backend to finish processing
  190. <-workerMsg.notifyMe
  191. e.Unlock()
  192. }()
  193. return NewResult(response.Canned.FailBackendTimeout)
  194. }
  195. }
  196. // ValidateRcpt asks one of the workers to validate the recipient
  197. // Only the last recipient appended to e.RcptTo will be validated.
  198. func (gw *BackendGateway) ValidateRcpt(e *mail.Envelope) RcptError {
  199. if gw.State != BackendStateRunning {
  200. return StorageNotAvailable
  201. }
  202. if _, ok := gw.validators[0].(NoopProcessor); ok {
  203. // no validator processors configured
  204. return nil
  205. }
  206. // place on the channel so that one of the save mail workers can pick it up
  207. workerMsg := workerMsgPool.Get().(*workerMsg)
  208. defer workerMsgPool.Put(workerMsg)
  209. workerMsg.reset(e, TaskValidateRcpt)
  210. gw.conveyor <- workerMsg
  211. // wait for the validation to complete
  212. // or timeout
  213. select {
  214. case status := <-workerMsg.notifyMe:
  215. if status.err != nil {
  216. return status.err
  217. }
  218. return nil
  219. case <-time.After(gw.validateRcptTimeout()):
  220. e.Lock()
  221. go func() {
  222. <-workerMsg.notifyMe
  223. e.Unlock()
  224. Log().Error("Backend has timed out while validating rcpt")
  225. }()
  226. return StorageTimeout
  227. }
  228. }
  229. func (gw *BackendGateway) StreamOn() bool {
  230. return len(gw.gwConfig.StreamSaveProcess) != 0
  231. }
  232. func (gw *BackendGateway) ProcessStream(r io.Reader, e *mail.Envelope) (Result, error) {
  233. res := response.Canned
  234. if gw.State != BackendStateRunning {
  235. return NewResult(res.FailBackendNotRunning, response.SP, gw.State), errors.New(res.FailBackendNotRunning.String())
  236. }
  237. // borrow a workerMsg from the pool
  238. workerMsg := workerMsgPool.Get().(*workerMsg)
  239. workerMsg.reset(e, TaskSaveMailStream)
  240. workerMsg.r = r
  241. // place on the channel so that one of the save mail workers can pick it up
  242. gw.conveyor <- workerMsg
  243. // wait for the save to complete
  244. // or timeout
  245. select {
  246. case status := <-workerMsg.notifyMe:
  247. // email saving transaction completed
  248. if status.result == BackendResultOK && status.queuedID != "" {
  249. return NewResult(res.SuccessMessageQueued, response.SP, status.queuedID), status.err
  250. }
  251. // A custom result, there was probably an error, if so, log it
  252. if status.result != nil {
  253. if status.err != nil {
  254. Log().Error(status.err)
  255. }
  256. return status.result, status.err
  257. }
  258. // if there was no result, but there's an error, then make a new result from the error
  259. if status.err != nil {
  260. if _, err := strconv.Atoi(status.err.Error()[:3]); err != nil {
  261. return NewResult(res.FailBackendTransaction, response.SP, status.err), status.err
  262. }
  263. return NewResult(status.err), status.err
  264. }
  265. // both result & error are nil (should not happen)
  266. err := errors.New("no response from backend - processor did not return a result or an error")
  267. Log().Error(err)
  268. return NewResult(res.FailBackendTransaction, response.SP, err), err
  269. case <-time.After(gw.saveTimeout()):
  270. Log().Error("Backend has timed out while saving email")
  271. e.Lock() // lock the envelope - it's still processing here, we don't want the server to recycle it
  272. go func() {
  273. // keep waiting for the backend to finish processing
  274. <-workerMsg.notifyMe
  275. e.Unlock()
  276. workerMsgPool.Put(workerMsg)
  277. }()
  278. return NewResult(res.FailBackendTimeout), errors.New("gateway timeout")
  279. }
  280. }
  281. // Shutdown shuts down the backend and leaves it in BackendStateShuttered state
  282. func (gw *BackendGateway) Shutdown() error {
  283. gw.Lock()
  284. defer gw.Unlock()
  285. if gw.State != BackendStateShuttered {
  286. // send a signal to all workers
  287. gw.stopWorkers()
  288. // wait for workers to stop
  289. gw.wg.Wait()
  290. // call shutdown on all processor shutdowners
  291. if err := Svc.shutdown(); err != nil {
  292. return err
  293. }
  294. gw.State = BackendStateShuttered
  295. }
  296. return nil
  297. }
  298. // Reinitialize initializes the gateway with the existing config after it was shutdown
  299. func (gw *BackendGateway) Reinitialize() error {
  300. if gw.State != BackendStateShuttered {
  301. return errors.New("backend must be in BackendStateshuttered state to Reinitialize")
  302. }
  303. // clear the Initializers and Shutdowners
  304. Svc.reset()
  305. err := gw.Initialize(gw.config)
  306. if err != nil {
  307. fmt.Println("reinitialize to ", gw.config, err)
  308. return fmt.Errorf("error while initializing the backend: %s", err)
  309. }
  310. return err
  311. }
  312. // newStack creates a new Processor by chaining multiple Processors in a call stack
  313. // Decorators are functions of Decorator type, source files prefixed with p_*
  314. // Each decorator does a specific task during the processing stage.
  315. // This function uses the config value save_process or validate_process to figure out which Decorator to use
  316. func (gw *BackendGateway) newStack(stackConfig string) (Processor, error) {
  317. var decorators []Decorator
  318. cfg := strings.ToLower(strings.TrimSpace(stackConfig))
  319. if len(cfg) == 0 {
  320. return NoopProcessor{}, nil
  321. }
  322. items := strings.Split(cfg, "|")
  323. for i := range items {
  324. name := items[len(items)-1-i] // reverse order, since decorators are stacked
  325. if makeFunc, ok := processors[name]; ok {
  326. decorators = append(decorators, makeFunc())
  327. } else {
  328. ErrProcessorNotFound = errors.New(fmt.Sprintf("processor [%s] not found", name))
  329. return nil, ErrProcessorNotFound
  330. }
  331. }
  332. // build the call-stack of decorators
  333. p := Decorate(DefaultProcessor{}, decorators...)
  334. return p, nil
  335. }
  336. func (gw *BackendGateway) newStreamStack(stackConfig string) (streamer, error) {
  337. var decorators []StreamDecorator
  338. cfg := strings.ToLower(strings.TrimSpace(stackConfig))
  339. if len(cfg) == 0 {
  340. return streamer{NoopStreamProcessor{}, decorators}, nil
  341. }
  342. items := strings.Split(cfg, "|")
  343. for i := range items {
  344. name := items[len(items)-1-i] // reverse order, since decorators are stacked
  345. if makeFunc, ok := streamers[name]; ok {
  346. emmy := makeFunc()
  347. decorators = append(decorators, emmy)
  348. } else {
  349. ErrProcessorNotFound = errors.New(fmt.Sprintf("stream processor [%s] not found", name))
  350. return streamer{nil, decorators}, ErrProcessorNotFound
  351. }
  352. }
  353. // build the call-stack of decorators
  354. sp := DecorateStream(DefaultStreamProcessor{}, decorators...)
  355. return streamer{sp, decorators}, nil
  356. }
  357. // loadConfig loads the config for the GatewayConfig
  358. func (gw *BackendGateway) loadConfig(cfg BackendConfig) error {
  359. configType := BaseConfig(&GatewayConfig{})
  360. // Note: treat config values as immutable
  361. // if you need to change a config value, change in the file then
  362. // send a SIGHUP
  363. bcfg, err := Svc.ExtractConfig(cfg, configType)
  364. if err != nil {
  365. return err
  366. }
  367. gw.gwConfig = bcfg.(*GatewayConfig)
  368. return nil
  369. }
  370. // Initialize builds the workers and initializes each one
  371. func (gw *BackendGateway) Initialize(cfg BackendConfig) error {
  372. gw.Lock()
  373. defer gw.Unlock()
  374. if gw.State != BackendStateNew && gw.State != BackendStateShuttered {
  375. return errors.New("can only Initialize in BackendStateNew or BackendStateShuttered state")
  376. }
  377. err := gw.loadConfig(cfg)
  378. if err != nil {
  379. gw.State = BackendStateError
  380. return err
  381. }
  382. workersSize := gw.workersSize()
  383. if workersSize < 1 {
  384. gw.State = BackendStateError
  385. return errors.New("must have at least 1 worker")
  386. }
  387. gw.processors = make([]Processor, 0)
  388. gw.validators = make([]Processor, 0)
  389. gw.streamers = make([]streamer, 0)
  390. for i := 0; i < workersSize; i++ {
  391. p, err := gw.newStack(gw.gwConfig.SaveProcess)
  392. if err != nil {
  393. gw.State = BackendStateError
  394. return err
  395. }
  396. gw.processors = append(gw.processors, p)
  397. v, err := gw.newStack(gw.gwConfig.ValidateProcess)
  398. if err != nil {
  399. gw.State = BackendStateError
  400. return err
  401. }
  402. gw.validators = append(gw.validators, v)
  403. s, err := gw.newStreamStack(gw.gwConfig.StreamSaveProcess)
  404. if err != nil {
  405. gw.State = BackendStateError
  406. return err
  407. }
  408. gw.streamers = append(gw.streamers, s)
  409. }
  410. // initialize processors
  411. if err := Svc.initialize(cfg); err != nil {
  412. gw.State = BackendStateError
  413. return err
  414. }
  415. if gw.conveyor == nil {
  416. gw.conveyor = make(chan *workerMsg, workersSize)
  417. }
  418. // ready to start
  419. gw.State = BackendStateInitialized
  420. return nil
  421. }
  422. // Start starts the worker goroutines, assuming it has been initialized or shuttered before
  423. func (gw *BackendGateway) Start() error {
  424. gw.Lock()
  425. defer gw.Unlock()
  426. if gw.State == BackendStateInitialized || gw.State == BackendStateShuttered {
  427. // we start our workers
  428. workersSize := gw.workersSize()
  429. // make our slice of channels for stopping
  430. gw.workStoppers = make([]chan bool, 0)
  431. // set the wait group
  432. gw.wg.Add(workersSize)
  433. for i := 0; i < workersSize; i++ {
  434. stop := make(chan bool)
  435. go func(workerId int, stop chan bool) {
  436. // blocks here until the worker exits
  437. for {
  438. state := gw.workDispatcher(
  439. gw.conveyor,
  440. gw.processors[workerId],
  441. gw.validators[workerId],
  442. gw.streamers[workerId],
  443. workerId+1,
  444. stop)
  445. // keep running after panic
  446. if state != dispatcherStatePanic {
  447. break
  448. }
  449. }
  450. gw.wg.Done()
  451. }(i, stop)
  452. gw.workStoppers = append(gw.workStoppers, stop)
  453. }
  454. gw.State = BackendStateRunning
  455. return nil
  456. } else {
  457. return errors.New(fmt.Sprintf("cannot start backend because it's in %s state", gw.State))
  458. }
  459. }
  460. // workersSize gets the number of workers to use for saving email by reading the save_workers_size config value
  461. // Returns 1 if no config value was set
  462. func (gw *BackendGateway) workersSize() int {
  463. if gw.gwConfig.WorkersSize <= 0 {
  464. return 1
  465. }
  466. return gw.gwConfig.WorkersSize
  467. }
  468. // saveTimeout returns the maximum amount of seconds to wait before timing out a save processing task
  469. func (gw *BackendGateway) saveTimeout() time.Duration {
  470. if gw.gwConfig.TimeoutSave == "" {
  471. return saveTimeout
  472. }
  473. t, err := time.ParseDuration(gw.gwConfig.TimeoutSave)
  474. if err != nil {
  475. return saveTimeout
  476. }
  477. return t
  478. }
  479. // validateRcptTimeout returns the maximum amount of seconds to wait before timing out a recipient validation task
  480. func (gw *BackendGateway) validateRcptTimeout() time.Duration {
  481. if gw.gwConfig.TimeoutValidateRcpt == "" {
  482. return validateRcptTimeout
  483. }
  484. t, err := time.ParseDuration(gw.gwConfig.TimeoutValidateRcpt)
  485. if err != nil {
  486. return validateRcptTimeout
  487. }
  488. return t
  489. }
  490. type dispatcherState int
  491. const (
  492. dispatcherStateStopped dispatcherState = iota
  493. dispatcherStateIdle
  494. dispatcherStateWorking
  495. dispatcherStateNotify
  496. dispatcherStatePanic
  497. )
  498. func (gw *BackendGateway) workDispatcher(
  499. workIn chan *workerMsg,
  500. save Processor,
  501. validate Processor,
  502. stream streamer,
  503. workerId int,
  504. stop chan bool) (state dispatcherState) {
  505. var msg *workerMsg
  506. defer func() {
  507. // panic recovery mechanism: it may panic when processing
  508. // since processors may call arbitrary code, some may be 3rd party / unstable
  509. // we need to detect the panic, and notify the backend that it failed & unlock the envelope
  510. if r := recover(); r != nil {
  511. Log().Error("worker recovered from panic:", r, string(debug.Stack()))
  512. if state == dispatcherStateWorking {
  513. msg.notifyMe <- &notifyMsg{err: errors.New("storage failed")}
  514. }
  515. state = dispatcherStatePanic
  516. return
  517. }
  518. // state is dispatcherStateStopped if it reached here
  519. return
  520. }()
  521. state = dispatcherStateIdle
  522. Log().Infof("processing worker started (#%d)", workerId)
  523. for {
  524. select {
  525. case <-stop:
  526. state = dispatcherStateStopped
  527. Log().Infof("stop signal for worker (#%d)", workerId)
  528. return
  529. case msg = <-workIn:
  530. state = dispatcherStateWorking // recovers from panic if in this state
  531. if msg.task == TaskSaveMail {
  532. result, err := save.Process(msg.e, msg.task)
  533. state = dispatcherStateNotify
  534. msg.notifyMe <- &notifyMsg{err: err, result: result, queuedID: msg.e.QueuedId}
  535. } else if msg.task == TaskSaveMailStream {
  536. err := stream.open(msg.e)
  537. if err == nil {
  538. N, copyErr := io.Copy(stream, msg.r)
  539. if copyErr != nil {
  540. err = append(err, copyErr)
  541. }
  542. msg.e.Values["size"] = N
  543. closeErr := stream.close()
  544. if closeErr != nil {
  545. err = append(err, copyErr)
  546. }
  547. }
  548. state = dispatcherStateNotify
  549. var result Result
  550. if err != nil {
  551. result = NewResult(response.Canned.SuccessMessageQueued, response.SP, msg.e.QueuedId)
  552. } else {
  553. result = NewResult(response.Canned.FailBackendTransaction, err)
  554. }
  555. msg.notifyMe <- &notifyMsg{err: err, result: result, queuedID: msg.e.QueuedId}
  556. } else {
  557. result, err := validate.Process(msg.e, msg.task)
  558. state = dispatcherStateNotify
  559. msg.notifyMe <- &notifyMsg{err: err, result: result}
  560. }
  561. }
  562. state = dispatcherStateIdle
  563. }
  564. }
  565. // stopWorkers sends a signal to all workers to stop
  566. func (gw *BackendGateway) stopWorkers() {
  567. for i := range gw.workStoppers {
  568. gw.workStoppers[i] <- true
  569. }
  570. }