gateway.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. package backends
  2. import (
  3. "errors"
  4. "fmt"
  5. "strconv"
  6. "sync"
  7. "time"
  8. "github.com/flashmob/go-guerrilla/envelope"
  9. "github.com/flashmob/go-guerrilla/response"
  10. "strings"
  11. )
  12. // A backend gateway is a proxy that implements the Backend interface.
  13. // It is used to start multiple goroutine workers for saving mail, and then distribute email saving to the workers
  14. // via a channel. Shutting down via Shutdown() will stop all workers.
  15. // The rest of this program always talks to the backend via this gateway.
  16. type BackendGateway struct {
  17. // channel for sending envelopes to process and save
  18. saveMailChan chan *workerMsg
  19. // channel for validating the last recipient added to the envelope
  20. validateRcptChan chan *workerMsg
  21. // waits for backend workers to start/stop
  22. wg sync.WaitGroup
  23. w *Worker
  24. // controls access to state
  25. sync.Mutex
  26. State backendState
  27. config BackendConfig
  28. gwConfig *GatewayConfig
  29. }
  30. type GatewayConfig struct {
  31. WorkersSize int `json:"save_workers_size,omitempty"`
  32. ProcessorLine string `json:"process_stack,omitempty"`
  33. }
  34. // savePayload is what get placed on the BackendGateway.saveMailChan channel
  35. type workerMsg struct {
  36. mail *envelope.Envelope
  37. // savedNotify is used to notify that the save operation completed
  38. notifyMe chan *notifyMsg
  39. }
  40. // possible values for state
  41. const (
  42. BackendStateRunning = iota
  43. BackendStateShuttered
  44. BackendStateError
  45. )
  46. const ProcessTimeout = time.Second * 30
  47. type backendState int
  48. func (s backendState) String() string {
  49. return strconv.Itoa(int(s))
  50. }
  51. // Process distributes an envelope to one of the backend workers
  52. func (gw *BackendGateway) Process(e *envelope.Envelope) Result {
  53. if gw.State != BackendStateRunning {
  54. return NewResult(response.Canned.FailBackendNotRunning + gw.State.String())
  55. }
  56. // place on the channel so that one of the save mail workers can pick it up
  57. savedNotify := make(chan *notifyMsg)
  58. gw.saveMailChan <- &workerMsg{e, savedNotify}
  59. // wait for the save to complete
  60. // or timeout
  61. select {
  62. case status := <-savedNotify:
  63. if status.err != nil {
  64. return NewResult(response.Canned.FailBackendTransaction + status.err.Error())
  65. }
  66. return NewResult(response.Canned.SuccessMessageQueued + status.queuedID)
  67. case <-time.After(ProcessTimeout):
  68. Log().Infof("Backend has timed out")
  69. return NewResult(response.Canned.FailBackendTimeout)
  70. }
  71. }
  72. // ValidateRcpt asks one of the workers to validate the recipient
  73. // Only the last recipient appended to e.RcptTo will be validated.
  74. func (gw *BackendGateway) ValidateRcpt(e *envelope.Envelope) RcptError {
  75. if gw.State != BackendStateRunning {
  76. return StorageNotAvailable
  77. }
  78. // place on the channel so that one of the save mail workers can pick it up
  79. notify := make(chan *notifyMsg)
  80. gw.validateRcptChan <- &workerMsg{e, notify}
  81. // wait for the validation to complete
  82. // or timeout
  83. select {
  84. case status := <-notify:
  85. if status.err != nil {
  86. return status.err
  87. }
  88. return nil
  89. case <-time.After(time.Second):
  90. Log().Infof("Backend has timed out")
  91. return StorageTimeout
  92. }
  93. }
  94. // Shutdown shuts down the backend and leaves it in BackendStateShuttered state
  95. func (gw *BackendGateway) Shutdown() error {
  96. gw.Lock()
  97. defer gw.Unlock()
  98. if gw.State != BackendStateShuttered {
  99. close(gw.saveMailChan) // workers will stop
  100. // wait for workers to stop
  101. gw.wg.Wait()
  102. Svc.shutdown()
  103. gw.State = BackendStateShuttered
  104. }
  105. return nil
  106. }
  107. // Reinitialize starts up a backend gateway that was shutdown before
  108. func (gw *BackendGateway) Reinitialize() error {
  109. if gw.State != BackendStateShuttered {
  110. return errors.New("backend must be in BackendStateshuttered state to Reinitialize")
  111. }
  112. err := gw.Initialize(gw.config)
  113. if err != nil {
  114. return fmt.Errorf("error while initializing the backend: %s", err)
  115. }
  116. gw.State = BackendStateRunning
  117. return err
  118. }
  119. // newProcessorLine creates a new call-stack of decorators and returns as a single Processor
  120. // Decorators are functions of Decorator type, source files prefixed with p_*
  121. // Each decorator does a specific task during the processing stage.
  122. // This function uses the config value process_stack to figure out which Decorator to use
  123. func (gw *BackendGateway) newProcessorLine() Processor {
  124. var decorators []Decorator
  125. if len(gw.gwConfig.ProcessorLine) == 0 {
  126. return nil
  127. }
  128. line := strings.Split(strings.ToLower(gw.gwConfig.ProcessorLine), "|")
  129. for i := range line {
  130. name := line[len(line)-1-i] // reverse order, since decorators are stacked
  131. if makeFunc, ok := processors[name]; ok {
  132. decorators = append(decorators, makeFunc())
  133. }
  134. }
  135. // build the call-stack of decorators
  136. p := Decorate(DefaultProcessor{}, decorators...)
  137. return p
  138. }
  139. // loadConfig loads the config for the GatewayConfig
  140. func (gw *BackendGateway) loadConfig(cfg BackendConfig) error {
  141. configType := BaseConfig(&GatewayConfig{})
  142. if _, ok := cfg["process_stack"]; !ok {
  143. cfg["process_stack"] = "Debugger"
  144. }
  145. if _, ok := cfg["save_workers_size"]; !ok {
  146. cfg["save_workers_size"] = 1
  147. }
  148. bcfg, err := Svc.ExtractConfig(cfg, configType)
  149. if err != nil {
  150. return err
  151. }
  152. gw.gwConfig = bcfg.(*GatewayConfig)
  153. return nil
  154. }
  155. // Initialize builds the workers and starts each worker in a goroutine
  156. func (gw *BackendGateway) Initialize(cfg BackendConfig) error {
  157. gw.Lock()
  158. defer gw.Unlock()
  159. err := gw.loadConfig(cfg)
  160. if err == nil {
  161. workersSize := gw.workersSize()
  162. if workersSize < 1 {
  163. gw.State = BackendStateError
  164. return errors.New("Must have at least 1 worker")
  165. }
  166. var lines []Processor
  167. for i := 0; i < workersSize; i++ {
  168. lines = append(lines, gw.newProcessorLine())
  169. }
  170. // initialize processors
  171. if err := Svc.initialize(cfg); err != nil {
  172. return err
  173. }
  174. gw.saveMailChan = make(chan *workerMsg, workersSize)
  175. gw.validateRcptChan = make(chan *workerMsg, workersSize)
  176. // start our workers
  177. gw.wg.Add(workersSize)
  178. for i := 0; i < workersSize; i++ {
  179. go func(workerId int) {
  180. gw.w.workDispatcher(gw.saveMailChan, gw.validateRcptChan, lines[workerId], workerId+1)
  181. gw.wg.Done()
  182. }(i)
  183. }
  184. } else {
  185. gw.State = BackendStateError
  186. }
  187. return err
  188. }
  189. // workersSize gets the number of workers to use for saving email by reading the save_workers_size config value
  190. // Returns 1 if no config value was set
  191. func (gw *BackendGateway) workersSize() int {
  192. if gw.gwConfig.WorkersSize == 0 {
  193. return 1
  194. }
  195. return gw.gwConfig.WorkersSize
  196. }