serve.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. "os/exec"
  6. "os/signal"
  7. "strconv"
  8. "strings"
  9. "syscall"
  10. "time"
  11. "github.com/flashmob/go-guerrilla"
  12. "github.com/flashmob/go-guerrilla/log"
  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. )
  60. for sig := range signalChannel {
  61. if sig == syscall.SIGHUP {
  62. if ac, err := readConfig(configPath, pidFile); err == nil {
  63. d.ReloadConfig(*ac)
  64. } else {
  65. mainlog.WithError(err).Error("Could not reload config")
  66. }
  67. } else if sig == syscall.SIGUSR1 {
  68. d.ReopenLogs()
  69. } else if sig == syscall.SIGTERM || sig == syscall.SIGQUIT || sig == syscall.SIGINT {
  70. mainlog.Infof("Shutdown signal caught")
  71. go func() {
  72. select {
  73. // exit if graceful shutdown not finished in 60 sec.
  74. case <-time.After(time.Second * 60):
  75. mainlog.Error("graceful shutdown timed out")
  76. os.Exit(1)
  77. }
  78. }()
  79. d.Shutdown()
  80. mainlog.Infof("Shutdown completed, exiting.")
  81. return
  82. } else {
  83. mainlog.Infof("Shutdown, unknown signal caught")
  84. return
  85. }
  86. }
  87. }
  88. func serve(cmd *cobra.Command, args []string) {
  89. logVersion()
  90. d = guerrilla.Daemon{Logger: mainlog}
  91. ac, err := readConfig(configPath, pidFile)
  92. if err != nil {
  93. mainlog.WithError(err).Fatal("Error while reading config")
  94. }
  95. d.SetConfig(*ac)
  96. // Check that max clients is not greater than system open file limit.
  97. fileLimit := getFileLimit()
  98. if fileLimit > 0 {
  99. maxClients := 0
  100. for _, s := range ac.Servers {
  101. maxClients += s.MaxClients
  102. }
  103. if maxClients > fileLimit {
  104. mainlog.Fatalf("Combined max clients for all servers (%d) is greater than open file limit (%d). "+
  105. "Please increase your open file limit or decrease max clients.", maxClients, fileLimit)
  106. }
  107. }
  108. err = d.Start()
  109. if err != nil {
  110. mainlog.WithError(err).Error("Error(s) when creating new server(s)")
  111. os.Exit(1)
  112. }
  113. sigHandler()
  114. }
  115. // ReadConfig is called at startup, or when a SIG_HUP is caught
  116. func readConfig(path string, pidFile string) (*guerrilla.AppConfig, error) {
  117. // Load in the config.
  118. // Note here is the only place we can make an exception to the
  119. // "treat config values as immutable". For example, here the
  120. // command line flags can override config values
  121. appConfig, err := d.LoadConfig(path)
  122. if err != nil {
  123. return &appConfig, fmt.Errorf("could not read config file: %s", err.Error())
  124. }
  125. // override config pidFile with with flag from the command line
  126. if len(pidFile) > 0 {
  127. appConfig.PidFile = pidFile
  128. } else if len(appConfig.PidFile) == 0 {
  129. appConfig.PidFile = defaultPidFile
  130. }
  131. if verbose {
  132. appConfig.LogLevel = "debug"
  133. }
  134. return &appConfig, nil
  135. }
  136. func getFileLimit() int {
  137. cmd := exec.Command("ulimit", "-n")
  138. out, err := cmd.Output()
  139. if err != nil {
  140. return -1
  141. }
  142. limit, err := strconv.Atoi(strings.TrimSpace(string(out)))
  143. if err != nil {
  144. return -1
  145. }
  146. return limit
  147. }