api.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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. Backend 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. if d.Backend == nil {
  48. d.Backend, err = backends.New(d.Config.BackendConfig, d.Logger)
  49. if err != nil {
  50. return err
  51. }
  52. }
  53. d.g, err = New(d.Config, d.Backend, d.Logger)
  54. if err != nil {
  55. return err
  56. }
  57. for i := range d.subs {
  58. _ = d.Subscribe(d.subs[i].topic, d.subs[i].fn)
  59. }
  60. d.subs = make([]deferredSub, 0)
  61. }
  62. err = d.g.Start()
  63. if err == nil {
  64. if err := d.resetLogger(); err == nil {
  65. d.Log().Infof("main log configured to %s", d.Config.LogFile)
  66. }
  67. }
  68. return err
  69. }
  70. // Shuts down the daemon, including servers and backend.
  71. // Do not call Start on it again, use a new server.
  72. func (d *Daemon) Shutdown() {
  73. if d.g != nil {
  74. d.g.Shutdown()
  75. }
  76. }
  77. // LoadConfig reads in the config from a JSON file.
  78. // Note: if d.Config is nil, the sets d.Config with the unmarshalled AppConfig which will be returned
  79. func (d *Daemon) LoadConfig(path string) (AppConfig, error) {
  80. var ac AppConfig
  81. data, err := ioutil.ReadFile(path)
  82. if err != nil {
  83. return ac, fmt.Errorf("could not read config file: %s", err.Error())
  84. }
  85. err = ac.Load(data)
  86. if err != nil {
  87. return ac, err
  88. }
  89. if d.Config == nil {
  90. d.Config = &ac
  91. }
  92. return ac, nil
  93. }
  94. // SetConfig is same as LoadConfig, except you can pass AppConfig directly
  95. // does not emit any change events, instead use ReloadConfig after daemon has started
  96. func (d *Daemon) SetConfig(c AppConfig) error {
  97. // need to call c.Load, thus need to convert the config
  98. // d.load takes json bytes, marshal it
  99. data, err := json.Marshal(&c)
  100. if err != nil {
  101. return err
  102. }
  103. err = c.Load(data)
  104. if err != nil {
  105. return err
  106. }
  107. d.Config = &c
  108. return nil
  109. }
  110. // Reload a config using the passed in AppConfig and emit config change events
  111. func (d *Daemon) ReloadConfig(c AppConfig) error {
  112. oldConfig := *d.Config
  113. err := d.SetConfig(c)
  114. if err != nil {
  115. d.Log().WithError(err).Error("Error while reloading config")
  116. return err
  117. } else {
  118. d.Log().Infof("Configuration was reloaded at %s", d.configLoadTime)
  119. d.Config.EmitChangeEvents(&oldConfig, d.g)
  120. }
  121. return nil
  122. }
  123. // Reload a config from a file and emit config change events
  124. func (d *Daemon) ReloadConfigFile(path string) error {
  125. ac, err := d.LoadConfig(path)
  126. if err != nil {
  127. d.Log().WithError(err).Error("Error while reloading config from file")
  128. return err
  129. } else if d.Config != nil {
  130. oldConfig := *d.Config
  131. d.Config = &ac
  132. d.Log().Infof("Configuration was reloaded at %s", d.configLoadTime)
  133. d.Config.EmitChangeEvents(&oldConfig, d.g)
  134. }
  135. return nil
  136. }
  137. // ReopenLogs send events to re-opens all log files.
  138. // Typically, one would call this after rotating logs
  139. func (d *Daemon) ReopenLogs() error {
  140. if d.Config == nil {
  141. return errors.New("d.Config nil")
  142. }
  143. d.Config.EmitLogReopenEvents(d.g)
  144. return nil
  145. }
  146. // Subscribe for subscribing to config change events
  147. func (d *Daemon) Subscribe(topic Event, fn interface{}) error {
  148. if d.g == nil {
  149. // defer the subscription until the daemon is started
  150. d.subs = append(d.subs, deferredSub{topic, fn})
  151. return nil
  152. }
  153. return d.g.Subscribe(topic, fn)
  154. }
  155. // for publishing config change events
  156. func (d *Daemon) Publish(topic Event, args ...interface{}) {
  157. if d.g == nil {
  158. return
  159. }
  160. d.g.Publish(topic, args...)
  161. }
  162. // for unsubscribing from config change events
  163. func (d *Daemon) Unsubscribe(topic Event, handler interface{}) error {
  164. if d.g == nil {
  165. for i := range d.subs {
  166. if d.subs[i].topic == topic && d.subs[i].fn == handler {
  167. d.subs = append(d.subs[:i], d.subs[i+1:]...)
  168. }
  169. }
  170. return nil
  171. }
  172. return d.g.Unsubscribe(topic, handler)
  173. }
  174. // log returns a logger that implements our log.Logger interface.
  175. // level is set to "info" by default
  176. func (d *Daemon) Log() log.Logger {
  177. if d.Logger != nil {
  178. return d.Logger
  179. }
  180. out := log.OutputStderr.String()
  181. level := log.InfoLevel.String()
  182. if d.Config != nil {
  183. if len(d.Config.LogFile) > 0 {
  184. out = d.Config.LogFile
  185. }
  186. if len(d.Config.LogLevel) > 0 {
  187. level = d.Config.LogLevel
  188. }
  189. }
  190. l, _ := log.GetLogger(out, level)
  191. return l
  192. }
  193. // set the default values for the servers and backend config options
  194. func (d *Daemon) configureDefaults() error {
  195. err := d.Config.setDefaults()
  196. if err != nil {
  197. return err
  198. }
  199. if d.Backend == nil {
  200. err = d.Config.setBackendDefaults()
  201. if err != nil {
  202. return err
  203. }
  204. }
  205. return err
  206. }
  207. // resetLogger sets the logger to the one specified in the config.
  208. // This is because at the start, the daemon may be logging to stderr,
  209. // then attaches to the logs once the config is loaded.
  210. // This will propagate down to the servers / backend too.
  211. func (d *Daemon) resetLogger() error {
  212. l, err := log.GetLogger(d.Config.LogFile, d.Config.LogLevel)
  213. if err != nil {
  214. return err
  215. }
  216. d.Logger = l
  217. d.g.SetLogger(d.Logger)
  218. return nil
  219. }