gateway.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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/log"
  10. "github.com/flashmob/go-guerrilla/response"
  11. "strings"
  12. )
  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. saveMailChan chan *savePayload
  19. // waits for backend workers to start/stop
  20. wg sync.WaitGroup
  21. w *Worker
  22. b Backend
  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. ProcessorLine string `json:"process_line,omitempty"`
  32. }
  33. // savePayload is what get placed on the BackendGateway.saveMailChan channel
  34. type savePayload struct {
  35. mail *envelope.Envelope
  36. // savedNotify is used to notify that the save operation completed
  37. savedNotify chan *saveStatus
  38. }
  39. // possible values for state
  40. const (
  41. BackendStateRunning = iota
  42. BackendStateShuttered
  43. BackendStateError
  44. )
  45. type backendState int
  46. func (s backendState) String() string {
  47. return strconv.Itoa(int(s))
  48. }
  49. // New retrieve a backend specified by the backendName, and initialize it using
  50. // backendConfig
  51. func New(backendName string, backendConfig BackendConfig, l log.Logger) (Backend, error) {
  52. Service.StoreMainlog(l)
  53. gateway := &BackendGateway{config: backendConfig}
  54. if backend, found := backends[backendName]; found {
  55. gateway.b = backend
  56. }
  57. err := gateway.Initialize(backendConfig)
  58. if err != nil {
  59. return nil, fmt.Errorf("error while initializing the backend: %s", err)
  60. }
  61. gateway.State = BackendStateRunning
  62. return gateway, nil
  63. }
  64. // Process distributes an envelope to one of the backend workers
  65. func (gw *BackendGateway) Process(e *envelope.Envelope) BackendResult {
  66. if gw.State != BackendStateRunning {
  67. return NewBackendResult(response.Canned.FailBackendNotRunning + gw.State.String())
  68. }
  69. // place on the channel so that one of the save mail workers can pick it up
  70. savedNotify := make(chan *saveStatus)
  71. gw.saveMailChan <- &savePayload{e, savedNotify}
  72. // wait for the save to complete
  73. // or timeout
  74. select {
  75. case status := <-savedNotify:
  76. if status.err != nil {
  77. return NewBackendResult(response.Canned.FailBackendTransaction + status.err.Error())
  78. }
  79. return NewBackendResult(response.Canned.SuccessMessageQueued + status.queuedID)
  80. case <-time.After(time.Second * 30):
  81. Log().Infof("Backend has timed out")
  82. return NewBackendResult(response.Canned.FailBackendTimeout)
  83. }
  84. }
  85. // Shutdown shuts down the backend and leaves it in BackendStateShuttered state
  86. func (gw *BackendGateway) Shutdown() error {
  87. gw.Lock()
  88. defer gw.Unlock()
  89. if gw.State != BackendStateShuttered {
  90. close(gw.saveMailChan) // workers will stop
  91. // wait for workers to stop
  92. gw.wg.Wait()
  93. Service.Shutdown()
  94. gw.State = BackendStateShuttered
  95. }
  96. return nil
  97. }
  98. // Reinitialize starts up a backend gateway that was shutdown before
  99. func (gw *BackendGateway) Reinitialize() error {
  100. if gw.State != BackendStateShuttered {
  101. return errors.New("backend must be in BackendStateshuttered state to Reinitialize")
  102. }
  103. err := gw.Initialize(gw.config)
  104. if err != nil {
  105. return fmt.Errorf("error while initializing the backend: %s", err)
  106. }
  107. gw.State = BackendStateRunning
  108. return err
  109. }
  110. // newProcessorLine creates a new call-stack of decorators and returns as a single Processor
  111. // Decorators are functions of Decorator type, source files prefixed with p_*
  112. // Each decorator does a specific task during the processing stage.
  113. // This function uses the config value process_line to figure out which Decorator to use
  114. func (gw *BackendGateway) newProcessorLine() Processor {
  115. var decorators []Decorator
  116. if len(gw.gwConfig.ProcessorLine) == 0 {
  117. return nil
  118. }
  119. line := strings.Split(strings.ToLower(gw.gwConfig.ProcessorLine), "|")
  120. for i := range line {
  121. name := line[len(line)-1-i] // reverse order, since decorators are stacked
  122. if makeFunc, ok := Processors[name]; ok {
  123. decorators = append(decorators, makeFunc())
  124. }
  125. }
  126. // build the call-stack of decorators
  127. p := Decorate(DefaultProcessor{}, decorators...)
  128. return p
  129. }
  130. // loadConfig loads the config for the GatewayConfig
  131. func (gw *BackendGateway) loadConfig(cfg BackendConfig) error {
  132. configType := BaseConfig(&GatewayConfig{})
  133. if _, ok := cfg["process_line"]; !ok {
  134. cfg["process_line"] = "Debugger"
  135. }
  136. if _, ok := cfg["save_workers_size"]; !ok {
  137. cfg["save_workers_size"] = 1
  138. }
  139. bcfg, err := Service.ExtractConfig(cfg, configType)
  140. if err != nil {
  141. return err
  142. }
  143. gw.gwConfig = bcfg.(*GatewayConfig)
  144. return nil
  145. }
  146. // Initialize builds the workers and starts each worker in a goroutine
  147. func (gw *BackendGateway) Initialize(cfg BackendConfig) error {
  148. gw.Lock()
  149. defer gw.Unlock()
  150. err := gw.loadConfig(cfg)
  151. if err == nil {
  152. workersSize := gw.getNumberOfWorkers()
  153. if workersSize < 1 {
  154. gw.State = BackendStateError
  155. return errors.New("Must have at least 1 worker")
  156. }
  157. var lines []Processor
  158. for i := 0; i < workersSize; i++ {
  159. lines = append(lines, gw.newProcessorLine())
  160. }
  161. // initialize processors
  162. Service.Initialize(cfg)
  163. gw.saveMailChan = make(chan *savePayload, workersSize)
  164. // start our savemail workers
  165. gw.wg.Add(workersSize)
  166. for i := 0; i < workersSize; i++ {
  167. go func(workerId int) {
  168. gw.w.saveMailWorker(gw.saveMailChan, lines[workerId], workerId+1)
  169. gw.wg.Done()
  170. }(i)
  171. }
  172. } else {
  173. gw.State = BackendStateError
  174. }
  175. return err
  176. }
  177. // getNumberOfWorkers gets the number of workers to use for saving email by reading the save_workers_size config value
  178. // Returns 1 if no config value was set
  179. func (gw *BackendGateway) getNumberOfWorkers() int {
  180. if gw.gwConfig.WorkersSize == 0 {
  181. return 1
  182. }
  183. return gw.gwConfig.WorkersSize
  184. }