api.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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. const defaultInterface = "127.0.0.1:2525"
  27. // AddProcessor adds a processor constructor to the backend.
  28. // name is the identifier to be used in the config. See backends docs for more info.
  29. func (d *Daemon) AddProcessor(name string, pc backends.ProcessorConstructor) {
  30. backends.Svc.AddProcessor(name, pc)
  31. }
  32. // Starts the daemon, initializing d.Config, d.Logger and d.Backend with defaults
  33. // can only be called once through the lifetime of the program
  34. func (d *Daemon) Start() (err error) {
  35. if d.g == nil {
  36. if d.Config == nil {
  37. d.Config = &AppConfig{}
  38. }
  39. if err = d.configureDefaults(); err != nil {
  40. return err
  41. }
  42. if d.Logger == nil {
  43. d.Logger, err = log.GetLogger(d.Config.LogFile, d.Config.LogLevel)
  44. if err != nil {
  45. return err
  46. }
  47. }
  48. if d.Backend == nil {
  49. d.Backend, err = backends.New(d.Config.BackendConfig, d.Logger)
  50. if err != nil {
  51. return err
  52. }
  53. }
  54. d.g, err = New(d.Config, d.Backend, d.Logger)
  55. if err != nil {
  56. return err
  57. }
  58. for i := range d.subs {
  59. d.Subscribe(d.subs[i].topic, d.subs[i].fn)
  60. }
  61. d.subs = make([]deferredSub, 0)
  62. }
  63. err = d.g.Start()
  64. if err == nil {
  65. if err := d.resetLogger(); err == nil {
  66. d.Log().Infof("main log configured to %s", d.Config.LogFile)
  67. }
  68. }
  69. return err
  70. }
  71. // Shuts down the daemon, including servers and backend.
  72. // Do not call Start on it again, use a new server.
  73. func (d *Daemon) Shutdown() {
  74. if d.g != nil {
  75. d.g.Shutdown()
  76. }
  77. }
  78. // LoadConfig reads in the config from a JSON file.
  79. // Note: if d.Config is nil, the sets d.Config with the unmarshalled AppConfig which will be returned
  80. func (d *Daemon) LoadConfig(path string) (AppConfig, error) {
  81. var ac AppConfig
  82. data, err := ioutil.ReadFile(path)
  83. if err != nil {
  84. return ac, fmt.Errorf("could not read config file: %s", err.Error())
  85. }
  86. err = ac.Load(data)
  87. if err != nil {
  88. return ac, err
  89. }
  90. if d.Config == nil {
  91. d.Config = &ac
  92. }
  93. return ac, nil
  94. }
  95. // SetConfig is same as LoadConfig, except you can pass AppConfig directly
  96. // does not emit any change events, instead use ReloadConfig after daemon has started
  97. func (d *Daemon) SetConfig(c AppConfig) error {
  98. // need to call c.Load, thus need to convert the config
  99. // d.load takes json bytes, marshal it
  100. data, err := json.Marshal(&c)
  101. if err != nil {
  102. return err
  103. }
  104. err = c.Load(data)
  105. if err != nil {
  106. return err
  107. }
  108. d.Config = &c
  109. return nil
  110. }
  111. // Reload a config using the passed in AppConfig and emit config change events
  112. func (d *Daemon) ReloadConfig(c AppConfig) error {
  113. oldConfig := *d.Config
  114. err := d.SetConfig(c)
  115. if err != nil {
  116. d.Log().WithError(err).Error("Error while reloading config")
  117. return err
  118. } else {
  119. d.Log().Infof("Configuration was reloaded at %s", d.configLoadTime)
  120. d.Config.EmitChangeEvents(&oldConfig, d.g)
  121. }
  122. return nil
  123. }
  124. // Reload a config from a file and emit config change events
  125. func (d *Daemon) ReloadConfigFile(path string) error {
  126. ac, err := d.LoadConfig(path)
  127. if err != nil {
  128. d.Log().WithError(err).Error("Error while reloading config from file")
  129. return err
  130. } else if d.Config != nil {
  131. oldConfig := *d.Config
  132. d.Config = &ac
  133. d.Log().Infof("Configuration was reloaded at %s", d.configLoadTime)
  134. d.Config.EmitChangeEvents(&oldConfig, d.g)
  135. }
  136. return nil
  137. }
  138. // ReopenLogs send events to re-opens all log files.
  139. // Typically, one would call this after rotating logs
  140. func (d *Daemon) ReopenLogs() error {
  141. if d.Config == nil {
  142. return errors.New("d.Config nil")
  143. }
  144. d.Config.EmitLogReopenEvents(d.g)
  145. return nil
  146. }
  147. // Subscribe for subscribing to config change events
  148. func (d *Daemon) Subscribe(topic Event, fn interface{}) error {
  149. if d.g == nil {
  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. }