diff --git a/main.go b/main.go index b205487f383..045527a6811 100644 --- a/main.go +++ b/main.go @@ -8,6 +8,7 @@ import ( "path/filepath" "runtime" "strconv" + "syscall" "time" "github.com/grafana/grafana/pkg/cmd" @@ -30,6 +31,7 @@ var buildstamp string var configFile = flag.String("config", "", "path to config file") var homePath = flag.String("homepath", "", "path to grafana install/home path, defaults to working directory") var pidFile = flag.String("pidfile", "", "path to pid file") +var exitChan = make(chan int) func init() { runtime.GOMAXPROCS(runtime.NumCPU()) @@ -42,15 +44,9 @@ func main() { setting.BuildCommit = commit setting.BuildStamp = buildstampInt64 - go func() { - c := make(chan os.Signal, 1) - signal.Notify(c, os.Interrupt) - <-c - os.Exit(0) - }() + go listenToSystemSignels() flag.Parse() - writePIDFile() initRuntime() @@ -69,8 +65,7 @@ func main() { } cmd.StartServer() - - log.Close() + exitChan <- 0 } func initRuntime() { @@ -105,3 +100,27 @@ func writePIDFile() { log.Fatal(3, "Failed to write pidfile", err) } } + +func listenToSystemSignels() { + signalChan := make(chan os.Signal, 1) + code := 0 + + signal.Notify(signalChan, os.Interrupt) + signal.Notify(signalChan, os.Kill) + signal.Notify(signalChan, syscall.SIGTERM) + + select { + case sig := <-signalChan: + log.Info("Received signal %s. shutting down", sig) + case code = <-exitChan: + switch code { + case 0: + log.Info("Shutting down") + default: + log.Warn("Shutting down") + } + } + + log.Close() + os.Exit(code) +}