2
0

gateway.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  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 = nil
  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 = nil
  82. // close in reverse order
  83. for i := len(s.d) - 1; i >= 0; i-- {
  84. if s.d[i].Close != nil {
  85. if e := s.d[i].Close(); e != nil {
  86. err = append(err, e)
  87. }
  88. }
  89. }
  90. return err
  91. }
  92. type backendState int
  93. // possible values for state
  94. const (
  95. BackendStateNew backendState = iota
  96. BackendStateRunning
  97. BackendStateShuttered
  98. BackendStateError
  99. BackendStateInitialized
  100. // default timeout for saving email, if 'gw_save_timeout' not present in config
  101. saveTimeout = time.Second * 30
  102. // default timeout for validating rcpt to, if 'gw_val_rcpt_timeout' not present in config
  103. validateRcptTimeout = time.Second * 5
  104. defaultProcessor = "Debugger"
  105. )
  106. func (s backendState) String() string {
  107. switch s {
  108. case BackendStateNew:
  109. return "NewState"
  110. case BackendStateRunning:
  111. return "RunningState"
  112. case BackendStateShuttered:
  113. return "ShutteredState"
  114. case BackendStateError:
  115. return "ErrorSate"
  116. case BackendStateInitialized:
  117. return "InitializedState"
  118. }
  119. return strconv.Itoa(int(s))
  120. }
  121. // New makes a new default BackendGateway backend, and initializes it using
  122. // backendConfig and stores the logger
  123. func New(backendConfig BackendConfig, l log.Logger) (Backend, error) {
  124. Svc.SetMainlog(l)
  125. gateway := &BackendGateway{}
  126. err := gateway.Initialize(backendConfig)
  127. if err != nil {
  128. return nil, fmt.Errorf("error while initializing the backend: %s", err)
  129. }
  130. // keep the config known to be good.
  131. gateway.config = backendConfig
  132. b = Backend(gateway)
  133. return b, nil
  134. }
  135. var workerMsgPool = sync.Pool{
  136. // if not available, then create a new one
  137. New: func() interface{} {
  138. return &workerMsg{}
  139. },
  140. }
  141. // reset resets a workerMsg that has been borrowed from the pool
  142. func (w *workerMsg) reset(e *mail.Envelope, task SelectTask) {
  143. if w.notifyMe == nil {
  144. w.notifyMe = make(chan *notifyMsg)
  145. }
  146. w.e = e
  147. w.task = task
  148. }
  149. // Process distributes an envelope to one of the backend workers with a TaskSaveMail task
  150. func (gw *BackendGateway) Process(e *mail.Envelope) Result {
  151. if gw.State != BackendStateRunning {
  152. return NewResult(response.Canned.FailBackendNotRunning, response.SP, gw.State)
  153. }
  154. // borrow a workerMsg from the pool
  155. workerMsg := workerMsgPool.Get().(*workerMsg)
  156. defer workerMsgPool.Put(workerMsg)
  157. workerMsg.reset(e, TaskSaveMail)
  158. // place on the channel so that one of the save mail workers can pick it up
  159. gw.conveyor <- workerMsg
  160. // wait for the save to complete
  161. // or timeout
  162. select {
  163. case status := <-workerMsg.notifyMe:
  164. // email saving transaction completed
  165. if status.result == BackendResultOK && status.queuedID != "" {
  166. return NewResult(response.Canned.SuccessMessageQueued, response.SP, status.queuedID)
  167. }
  168. // A custom result, there was probably an error, if so, log it
  169. if status.result != nil {
  170. if status.err != nil {
  171. Log().Error(status.err)
  172. }
  173. return status.result
  174. }
  175. // if there was no result, but there's an error, then make a new result from the error
  176. if status.err != nil {
  177. if _, err := strconv.Atoi(status.err.Error()[:3]); err != nil {
  178. return NewResult(response.Canned.FailBackendTransaction, response.SP, status.err)
  179. }
  180. return NewResult(status.err)
  181. }
  182. // both result & error are nil (should not happen)
  183. err := errors.New("no response from backend - processor did not return a result or an error")
  184. Log().Error(err)
  185. return NewResult(response.Canned.FailBackendTransaction, response.SP, err)
  186. case <-time.After(gw.saveTimeout()):
  187. Log().Error("Backend has timed out while saving email")
  188. e.Lock() // lock the envelope - it's still processing here, we don't want the server to recycle it
  189. go func() {
  190. // keep waiting for the backend to finish processing
  191. <-workerMsg.notifyMe
  192. e.Unlock()
  193. }()
  194. return NewResult(response.Canned.FailBackendTimeout)
  195. }
  196. }
  197. // ValidateRcpt asks one of the workers to validate the recipient
  198. // Only the last recipient appended to e.RcptTo will be validated.
  199. func (gw *BackendGateway) ValidateRcpt(e *mail.Envelope) RcptError {
  200. if gw.State != BackendStateRunning {
  201. return StorageNotAvailable
  202. }
  203. if _, ok := gw.validators[0].(NoopProcessor); ok {
  204. // no validator processors configured
  205. return nil
  206. }
  207. // place on the channel so that one of the save mail workers can pick it up
  208. workerMsg := workerMsgPool.Get().(*workerMsg)
  209. defer workerMsgPool.Put(workerMsg)
  210. workerMsg.reset(e, TaskValidateRcpt)
  211. gw.conveyor <- workerMsg
  212. // wait for the validation to complete
  213. // or timeout
  214. select {
  215. case status := <-workerMsg.notifyMe:
  216. if status.err != nil {
  217. return status.err
  218. }
  219. return nil
  220. case <-time.After(gw.validateRcptTimeout()):
  221. e.Lock()
  222. go func() {
  223. <-workerMsg.notifyMe
  224. e.Unlock()
  225. Log().Error("Backend has timed out while validating rcpt")
  226. }()
  227. return StorageTimeout
  228. }
  229. }
  230. func (gw *BackendGateway) StreamOn() bool {
  231. return len(gw.gwConfig.StreamSaveProcess) != 0
  232. }
  233. func (gw *BackendGateway) ProcessStream(r io.Reader, e *mail.Envelope) (Result, error) {
  234. res := response.Canned
  235. if gw.State != BackendStateRunning {
  236. return NewResult(res.FailBackendNotRunning, response.SP, gw.State), errors.New(res.FailBackendNotRunning.String())
  237. }
  238. // borrow a workerMsg from the pool
  239. workerMsg := workerMsgPool.Get().(*workerMsg)
  240. workerMsg.reset(e, TaskSaveMailStream)
  241. workerMsg.r = r
  242. // place on the channel so that one of the save mail workers can pick it up
  243. gw.conveyor <- workerMsg
  244. // wait for the save to complete
  245. // or timeout
  246. select {
  247. case status := <-workerMsg.notifyMe:
  248. // email saving transaction completed
  249. if status.result == BackendResultOK && status.queuedID != "" {
  250. return NewResult(res.SuccessMessageQueued, response.SP, status.queuedID), status.err
  251. }
  252. // A custom result, there was probably an error, if so, log it
  253. if status.result != nil {
  254. if status.err != nil {
  255. Log().Error(status.err)
  256. }
  257. return status.result, status.err
  258. }
  259. // if there was no result, but there's an error, then make a new result from the error
  260. if status.err != nil {
  261. if _, err := strconv.Atoi(status.err.Error()[:3]); err != nil {
  262. return NewResult(res.FailBackendTransaction, response.SP, status.err), status.err
  263. }
  264. return NewResult(status.err), status.err
  265. }
  266. // both result & error are nil (should not happen)
  267. err := errors.New("no response from backend - processor did not return a result or an error")
  268. Log().Error(err)
  269. return NewResult(res.FailBackendTransaction, response.SP, err), err
  270. case <-time.After(gw.saveTimeout()):
  271. Log().Error("Backend has timed out while saving email")
  272. e.Lock() // lock the envelope - it's still processing here, we don't want the server to recycle it
  273. go func() {
  274. // keep waiting for the backend to finish processing
  275. <-workerMsg.notifyMe
  276. e.Unlock()
  277. workerMsgPool.Put(workerMsg)
  278. }()
  279. return NewResult(res.FailBackendTimeout), errors.New("gateway timeout")
  280. }
  281. }
  282. // Shutdown shuts down the backend and leaves it in BackendStateShuttered state
  283. func (gw *BackendGateway) Shutdown() error {
  284. gw.Lock()
  285. defer gw.Unlock()
  286. if gw.State != BackendStateShuttered {
  287. // send a signal to all workers
  288. gw.stopWorkers()
  289. // wait for workers to stop
  290. gw.wg.Wait()
  291. // call shutdown on all processor shutdowners
  292. if err := Svc.shutdown(); err != nil {
  293. return err
  294. }
  295. gw.State = BackendStateShuttered
  296. }
  297. return nil
  298. }
  299. // Reinitialize initializes the gateway with the existing config after it was shutdown
  300. func (gw *BackendGateway) Reinitialize() error {
  301. if gw.State != BackendStateShuttered {
  302. return errors.New("backend must be in BackendStateshuttered state to Reinitialize")
  303. }
  304. // clear the Initializers and Shutdowners
  305. Svc.reset()
  306. err := gw.Initialize(gw.config)
  307. if err != nil {
  308. fmt.Println("reinitialize to ", gw.config, err)
  309. return fmt.Errorf("error while initializing the backend: %s", err)
  310. }
  311. return err
  312. }
  313. // newStack creates a new Processor by chaining multiple Processors in a call stack
  314. // Decorators are functions of Decorator type, source files prefixed with p_*
  315. // Each decorator does a specific task during the processing stage.
  316. // This function uses the config value save_process or validate_process to figure out which Decorator to use
  317. func (gw *BackendGateway) newStack(stackConfig string) (Processor, error) {
  318. var decorators []Decorator
  319. cfg := strings.ToLower(strings.TrimSpace(stackConfig))
  320. if len(cfg) == 0 {
  321. return NoopProcessor{}, nil
  322. }
  323. items := strings.Split(cfg, "|")
  324. for i := range items {
  325. name := items[len(items)-1-i] // reverse order, since decorators are stacked
  326. if makeFunc, ok := processors[name]; ok {
  327. decorators = append(decorators, makeFunc())
  328. } else {
  329. ErrProcessorNotFound = errors.New(fmt.Sprintf("processor [%s] not found", name))
  330. return nil, ErrProcessorNotFound
  331. }
  332. }
  333. // build the call-stack of decorators
  334. p := Decorate(DefaultProcessor{}, decorators...)
  335. return p, nil
  336. }
  337. func (gw *BackendGateway) newStreamStack(stackConfig string) (streamer, error) {
  338. var decorators []*StreamDecorator
  339. cfg := strings.ToLower(strings.TrimSpace(stackConfig))
  340. if len(cfg) == 0 {
  341. return streamer{NoopStreamProcessor{}, decorators}, nil
  342. }
  343. items := strings.Split(cfg, "|")
  344. for i := range items {
  345. name := items[len(items)-1-i] // reverse order, since decorators are stacked
  346. if makeFunc, ok := streamers[name]; ok {
  347. decorators = append(decorators, makeFunc())
  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, decorators := 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. if N, copyErr := io.Copy(stream, msg.r); copyErr != nil {
  539. err = append(err, copyErr)
  540. msg.e.Values["size"] = N
  541. }
  542. if closeErr := stream.close(); closeErr != nil {
  543. err = append(err, closeErr)
  544. }
  545. }
  546. state = dispatcherStateNotify
  547. var result Result
  548. if err != nil {
  549. result = NewResult(response.Canned.FailBackendTransaction, err)
  550. } else {
  551. result = NewResult(response.Canned.SuccessMessageQueued, response.SP, msg.e.QueuedId)
  552. }
  553. msg.notifyMe <- &notifyMsg{err: err, result: result, queuedID: msg.e.QueuedId}
  554. } else {
  555. result, err := validate.Process(msg.e, msg.task)
  556. state = dispatcherStateNotify
  557. msg.notifyMe <- &notifyMsg{err: err, result: result}
  558. }
  559. }
  560. state = dispatcherStateIdle
  561. }
  562. }
  563. // stopWorkers sends a signal to all workers to stop
  564. func (gw *BackendGateway) stopWorkers() {
  565. for i := range gw.workStoppers {
  566. gw.workStoppers[i] <- true
  567. }
  568. }