gateway.go 5.5 KB

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