api.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. package guerrilla
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "github.com/flashmob/go-guerrilla/backends"
  7. "github.com/flashmob/go-guerrilla/log"
  8. "io/ioutil"
  9. "time"
  10. )
  11. // Daemon provides a convenient API when using go-guerrilla as a package in your Go project.
  12. // Is's facade for Guerrilla, AppConfig, backends.Backend and log.Logger
  13. type Daemon struct {
  14. Config *AppConfig
  15. Logger log.Logger
  16. Backends []backends.Backend
  17. // Guerrilla will be managed through the API
  18. g Guerrilla
  19. configLoadTime time.Time
  20. subs []deferredSub
  21. }
  22. type deferredSub struct {
  23. topic Event
  24. fn interface{}
  25. }
  26. // AddProcessor adds a processor constructor to the backend.
  27. // name is the identifier to be used in the config. See backends docs for more info.
  28. func (d *Daemon) AddProcessor(name string, pc backends.ProcessorConstructor) {
  29. backends.Svc.AddProcessor(name, pc)
  30. }
  31. // Starts the daemon, initializing d.Config, d.Logger and d.Backend with defaults
  32. // can only be called once through the lifetime of the program
  33. func (d *Daemon) Start() (err error) {
  34. if d.g == nil {
  35. if d.Config == nil {
  36. d.Config = &AppConfig{}
  37. }
  38. if err = d.configureDefaults(); err != nil {
  39. return err
  40. }
  41. if d.Logger == nil {
  42. d.Logger, err = log.GetLogger(d.Config.LogFile, d.Config.LogLevel)
  43. if err != nil {
  44. return err
  45. }
  46. }
  47. d.g, err = New(d.Config, d.Logger, d.Backends...)
  48. if err != nil {
  49. return err
  50. }
  51. for i := range d.subs {
  52. _ = d.Subscribe(d.subs[i].topic, d.subs[i].fn)
  53. }
  54. d.subs = make([]deferredSub, 0)
  55. }
  56. err = d.g.Start()
  57. if err == nil {
  58. if err := d.resetLogger(); err == nil {
  59. d.Log().Fields("file", d.Config.LogFile).Info("main log configured")
  60. }
  61. }
  62. return err
  63. }
  64. // Shuts down the daemon, including servers and backend.
  65. // Do not call Start on it again, use a new server.
  66. func (d *Daemon) Shutdown() {
  67. if d.g != nil {
  68. d.g.Shutdown()
  69. }
  70. }
  71. // LoadConfig reads in the config from a JSON file.
  72. // Note: if d.Config is nil, the sets d.Config with the unmarshalled AppConfig which will be returned
  73. func (d *Daemon) LoadConfig(path string) (AppConfig, error) {
  74. var ac AppConfig
  75. data, err := ioutil.ReadFile(path)
  76. if err != nil {
  77. return ac, fmt.Errorf("could not read config file: %s", err.Error())
  78. }
  79. err = ac.Load(data)
  80. if err != nil {
  81. return ac, err
  82. }
  83. if d.Config == nil {
  84. d.Config = &ac
  85. }
  86. return ac, nil
  87. }
  88. // SetConfig is same as LoadConfig, except you can pass AppConfig directly
  89. // does not emit any change events, instead use ReloadConfig after daemon has started
  90. func (d *Daemon) SetConfig(c AppConfig) error {
  91. // need to call c.Load, thus need to convert the config
  92. // d.load takes json bytes, marshal it
  93. data, err := json.Marshal(&c)
  94. if err != nil {
  95. return err
  96. }
  97. err = c.Load(data)
  98. if err != nil {
  99. return err
  100. }
  101. d.Config = &c
  102. return nil
  103. }
  104. // Reload a config using the passed in AppConfig and emit config change events
  105. func (d *Daemon) ReloadConfig(c AppConfig) error {
  106. oldConfig := *d.Config
  107. err := d.SetConfig(c)
  108. if err != nil {
  109. d.Log().WithError(err).Error("Error while reloading config")
  110. return err
  111. }
  112. d.Log().Info("configuration was reloaded")
  113. d.Config.EmitChangeEvents(&oldConfig, d.g)
  114. return nil
  115. }
  116. // Reload a config from a file and emit config change events
  117. func (d *Daemon) ReloadConfigFile(path string) error {
  118. ac, err := d.LoadConfig(path)
  119. if err != nil {
  120. d.Log().WithError(err).Error("Error while reloading config from file")
  121. return err
  122. } else if d.Config != nil {
  123. oldConfig := *d.Config
  124. d.Config = &ac
  125. d.Log().Info("configuration was reloaded")
  126. d.Config.EmitChangeEvents(&oldConfig, d.g)
  127. }
  128. return nil
  129. }
  130. // ReopenLogs send events to re-opens all log files.
  131. // Typically, one would call this after rotating logs
  132. func (d *Daemon) ReopenLogs() error {
  133. if d.Config == nil {
  134. return errors.New("d.Config nil")
  135. }
  136. d.Config.emitLogReopenEvents(d.g)
  137. return nil
  138. }
  139. // Subscribe for subscribing to config change events
  140. func (d *Daemon) Subscribe(topic Event, fn interface{}) error {
  141. if d.g == nil {
  142. // defer the subscription until the daemon is started
  143. d.subs = append(d.subs, deferredSub{topic, fn})
  144. return nil
  145. }
  146. return d.g.Subscribe(topic, fn)
  147. }
  148. // for publishing config change events
  149. func (d *Daemon) Publish(topic Event, args ...interface{}) {
  150. if d.g == nil {
  151. return
  152. }
  153. d.g.Publish(topic, args...)
  154. }
  155. // for unsubscribing from config change events
  156. func (d *Daemon) Unsubscribe(topic Event, handler interface{}) error {
  157. if d.g == nil {
  158. for i := range d.subs {
  159. if d.subs[i].topic == topic && d.subs[i].fn == handler {
  160. d.subs = append(d.subs[:i], d.subs[i+1:]...)
  161. }
  162. }
  163. return nil
  164. }
  165. return d.g.Unsubscribe(topic, handler)
  166. }
  167. // log returns a logger that implements our log.Logger interface.
  168. // level is set to "info" by default
  169. func (d *Daemon) Log() log.Logger {
  170. if d.Logger != nil {
  171. return d.Logger
  172. }
  173. out := log.OutputStderr.String()
  174. level := log.InfoLevel.String()
  175. if d.Config != nil {
  176. if len(d.Config.LogFile) > 0 {
  177. out = d.Config.LogFile
  178. }
  179. if len(d.Config.LogLevel) > 0 {
  180. level = d.Config.LogLevel
  181. }
  182. }
  183. l, _ := log.GetLogger(out, level)
  184. return l
  185. }
  186. // set the default values for the servers and backend config options
  187. func (d *Daemon) configureDefaults() error {
  188. err := d.Config.setDefaults()
  189. if err != nil {
  190. return err
  191. }
  192. if d.Backends == nil {
  193. d.Backends = make([]backends.Backend, 0)
  194. // the config will be used to make backends
  195. err = d.Config.BackendConfig.ConfigureDefaults()
  196. if err != nil {
  197. return err
  198. }
  199. }
  200. return err
  201. }
  202. // resetLogger sets the logger to the one specified in the config.
  203. // This is because at the start, the daemon may be logging to stderr,
  204. // then attaches to the logs once the config is loaded.
  205. // This will propagate down to the servers / backend too.
  206. func (d *Daemon) resetLogger() error {
  207. l, err := log.GetLogger(d.Config.LogFile, d.Config.LogLevel)
  208. if err != nil {
  209. return err
  210. }
  211. d.Logger = l
  212. d.g.SetLogger(d.Logger)
  213. return nil
  214. }