serve.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. "os/signal"
  6. "syscall"
  7. "time"
  8. "github.com/flashmob/go-guerrilla"
  9. "github.com/flashmob/go-guerrilla/log"
  10. // enable the Redis redigo driver
  11. _ "github.com/flashmob/go-guerrilla/backends/storage/redigo"
  12. // Choose iconv or mail/encoding package which uses golang.org/x/net/html/charset
  13. //_ "github.com/flashmob/go-guerrilla/mail/iconv"
  14. _ "github.com/flashmob/go-guerrilla/mail/encoding"
  15. "github.com/spf13/cobra"
  16. _ "github.com/go-sql-driver/mysql"
  17. )
  18. const (
  19. defaultPidFile = "/var/run/go-guerrilla.pid"
  20. )
  21. var (
  22. configPath string
  23. pidFile string
  24. serveCmd = &cobra.Command{
  25. Use: "serve",
  26. Short: "start the daemon and start all available servers",
  27. Run: serve,
  28. }
  29. signalChannel = make(chan os.Signal, 1) // for trapping SIGHUP and friends
  30. mainlog log.Logger
  31. d guerrilla.Daemon
  32. )
  33. func init() {
  34. // log to stderr on startup
  35. var err error
  36. mainlog, err = log.GetLogger(log.OutputStderr.String(), log.InfoLevel.String())
  37. if err != nil && mainlog != nil {
  38. mainlog.Fields("error", err, "file", log.OutputStderr).Error("failed creating a logger")
  39. }
  40. cfgFile := "goguerrilla.conf" // deprecated default name
  41. if _, err := os.Stat(cfgFile); err != nil {
  42. cfgFile = "goguerrilla.conf.json" // use the new name
  43. }
  44. serveCmd.PersistentFlags().StringVarP(&configPath, "config", "c",
  45. cfgFile, "Path to the configuration file")
  46. // intentionally didn't specify default pidFile; value from config is used if flag is empty
  47. serveCmd.PersistentFlags().StringVarP(&pidFile, "pidFile", "p",
  48. "", "Path to the pid file")
  49. rootCmd.AddCommand(serveCmd)
  50. }
  51. func sigHandler() {
  52. signal.Notify(signalChannel,
  53. syscall.SIGHUP,
  54. syscall.SIGTERM,
  55. syscall.SIGQUIT,
  56. syscall.SIGINT,
  57. syscall.SIGKILL,
  58. syscall.SIGUSR1,
  59. os.Kill,
  60. )
  61. for sig := range signalChannel {
  62. if sig == syscall.SIGHUP {
  63. if ac, err := readConfig(configPath, pidFile); err == nil {
  64. _ = d.ReloadConfig(*ac)
  65. } else {
  66. mainlog.WithError(err).Error("Could not reload config")
  67. }
  68. } else if sig == syscall.SIGUSR1 {
  69. if err := d.ReopenLogs(); err != nil {
  70. mainlog.WithError(err).Error("reopening logs failed")
  71. }
  72. } else if sig == syscall.SIGTERM || sig == syscall.SIGQUIT || sig == syscall.SIGINT || sig == os.Kill {
  73. mainlog.Info("shutdown signal caught")
  74. go func() {
  75. select {
  76. // exit if graceful shutdown not finished in 60 sec.
  77. case <-time.After(time.Second * 60):
  78. mainlog.Error("graceful shutdown timed out")
  79. os.Exit(1)
  80. }
  81. }()
  82. d.Shutdown()
  83. mainlog.Info("Shutdown completed, exiting")
  84. return
  85. } else {
  86. mainlog.Info("Shutdown, unknown signal caught")
  87. return
  88. }
  89. }
  90. }
  91. func serve(cmd *cobra.Command, args []string) {
  92. logVersion()
  93. d = guerrilla.Daemon{Logger: mainlog}
  94. c, err := readConfig(configPath, pidFile)
  95. if err != nil {
  96. mainlog.WithError(err).Fatal("error while reading config")
  97. }
  98. _ = d.SetConfig(*c)
  99. // Check that max clients is not greater than system open file limit.
  100. if ok, maxClients, fileLimit := guerrilla.CheckFileLimit(c); !ok {
  101. mainlog.Fields("naxClients", maxClients, "fileLimit", fileLimit).
  102. Fatal("combined max clients for all servers is greater than open file limit, " +
  103. "please increase your open file limit or decrease max clients")
  104. }
  105. err = d.Start()
  106. if err != nil {
  107. mainlog.WithError(err).Error("error(s) when creating new server(s)")
  108. os.Exit(1)
  109. }
  110. sigHandler()
  111. }
  112. // ReadConfig is called at startup, or when a SIG_HUP is caught
  113. func readConfig(path string, pidFile string) (*guerrilla.AppConfig, error) {
  114. // Load in the config.
  115. // Note here is the only place we can make an exception to the
  116. // "treat config values as immutable". For example, here the
  117. // command line flags can override config values
  118. appConfig, err := d.LoadConfig(path)
  119. if err != nil {
  120. return &appConfig, fmt.Errorf("could not read config file: %s", err.Error())
  121. }
  122. // override config pidFile with with flag from the command line
  123. if len(pidFile) > 0 {
  124. appConfig.PidFile = pidFile
  125. } else if len(appConfig.PidFile) == 0 {
  126. appConfig.PidFile = defaultPidFile
  127. }
  128. if verbose {
  129. appConfig.LogLevel = "debug"
  130. }
  131. return &appConfig, nil
  132. }