serve.go 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  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 {
  38. mainlog.WithError(err).Errorf("Failed creating a logger to %s", log.OutputStderr)
  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.Infof("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.Infof("Shutdown completed, exiting.")
  84. return
  85. } else {
  86. mainlog.Infof("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.Fatalf("Combined max clients for all servers (%d) is greater than open file limit (%d). "+
  102. "Please increase your open file limit or decrease max clients.", maxClients, fileLimit)
  103. }
  104. err = d.Start()
  105. if err != nil {
  106. mainlog.WithError(err).Error("Error(s) when creating new server(s)")
  107. os.Exit(1)
  108. }
  109. sigHandler()
  110. }
  111. // ReadConfig is called at startup, or when a SIG_HUP is caught
  112. func readConfig(path string, pidFile string) (*guerrilla.AppConfig, error) {
  113. // Load in the config.
  114. // Note here is the only place we can make an exception to the
  115. // "treat config values as immutable". For example, here the
  116. // command line flags can override config values
  117. appConfig, err := d.LoadConfig(path)
  118. if err != nil {
  119. return &appConfig, fmt.Errorf("could not read config file: %s", err.Error())
  120. }
  121. // override config pidFile with with flag from the command line
  122. if len(pidFile) > 0 {
  123. appConfig.PidFile = pidFile
  124. } else if len(appConfig.PidFile) == 0 {
  125. appConfig.PidFile = defaultPidFile
  126. }
  127. if verbose {
  128. appConfig.LogLevel = "debug"
  129. }
  130. return &appConfig, nil
  131. }