2
0

gateway.go 6.3 KB

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