Handle SIGTERM gracefully (#449)
authorPeter Gallerani <peter.gallerani@gmail.com>
Wed, 27 Mar 2019 16:00:28 +0000 (10:00 -0600)
committerBrian Brazil <brian.brazil@robustperception.io>
Wed, 27 Mar 2019 16:00:28 +0000 (16:00 +0000)
Fixes #447

Signed-off-by: silentpete <peter.gallerani@gmail.com>
main.go

diff --git a/main.go b/main.go
index 9103682a5f759c355e309649843e58a8e7b4b5f3..c9023db85c273d98b6bdcd6331e386ca260b68bb 100644 (file)
--- a/main.go
+++ b/main.go
@@ -202,6 +202,10 @@ func init() {
 }
 
 func main() {
+       os.Exit(run())
+}
+
+func run() int {
        allowedLevel := promlog.AllowedLevel{}
        flag.AddFlags(kingpin.CommandLine, &allowedLevel)
        kingpin.Version(version.Print("blackbox_exporter"))
@@ -215,12 +219,12 @@ func main() {
 
        if err := sc.ReloadConfig(*configFile); err != nil {
                level.Error(logger).Log("msg", "Error loading config", "err", err)
-               os.Exit(1)
+               return 1
        }
 
        if *configCheck {
                level.Info(logger).Log("msg", "Config file is ok exiting...")
-               os.Exit(0)
+               return 0
        }
 
        level.Info(logger).Log("msg", "Loaded config file")
@@ -327,9 +331,27 @@ func main() {
                w.Write(c)
        })
 
-       level.Info(logger).Log("msg", "Listening on address", "address", *listenAddress)
-       if err := http.ListenAndServe(*listenAddress, nil); err != nil {
-               level.Error(logger).Log("msg", "Error starting HTTP server", "err", err)
-               os.Exit(1)
+       srv := http.Server{Addr: *listenAddress}
+       srvc := make(chan struct{})
+       term := make(chan os.Signal, 1)
+       signal.Notify(term, os.Interrupt, syscall.SIGTERM)
+
+       go func() {
+               level.Info(logger).Log("msg", "Listening on address", "address", *listenAddress)
+               if err := srv.ListenAndServe(); err != http.ErrServerClosed {
+                       level.Error(logger).Log("msg", "Error starting HTTP server", "err", err)
+                       close(srvc)
+               }
+       }()
+
+       for {
+               select {
+               case <-term:
+                       level.Info(logger).Log("msg", "Received SIGTERM, exiting gracefully...")
+                       return 0
+               case <-srvc:
+                       return 1
+               }
        }
+
 }