abstract.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. package backends
  2. import (
  3. "errors"
  4. "fmt"
  5. "github.com/flashmob/go-guerrilla/envelope"
  6. "github.com/flashmob/go-guerrilla/ev"
  7. "reflect"
  8. "runtime/debug"
  9. "strings"
  10. )
  11. type AbstractBackend struct {
  12. config abstractConfig
  13. Extend Worker
  14. p Processor
  15. configLoaders []ConfigLoaderFunc
  16. configTesters []ConfigTesterFunc
  17. initializers []DecoratorinitializeFunc
  18. }
  19. type abstractConfig struct {
  20. LogReceivedMails bool `json:"log_received_mails"`
  21. }
  22. var ab AbstractBackend
  23. type ConfigLoaderFunc func(backendConfig BackendConfig) error
  24. func (b *AbstractBackend) AddConfigLoader(f ConfigLoaderFunc) {
  25. b.configLoaders = append(b.configLoaders, f)
  26. }
  27. type ConfigTesterFunc func(backendConfig BackendConfig) error
  28. func (b *AbstractBackend) AddConfigTester(f ConfigTesterFunc) {
  29. b.configTesters = append(b.configTesters, f)
  30. }
  31. type DecoratorinitializeFunc func() error
  32. func (b *AbstractBackend) AddInitializer(f DecoratorinitializeFunc) {
  33. b.initializers = append(b.initializers, f)
  34. }
  35. // Your backend should implement this method and set b.config field with a custom config struct
  36. // Therefore, your implementation would have your own custom config type instead of dummyConfig
  37. func (b *AbstractBackend) loadConfig(backendConfig BackendConfig) (err error) {
  38. // Load the backend config for the backend. It has already been unmarshalled
  39. // from the main config file 'backend' config "backend_config"
  40. // Now we need to convert each type and copy into the dummyConfig struct
  41. configType := baseConfig(&abstractConfig{})
  42. bcfg, err := b.extractConfig(backendConfig, configType)
  43. if err != nil {
  44. return err
  45. }
  46. m := bcfg.(*abstractConfig)
  47. b.config = *m
  48. return nil
  49. }
  50. func (b *AbstractBackend) SetProcessors(p ...Decorator) {
  51. if b.Extend != nil {
  52. b.Extend.SetProcessors(p...)
  53. return
  54. }
  55. b.p = Decorate(DefaultProcessor{}, p...)
  56. }
  57. func (b *AbstractBackend) Initialize(config BackendConfig) error {
  58. for _, loader := range b.configLoaders {
  59. loader(config)
  60. }
  61. for i := range b.initializers {
  62. b.initializers[i]()
  63. }
  64. //Service.Publish(ev.BackendProcConfigLoad, config)
  65. Service.Publish(ev.BackendProcInitialize, config)
  66. return nil
  67. // TODO delete
  68. if b.Extend != nil {
  69. return b.Extend.loadConfig(config)
  70. }
  71. err := b.loadConfig(config)
  72. if err != nil {
  73. return err
  74. }
  75. return nil
  76. }
  77. func (b *AbstractBackend) Shutdown() error {
  78. if b.Extend != nil {
  79. return b.Extend.Shutdown()
  80. }
  81. return nil
  82. }
  83. func (b *AbstractBackend) Process(mail *envelope.Envelope) BackendResult {
  84. if b.Extend != nil {
  85. return b.Extend.Process(mail)
  86. }
  87. // call the decorated process function
  88. b.p.Process(mail)
  89. return NewBackendResult("250 OK")
  90. }
  91. func (b *AbstractBackend) saveMailWorker(saveMailChan chan *savePayload) {
  92. if b.Extend != nil {
  93. b.Extend.saveMailWorker(saveMailChan)
  94. return
  95. }
  96. defer func() {
  97. if r := recover(); r != nil {
  98. // recover form closed channel
  99. fmt.Println("Recovered in f", r, string(debug.Stack()))
  100. mainlog.Error("Recovered form panic:", r, string(debug.Stack()))
  101. }
  102. // close any connections / files
  103. // ...
  104. }()
  105. for {
  106. payload := <-saveMailChan
  107. if payload == nil {
  108. mainlog.Debug("No more saveMailChan payload")
  109. return
  110. }
  111. // process the email here
  112. result := b.Process(payload.mail)
  113. // if all good
  114. if result.Code() < 300 {
  115. payload.savedNotify <- &saveStatus{nil, "s0m3l337Ha5hva1u3LOL"}
  116. } else {
  117. payload.savedNotify <- &saveStatus{errors.New(result.String()), "s0m3l337Ha5hva1u3LOL"}
  118. }
  119. }
  120. }
  121. func (b *AbstractBackend) getNumberOfWorkers() int {
  122. if b.Extend != nil {
  123. return b.Extend.getNumberOfWorkers()
  124. }
  125. return 1
  126. }
  127. func (b *AbstractBackend) testSettings() error {
  128. if b.Extend != nil {
  129. return b.Extend.testSettings()
  130. }
  131. return nil
  132. }
  133. // Load the backend config for the backend. It has already been unmarshalled
  134. // from the main config file 'backend' config "backend_config"
  135. // Now we need to convert each type and copy into the guerrillaDBAndRedisConfig struct
  136. // The reason why using reflection is because we'll get a nice error message if the field is missing
  137. // the alternative solution would be to json.Marshal() and json.Unmarshal() however that will not give us any
  138. // error messages
  139. func (h *AbstractBackend) extractConfig(configData BackendConfig, configType baseConfig) (interface{}, error) {
  140. // Use reflection so that we can provide a nice error message
  141. s := reflect.ValueOf(configType).Elem() // so that we can set the values
  142. m := reflect.ValueOf(configType).Elem()
  143. t := reflect.TypeOf(configType).Elem()
  144. typeOfT := s.Type()
  145. for i := 0; i < m.NumField(); i++ {
  146. f := s.Field(i)
  147. // read the tags of the config struct
  148. field_name := t.Field(i).Tag.Get("json")
  149. if len(field_name) > 0 {
  150. // parse the tag to
  151. // get the field name from struct tag
  152. split := strings.Split(field_name, ",")
  153. field_name = split[0]
  154. } else {
  155. // could have no tag
  156. // so use the reflected field name
  157. field_name = typeOfT.Field(i).Name
  158. }
  159. if f.Type().Name() == "int" {
  160. if intVal, converted := configData[field_name].(float64); converted {
  161. s.Field(i).SetInt(int64(intVal))
  162. } else {
  163. return configType, convertError("property missing/invalid: '" + field_name + "' of expected type: " + f.Type().Name())
  164. }
  165. }
  166. if f.Type().Name() == "string" {
  167. if stringVal, converted := configData[field_name].(string); converted {
  168. s.Field(i).SetString(stringVal)
  169. } else {
  170. return configType, convertError("missing/invalid: '" + field_name + "' of type: " + f.Type().Name())
  171. }
  172. }
  173. if f.Type().Name() == "bool" {
  174. if boolVal, converted := configData[field_name].(bool); converted {
  175. s.Field(i).SetBool(boolVal)
  176. } else {
  177. return configType, convertError("missing/invalid: '" + field_name + "' of type: " + f.Type().Name())
  178. }
  179. }
  180. }
  181. return configType, nil
  182. }