guerrilla.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. package guerrilla
  2. import (
  3. "errors"
  4. "github.com/flashmob/go-guerrilla/backends"
  5. "github.com/flashmob/go-guerrilla/log"
  6. "sync"
  7. "sync/atomic"
  8. )
  9. const (
  10. // server has just been created
  11. GuerrillaStateNew = iota
  12. // Server has been started and is running
  13. GuerrillaStateStarted
  14. // Server has just been stopped
  15. GuerrillaStateStopped
  16. )
  17. type Errors []error
  18. // implement the Error interface
  19. func (e Errors) Error() string {
  20. if len(e) == 1 {
  21. return e[0].Error()
  22. }
  23. // multiple errors
  24. msg := ""
  25. for _, err := range e {
  26. msg += "\n" + err.Error()
  27. }
  28. return msg
  29. }
  30. type Guerrilla interface {
  31. Start() error
  32. Shutdown()
  33. Subscribe(topic Event, fn interface{}) error
  34. Publish(topic Event, args ...interface{})
  35. Unsubscribe(topic Event, handler interface{}) error
  36. SetLogger(log.Logger)
  37. }
  38. type guerrilla struct {
  39. Config AppConfig
  40. servers map[string]*server
  41. backend backends.Backend
  42. // guard controls access to g.servers
  43. guard sync.Mutex
  44. state int8
  45. EventHandler
  46. logStore
  47. }
  48. type logStore struct {
  49. atomic.Value
  50. }
  51. // Get loads the log.logger in an atomic operation. Returns a stderr logger if not able to load
  52. func (ls *logStore) mainlog() log.Logger {
  53. if v, ok := ls.Load().(log.Logger); ok {
  54. return v
  55. }
  56. l, _ := log.GetLogger(log.OutputStderr.String())
  57. return l
  58. }
  59. // storeMainlog stores the log value in an atomic operation
  60. func (ls *logStore) storeMainlog(log log.Logger) {
  61. ls.Store(log)
  62. }
  63. // Returns a new instance of Guerrilla with the given config, not yet running.
  64. func New(ac *AppConfig, b backends.Backend, l log.Logger) (Guerrilla, error) {
  65. g := &guerrilla{
  66. Config: *ac, // take a local copy
  67. servers: make(map[string]*server, len(ac.Servers)),
  68. backend: b,
  69. }
  70. g.storeMainlog(l)
  71. if ac.LogLevel != "" {
  72. g.mainlog().SetLevel(ac.LogLevel)
  73. }
  74. g.state = GuerrillaStateNew
  75. err := g.makeServers()
  76. // subscribe for any events that may come in while running
  77. g.subscribeEvents()
  78. return g, err
  79. }
  80. // Instantiate servers
  81. func (g *guerrilla) makeServers() error {
  82. g.mainlog().Debug("making servers")
  83. var errs Errors
  84. for _, sc := range g.Config.Servers {
  85. if _, ok := g.servers[sc.ListenInterface]; ok {
  86. // server already instantiated
  87. continue
  88. }
  89. if errs := sc.Validate(); errs != nil {
  90. g.mainlog().WithError(errs).Errorf("Failed to create server [%s]", sc.ListenInterface)
  91. errs = append(errs, errs...)
  92. continue
  93. } else {
  94. server, err := newServer(&sc, g.backend, g.mainlog())
  95. if err != nil {
  96. g.mainlog().WithError(err).Errorf("Failed to create server [%s]", sc.ListenInterface)
  97. errs = append(errs, err)
  98. }
  99. if server != nil {
  100. g.servers[sc.ListenInterface] = server
  101. server.setAllowedHosts(g.Config.AllowedHosts)
  102. }
  103. }
  104. }
  105. if len(g.servers) == 0 {
  106. errs = append(errs, errors.New("There are no servers that can start, please check your config"))
  107. }
  108. if len(errs) == 0 {
  109. return nil
  110. }
  111. return errs
  112. }
  113. // find a server by interface, retuning the server or err
  114. func (g *guerrilla) findServer(iface string) (*server, error) {
  115. g.guard.Lock()
  116. defer g.guard.Unlock()
  117. if server, ok := g.servers[iface]; ok {
  118. return server, nil
  119. }
  120. return nil, errors.New("server not found in g.servers")
  121. }
  122. func (g *guerrilla) removeServer(iface string) {
  123. g.guard.Lock()
  124. defer g.guard.Unlock()
  125. delete(g.servers, iface)
  126. }
  127. // setConfig sets the app config
  128. func (g *guerrilla) setConfig(c *AppConfig) {
  129. g.guard.Lock()
  130. defer g.guard.Unlock()
  131. g.Config = *c
  132. }
  133. // setServerConfig config updates the server's config, which will update for the next connected client
  134. func (g *guerrilla) setServerConfig(sc *ServerConfig) {
  135. g.guard.Lock()
  136. defer g.guard.Unlock()
  137. if _, ok := g.servers[sc.ListenInterface]; ok {
  138. g.servers[sc.ListenInterface].setConfig(sc)
  139. }
  140. }
  141. // mapServers calls a callback on each server in g.servers map
  142. // It locks the g.servers map before mapping
  143. func (g *guerrilla) mapServers(callback func(*server)) map[string]*server {
  144. defer g.guard.Unlock()
  145. g.guard.Lock()
  146. for _, server := range g.servers {
  147. callback(server)
  148. }
  149. return g.servers
  150. }
  151. // subscribeEvents subscribes event handlers for configuration change events
  152. func (g *guerrilla) subscribeEvents() {
  153. // main config changed
  154. g.Subscribe(EventConfigNewConfig, func(c *AppConfig) {
  155. g.setConfig(c)
  156. })
  157. // allowed_hosts changed, set for all servers
  158. g.Subscribe(EventConfigAllowedHosts, func(c *AppConfig) {
  159. g.mapServers(func(server *server) {
  160. server.setAllowedHosts(c.AllowedHosts)
  161. })
  162. g.mainlog().Infof("allowed_hosts config changed, a new list was set")
  163. })
  164. // the main log file changed
  165. g.Subscribe(EventConfigLogFile, func(c *AppConfig) {
  166. var err error
  167. var l log.Logger
  168. if l, err = log.GetLogger(c.LogFile); err == nil {
  169. g.storeMainlog(l)
  170. g.mapServers(func(server *server) {
  171. // it will change server's logger when the next client gets accepted
  172. server.mainlogStore.Store(l)
  173. })
  174. g.mainlog().Infof("main log for new clients changed to to [%s]", c.LogFile)
  175. } else {
  176. g.mainlog().WithError(err).Errorf("main logging change failed [%s]", c.LogFile)
  177. }
  178. })
  179. // re-open the main log file (file not changed)
  180. g.Subscribe(EventConfigLogReopen, func(c *AppConfig) {
  181. g.mainlog().Reopen()
  182. g.mainlog().Infof("re-opened main log file [%s]", c.LogFile)
  183. })
  184. // when log level changes, apply to mainlog and server logs
  185. g.Subscribe(EventConfigLogLevel, func(c *AppConfig) {
  186. g.mainlog().SetLevel(c.LogLevel)
  187. g.mapServers(func(server *server) {
  188. server.log.SetLevel(c.LogLevel)
  189. })
  190. g.mainlog().Infof("log level changed to [%s]", c.LogLevel)
  191. })
  192. // server config was updated
  193. g.Subscribe(EventConfigServerConfig, func(sc *ServerConfig) {
  194. g.setServerConfig(sc)
  195. })
  196. // add a new server to the config & start
  197. g.Subscribe(EventConfigEvServerNew, func(sc *ServerConfig) {
  198. if _, err := g.findServer(sc.ListenInterface); err != nil {
  199. // not found, lets add it
  200. if err := g.makeServers(); err != nil {
  201. g.mainlog().WithError(err).Error("cannot add server [%s]", sc.ListenInterface)
  202. return
  203. }
  204. g.mainlog().Infof("New server added [%s]", sc.ListenInterface)
  205. if g.state == GuerrillaStateStarted {
  206. err := g.Start()
  207. if err != nil {
  208. g.mainlog().WithError(err).Info("Event server_change:new_server returned errors when starting")
  209. }
  210. }
  211. }
  212. })
  213. // start a server that already exists in the config and has been enabled
  214. g.Subscribe(EventConfigServerStart, func(sc *ServerConfig) {
  215. if server, err := g.findServer(sc.ListenInterface); err == nil {
  216. if server.state == ServerStateStopped || server.state == ServerStateNew {
  217. g.mainlog().Infof("Starting server [%s]", server.listenInterface)
  218. err := g.Start()
  219. if err != nil {
  220. g.mainlog().WithError(err).Info("Event server_change:start_server returned errors when starting")
  221. }
  222. }
  223. }
  224. })
  225. // stop running a server
  226. g.Subscribe(EventConfigServerStop, func(sc *ServerConfig) {
  227. if server, err := g.findServer(sc.ListenInterface); err == nil {
  228. if server.state == ServerStateRunning {
  229. server.Shutdown()
  230. g.mainlog().Infof("Server [%s] stopped.", sc.ListenInterface)
  231. }
  232. }
  233. })
  234. // server was removed from config
  235. g.Subscribe(EventConfigServerRemove, func(sc *ServerConfig) {
  236. if server, err := g.findServer(sc.ListenInterface); err == nil {
  237. server.Shutdown()
  238. g.removeServer(sc.ListenInterface)
  239. g.mainlog().Infof("Server [%s] removed from config, stopped it.", sc.ListenInterface)
  240. }
  241. })
  242. // TLS changes
  243. g.Subscribe(EventConfigServerTLSConfig, func(sc *ServerConfig) {
  244. if server, err := g.findServer(sc.ListenInterface); err == nil {
  245. if err := server.configureSSL(); err == nil {
  246. g.mainlog().Infof("Server [%s] new TLS configuration loaded", sc.ListenInterface)
  247. } else {
  248. g.mainlog().WithError(err).Errorf("Server [%s] failed to load the new TLS configuration", sc.ListenInterface)
  249. }
  250. }
  251. })
  252. // when server's timeout change.
  253. g.Subscribe(EventConfigServerTimeout, func(sc *ServerConfig) {
  254. g.mapServers(func(server *server) {
  255. server.setTimeout(sc.Timeout)
  256. })
  257. })
  258. // when server's max clients change.
  259. g.Subscribe(EventConfigServerMaxClients, func(sc *ServerConfig) {
  260. g.mapServers(func(server *server) {
  261. // TODO resize the pool somehow
  262. })
  263. })
  264. // when a server's log file changes
  265. g.Subscribe(EventConfigServerLogFile, func(sc *ServerConfig) {
  266. if server, err := g.findServer(sc.ListenInterface); err == nil {
  267. var err error
  268. var l log.Logger
  269. if l, err = log.GetLogger(sc.LogFile); err == nil {
  270. g.storeMainlog(l)
  271. backends.Service.StoreMainlog(l)
  272. // it will change to the new logger on the next accepted client
  273. server.logStore.Store(l)
  274. g.mainlog().Infof("Server [%s] changed, new clients will log to: [%s]",
  275. sc.ListenInterface,
  276. sc.LogFile,
  277. )
  278. } else {
  279. g.mainlog().WithError(err).Errorf(
  280. "Server [%s] log change failed to: [%s]",
  281. sc.ListenInterface,
  282. sc.LogFile,
  283. )
  284. }
  285. }
  286. })
  287. // when the daemon caught a sighup, event for individual server
  288. g.Subscribe(EventConfigServerLogReopen, func(sc *ServerConfig) {
  289. if server, err := g.findServer(sc.ListenInterface); err == nil {
  290. server.log.Reopen()
  291. g.mainlog().Infof("Server [%s] re-opened log file [%s]", sc.ListenInterface, sc.LogFile)
  292. }
  293. })
  294. }
  295. // Entry point for the application. Starts all servers.
  296. func (g *guerrilla) Start() error {
  297. var startErrors Errors
  298. g.guard.Lock()
  299. defer func() {
  300. g.state = GuerrillaStateStarted
  301. g.guard.Unlock()
  302. }()
  303. if len(g.servers) == 0 {
  304. return append(startErrors, errors.New("No servers to start, please check the config"))
  305. }
  306. // channel for reading errors
  307. errs := make(chan error, len(g.servers))
  308. var startWG sync.WaitGroup
  309. // start servers, send any errors back to errs channel
  310. for ListenInterface := range g.servers {
  311. g.mainlog().Infof("Starting: %s", ListenInterface)
  312. if !g.servers[ListenInterface].isEnabled() {
  313. // not enabled
  314. continue
  315. }
  316. if g.servers[ListenInterface].state != ServerStateNew &&
  317. g.servers[ListenInterface].state != ServerStateStopped {
  318. continue
  319. }
  320. startWG.Add(1)
  321. go func(s *server) {
  322. if err := s.Start(&startWG); err != nil {
  323. errs <- err
  324. }
  325. }(g.servers[ListenInterface])
  326. }
  327. // wait for all servers to start (or fail)
  328. startWG.Wait()
  329. // close, then read any errors
  330. close(errs)
  331. for err := range errs {
  332. if err != nil {
  333. startErrors = append(startErrors, err)
  334. }
  335. }
  336. if len(startErrors) > 0 {
  337. return startErrors
  338. } else {
  339. if gw, ok := g.backend.(*backends.BackendGateway); ok {
  340. if gw.State == backends.BackendStateShuttered {
  341. _ = gw.Reinitialize()
  342. }
  343. }
  344. }
  345. return nil
  346. }
  347. func (g *guerrilla) Shutdown() {
  348. g.guard.Lock()
  349. defer func() {
  350. g.state = GuerrillaStateStopped
  351. defer g.guard.Unlock()
  352. }()
  353. for ListenInterface, s := range g.servers {
  354. if s.state == ServerStateRunning {
  355. s.Shutdown()
  356. g.mainlog().Infof("shutdown completed for [%s]", ListenInterface)
  357. }
  358. }
  359. if err := g.backend.Shutdown(); err != nil {
  360. g.mainlog().WithError(err).Warn("Backend failed to shutdown")
  361. } else {
  362. g.mainlog().Infof("Backend shutdown completed")
  363. }
  364. }
  365. // SetLogger sets the logger for the app and propagates it to sub-packages (eg.
  366. func (g *guerrilla) SetLogger(l log.Logger) {
  367. l.SetLevel(g.Config.LogLevel)
  368. g.storeMainlog(l)
  369. backends.Service.StoreMainlog(l)
  370. }