From f6e328a0aa3c0ea1501945c0672bde0aeee97f29 Mon Sep 17 00:00:00 2001 From: Hector Date: Sun, 20 Feb 2022 08:17:06 +0000 Subject: [PATCH] feat: correctly handle shutdown signals Add a new method to the application startup to listen for OS shutdown signals and handle them appropriately. A shutdown signal will cause the app to exit immediately. Use correct syntax for the `ENTRYPOINT` field in the Dockerfile to ensure that OS signals get passed down to the running application. --- Dockerfile | 2 +- src/exporter.go | 22 +++++++++++++++++++--- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/Dockerfile b/Dockerfile index d14e460..4742e37 100644 --- a/Dockerfile +++ b/Dockerfile @@ -20,4 +20,4 @@ WORKDIR /app # Copy compiled binary to release image COPY --from=build /build/src/exporter /app/fail2ban-prometheus-exporter -ENTRYPOINT /app/fail2ban-prometheus-exporter +ENTRYPOINT ["/app/fail2ban-prometheus-exporter"] diff --git a/src/exporter.go b/src/exporter.go index ff357d2..5b2c837 100644 --- a/src/exporter.go +++ b/src/exporter.go @@ -6,11 +6,13 @@ import ( "fail2ban-prometheus-exporter/collector/f2b" "fail2ban-prometheus-exporter/collector/textfile" "fmt" - "log" - "net/http" - "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" + "log" + "net/http" + "os" + "os/signal" + "syscall" ) const ( @@ -54,6 +56,7 @@ func main() { if appSettings.VersionMode { printAppVersion() } else { + handleGracefulShutdown() log.Printf("fail2ban exporter version %s", version) log.Printf("starting server at %s", appSettings.MetricsAddress) @@ -85,3 +88,16 @@ func main() { log.Print(err) } } + +func handleGracefulShutdown() { + var signals = make(chan os.Signal) + + signal.Notify(signals, syscall.SIGTERM) + signal.Notify(signals, syscall.SIGINT) + + go func() { + sig := <-signals + log.Printf("caught signal: %+v", sig) + os.Exit(0) + }() +}