Skip to content

Commit

Permalink
Handle SIGTERM gracefully (#449)
Browse files Browse the repository at this point in the history
Fixes #447

Signed-off-by: silentpete <[email protected]>
  • Loading branch information
silentpete authored and brian-brazil committed Mar 27, 2019
1 parent 4aa9359 commit 7219140
Showing 1 changed file with 28 additions and 6 deletions.
34 changes: 28 additions & 6 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"))
Expand All @@ -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")
Expand Down Expand Up @@ -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
}
}

}

0 comments on commit 7219140

Please sign in to comment.