gateway.go 14 KB

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