gateway.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  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.hash)
  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. gw.Lock()
  101. defer gw.Unlock()
  102. if gw.State != BackendStateShuttered {
  103. return errors.New("backend must be in BackendStateshuttered state to Reinitialize")
  104. }
  105. err := gw.Initialize(gw.config)
  106. if err != nil {
  107. return fmt.Errorf("error while initializing the backend: %s", err)
  108. }
  109. gw.State = BackendStateRunning
  110. return err
  111. }
  112. // newProcessorLine creates a new call-stack of decorators and returns as a single Processor
  113. // Decorators are functions of Decorator type, source files prefixed with p_*
  114. // Each decorator does a specific task during the processing stage.
  115. // This function uses the config value process_line to figure out which Decorator to use
  116. func (gw *BackendGateway) newProcessorLine() Processor {
  117. var decorators []Decorator
  118. if len(gw.gwConfig.ProcessorLine) == 0 {
  119. return nil
  120. }
  121. line := strings.Split(strings.ToLower(gw.gwConfig.ProcessorLine), "|")
  122. for i := range line {
  123. name := line[len(line)-1-i] // reverse order, since decorators are stacked
  124. if makeFunc, ok := Processors[name]; ok {
  125. decorators = append(decorators, makeFunc())
  126. }
  127. }
  128. // build the call-stack of decorators
  129. p := Decorate(DefaultProcessor{}, decorators...)
  130. return p
  131. }
  132. // loadConfig loads the config for the GatewayConfig
  133. func (gw *BackendGateway) loadConfig(cfg BackendConfig) error {
  134. configType := baseConfig(&GatewayConfig{})
  135. bcfg, err := Service.extractConfig(cfg, configType)
  136. if err != nil {
  137. return err
  138. }
  139. gw.gwConfig = bcfg.(*GatewayConfig)
  140. return nil
  141. }
  142. // Initialize builds the workers and starts each worker in a goroutine
  143. func (gw *BackendGateway) Initialize(cfg BackendConfig) error {
  144. gw.Lock()
  145. defer gw.Unlock()
  146. err := gw.loadConfig(cfg)
  147. if err == nil {
  148. workersSize := gw.getNumberOfWorkers()
  149. if workersSize < 1 {
  150. gw.State = BackendStateError
  151. return errors.New("Must have at least 1 worker")
  152. }
  153. var lines []Processor
  154. for i := 0; i < workersSize; i++ {
  155. lines = append(lines, gw.newProcessorLine())
  156. }
  157. // initialize processors
  158. Service.Initialize(cfg)
  159. gw.saveMailChan = make(chan *savePayload, workersSize)
  160. // start our savemail workers
  161. gw.wg.Add(workersSize)
  162. for i := 0; i < workersSize; i++ {
  163. go func(workerId int) {
  164. gw.w.saveMailWorker(gw.saveMailChan, lines[workerId], workerId+1)
  165. gw.wg.Done()
  166. }(i)
  167. }
  168. } else {
  169. gw.State = BackendStateError
  170. }
  171. return err
  172. }
  173. // getNumberOfWorkers gets the number of workers to use for saving email by reading the save_workers_size config value
  174. // Returns 1 if no config value was set
  175. func (gw *BackendGateway) getNumberOfWorkers() int {
  176. if gw.gwConfig.WorkersSize == 0 {
  177. return 1
  178. }
  179. return gw.gwConfig.WorkersSize
  180. }