gateway.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  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. defer 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 eamil")
  132. return NewResult(response.Canned.FailBackendTimeout)
  133. }
  134. }
  135. // ValidateRcpt asks one of the workers to validate the recipient
  136. // Only the last recipient appended to e.RcptTo will be validated.
  137. func (gw *BackendGateway) ValidateRcpt(e *mail.Envelope) RcptError {
  138. if gw.State != BackendStateRunning {
  139. return StorageNotAvailable
  140. }
  141. if _, ok := gw.validators[0].(NoopProcessor); ok {
  142. // no validator processors configured
  143. return nil
  144. }
  145. // place on the channel so that one of the save mail workers can pick it up
  146. workerMsg := workerMsgPool.Get().(*workerMsg)
  147. workerMsg.reset(e, TaskValidateRcpt)
  148. gw.conveyor <- workerMsg
  149. // wait for the validation to complete
  150. // or timeout
  151. select {
  152. case status := <-workerMsg.notifyMe:
  153. if status.err != nil {
  154. return status.err
  155. }
  156. return nil
  157. case <-time.After(gw.validateRcptTimeout()):
  158. Log().Error("Backend has timed out while validating rcpt")
  159. return StorageTimeout
  160. }
  161. }
  162. // Shutdown shuts down the backend and leaves it in BackendStateShuttered state
  163. func (gw *BackendGateway) Shutdown() error {
  164. gw.Lock()
  165. defer gw.Unlock()
  166. if gw.State != BackendStateShuttered {
  167. // send a signal to all workers
  168. gw.stopWorkers()
  169. // wait for workers to stop
  170. gw.wg.Wait()
  171. // call shutdown on all processor shutdowners
  172. if err := Svc.shutdown(); err != nil {
  173. return err
  174. }
  175. gw.State = BackendStateShuttered
  176. }
  177. return nil
  178. }
  179. // Reinitialize initializes the gateway with the existing config after it was shutdown
  180. func (gw *BackendGateway) Reinitialize() error {
  181. if gw.State != BackendStateShuttered {
  182. return errors.New("backend must be in BackendStateshuttered state to Reinitialize")
  183. }
  184. // clear the Initializers and Shutdowners
  185. Svc.reset()
  186. err := gw.Initialize(gw.config)
  187. if err != nil {
  188. fmt.Println("reinitialize to ", gw.config, err)
  189. return fmt.Errorf("error while initializing the backend: %s", err)
  190. }
  191. return err
  192. }
  193. // newStack creates a new Processor by chaining multiple Processors in a call stack
  194. // Decorators are functions of Decorator type, source files prefixed with p_*
  195. // Each decorator does a specific task during the processing stage.
  196. // This function uses the config value save_process or validate_process to figure out which Decorator to use
  197. func (gw *BackendGateway) newStack(stackConfig string) (Processor, error) {
  198. var decorators []Decorator
  199. cfg := strings.ToLower(strings.TrimSpace(stackConfig))
  200. if len(cfg) == 0 {
  201. //cfg = strings.ToLower(defaultProcessor)
  202. return NoopProcessor{}, nil
  203. }
  204. items := strings.Split(cfg, "|")
  205. for i := range items {
  206. name := items[len(items)-1-i] // reverse order, since decorators are stacked
  207. if makeFunc, ok := processors[name]; ok {
  208. decorators = append(decorators, makeFunc())
  209. } else {
  210. ErrProcessorNotFound = errors.New(fmt.Sprintf("processor [%s] not found", name))
  211. return nil, ErrProcessorNotFound
  212. }
  213. }
  214. // build the call-stack of decorators
  215. p := Decorate(DefaultProcessor{}, decorators...)
  216. return p, nil
  217. }
  218. // loadConfig loads the config for the GatewayConfig
  219. func (gw *BackendGateway) loadConfig(cfg BackendConfig) error {
  220. configType := BaseConfig(&GatewayConfig{})
  221. // Note: treat config values as immutable
  222. // if you need to change a config value, change in the file then
  223. // send a SIGHUP
  224. bcfg, err := Svc.ExtractConfig(cfg, configType)
  225. if err != nil {
  226. return err
  227. }
  228. gw.gwConfig = bcfg.(*GatewayConfig)
  229. return nil
  230. }
  231. // Initialize builds the workers and initializes each one
  232. func (gw *BackendGateway) Initialize(cfg BackendConfig) error {
  233. gw.Lock()
  234. defer gw.Unlock()
  235. if gw.State != BackendStateNew && gw.State != BackendStateShuttered {
  236. return errors.New("Can only Initialize in BackendStateNew or BackendStateShuttered state")
  237. }
  238. err := gw.loadConfig(cfg)
  239. if err != nil {
  240. gw.State = BackendStateError
  241. return err
  242. }
  243. workersSize := gw.workersSize()
  244. if workersSize < 1 {
  245. gw.State = BackendStateError
  246. return errors.New("Must have at least 1 worker")
  247. }
  248. gw.processors = make([]Processor, 0)
  249. gw.validators = make([]Processor, 0)
  250. for i := 0; i < workersSize; i++ {
  251. p, err := gw.newStack(gw.gwConfig.SaveProcess)
  252. if err != nil {
  253. gw.State = BackendStateError
  254. return err
  255. }
  256. gw.processors = append(gw.processors, p)
  257. v, err := gw.newStack(gw.gwConfig.ValidateProcess)
  258. if err != nil {
  259. gw.State = BackendStateError
  260. return err
  261. }
  262. gw.validators = append(gw.validators, v)
  263. }
  264. // initialize processors
  265. if err := Svc.initialize(cfg); err != nil {
  266. gw.State = BackendStateError
  267. return err
  268. }
  269. if gw.conveyor == nil {
  270. gw.conveyor = make(chan *workerMsg, workersSize)
  271. }
  272. // ready to start
  273. gw.State = BackendStateInitialized
  274. return nil
  275. }
  276. // Start starts the worker goroutines, assuming it has been initialized or shuttered before
  277. func (gw *BackendGateway) Start() error {
  278. gw.Lock()
  279. defer gw.Unlock()
  280. if gw.State == BackendStateInitialized || gw.State == BackendStateShuttered {
  281. // we start our workers
  282. workersSize := gw.workersSize()
  283. // make our slice of channels for stopping
  284. gw.workStoppers = make([]chan bool, 0)
  285. // set the wait group
  286. gw.wg.Add(workersSize)
  287. for i := 0; i < workersSize; i++ {
  288. stop := make(chan bool)
  289. go func(workerId int, stop chan bool) {
  290. // blocks here until the worker exits
  291. for {
  292. state := gw.workDispatcher(
  293. gw.conveyor,
  294. gw.processors[workerId],
  295. gw.validators[workerId],
  296. workerId+1,
  297. stop)
  298. // keep running after panic
  299. if state != dispatcherStatePanic {
  300. break
  301. }
  302. }
  303. gw.wg.Done()
  304. }(i, stop)
  305. gw.workStoppers = append(gw.workStoppers, stop)
  306. }
  307. gw.State = BackendStateRunning
  308. return nil
  309. } else {
  310. return errors.New(fmt.Sprintf("cannot start backend because it's in %s state", gw.State))
  311. }
  312. }
  313. // workersSize gets the number of workers to use for saving email by reading the save_workers_size config value
  314. // Returns 1 if no config value was set
  315. func (gw *BackendGateway) workersSize() int {
  316. if gw.gwConfig.WorkersSize <= 0 {
  317. return 1
  318. }
  319. return gw.gwConfig.WorkersSize
  320. }
  321. // saveTimeout returns the maximum amount of seconds to wait before timing out a save processing task
  322. func (gw *BackendGateway) saveTimeout() time.Duration {
  323. if gw.gwConfig.TimeoutSave == "" {
  324. return saveTimeout
  325. }
  326. t, err := time.ParseDuration(gw.gwConfig.TimeoutSave)
  327. if err != nil {
  328. return saveTimeout
  329. }
  330. return t
  331. }
  332. // validateRcptTimeout returns the maximum amount of seconds to wait before timing out a recipient validation task
  333. func (gw *BackendGateway) validateRcptTimeout() time.Duration {
  334. if gw.gwConfig.TimeoutValidateRcpt == "" {
  335. return validateRcptTimeout
  336. }
  337. t, err := time.ParseDuration(gw.gwConfig.TimeoutValidateRcpt)
  338. if err != nil {
  339. return validateRcptTimeout
  340. }
  341. return t
  342. }
  343. type dispatcherState int
  344. const (
  345. dispatcherStateStopped dispatcherState = iota
  346. dispatcherStateIdle
  347. dispatcherStateWorking
  348. dispatcherStateNotify
  349. dispatcherStatePanic
  350. )
  351. func (gw *BackendGateway) workDispatcher(
  352. workIn chan *workerMsg,
  353. save Processor,
  354. validate Processor,
  355. workerId int,
  356. stop chan bool) (state dispatcherState) {
  357. var msg *workerMsg
  358. defer func() {
  359. // panic recovery mechanism: it may panic when processing
  360. // since processors may call arbitrary code, some may be 3rd party / unstable
  361. // we need to detect the panic, and notify the backend that it failed & unlock the envelope
  362. if r := recover(); r != nil {
  363. Log().Error("worker recovered from panic:", r, string(debug.Stack()))
  364. if state == dispatcherStateWorking {
  365. msg.notifyMe <- &notifyMsg{err: errors.New("storage failed")}
  366. msg.e.Unlock()
  367. }
  368. state = dispatcherStatePanic
  369. return
  370. }
  371. // state is dispatcherStateStopped if it reached here
  372. return
  373. }()
  374. state = dispatcherStateIdle
  375. Log().Infof("processing worker started (#%d)", workerId)
  376. for {
  377. select {
  378. case <-stop:
  379. state = dispatcherStateStopped
  380. Log().Infof("stop signal for worker (#%d)", workerId)
  381. return
  382. case msg = <-workIn:
  383. msg.e.Lock()
  384. state = dispatcherStateWorking
  385. if msg.task == TaskSaveMail {
  386. // process the email here
  387. result, _ := save.Process(msg.e, TaskSaveMail)
  388. state = dispatcherStateNotify
  389. if result.Code() < 300 {
  390. // if all good, let the gateway know that it was queued
  391. msg.notifyMe <- &notifyMsg{nil, msg.e.QueuedId}
  392. } else {
  393. // notify the gateway about the error
  394. msg.notifyMe <- &notifyMsg{err: errors.New(result.String())}
  395. }
  396. } else if msg.task == TaskValidateRcpt {
  397. _, err := validate.Process(msg.e, TaskValidateRcpt)
  398. state = dispatcherStateNotify
  399. if err != nil {
  400. // validation failed
  401. msg.notifyMe <- &notifyMsg{err: err}
  402. } else {
  403. // all good.
  404. msg.notifyMe <- &notifyMsg{err: nil}
  405. }
  406. }
  407. msg.e.Unlock()
  408. }
  409. state = dispatcherStateIdle
  410. }
  411. }
  412. // stopWorkers sends a signal to all workers to stop
  413. func (gw *BackendGateway) stopWorkers() {
  414. for i := range gw.workStoppers {
  415. gw.workStoppers[i] <- true
  416. }
  417. }