From: Peter Gallerani Date: Wed, 27 Mar 2019 16:00:28 +0000 (-0600) Subject: Handle SIGTERM gracefully (#449) X-Git-Url: https://vcs.fsf.org/?a=commitdiff_plain;h=721914029acc67f1bd78f9d981814cc02e89b61d;p=blackbox_exporter.git Handle SIGTERM gracefully (#449) Fixes #447 Signed-off-by: silentpete --- diff --git a/main.go b/main.go index 9103682..c9023db 100644 --- 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 + } } + }