Browse Source

fix(shutdown flow): improved shutdown flow and log closing, listing to kill and and SIGTERM as well, closes #2516

Torkel Ödegaard 10 years ago
parent
commit
7b911aea46
1 changed files with 28 additions and 9 deletions
  1. 28 9
      main.go

+ 28 - 9
main.go

@@ -8,6 +8,7 @@ import (
 	"path/filepath"
 	"path/filepath"
 	"runtime"
 	"runtime"
 	"strconv"
 	"strconv"
+	"syscall"
 	"time"
 	"time"
 
 
 	"github.com/grafana/grafana/pkg/cmd"
 	"github.com/grafana/grafana/pkg/cmd"
@@ -30,6 +31,7 @@ var buildstamp string
 var configFile = flag.String("config", "", "path to config file")
 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 homePath = flag.String("homepath", "", "path to grafana install/home path, defaults to working directory")
 var pidFile = flag.String("pidfile", "", "path to pid file")
 var pidFile = flag.String("pidfile", "", "path to pid file")
+var exitChan = make(chan int)
 
 
 func init() {
 func init() {
 	runtime.GOMAXPROCS(runtime.NumCPU())
 	runtime.GOMAXPROCS(runtime.NumCPU())
@@ -42,15 +44,9 @@ func main() {
 	setting.BuildCommit = commit
 	setting.BuildCommit = commit
 	setting.BuildStamp = buildstampInt64
 	setting.BuildStamp = buildstampInt64
 
 
-	go func() {
-		c := make(chan os.Signal, 1)
-		signal.Notify(c, os.Interrupt)
-		<-c
-		os.Exit(0)
-	}()
+	go listenToSystemSignels()
 
 
 	flag.Parse()
 	flag.Parse()
-
 	writePIDFile()
 	writePIDFile()
 	initRuntime()
 	initRuntime()
 
 
@@ -69,8 +65,7 @@ func main() {
 	}
 	}
 
 
 	cmd.StartServer()
 	cmd.StartServer()
-
-	log.Close()
+	exitChan <- 0
 }
 }
 
 
 func initRuntime() {
 func initRuntime() {
@@ -105,3 +100,27 @@ func writePIDFile() {
 		log.Fatal(3, "Failed to write pidfile", err)
 		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)
+}