From 7ddc71006ba78dcbe7c3a6e7cdd133f2d5602943 Mon Sep 17 00:00:00 2001 From: Eugene Bujak Date: Wed, 5 Dec 2018 15:36:18 +0300 Subject: [PATCH] stop DNS server properly when interrupted with ctrl+c, SIGTERM, SIGHUP or SIGQUIT --- app.go | 20 ++++++++++++++++---- coredns.go | 13 +++++++++++++ 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/app.go b/app.go index f958c7b4..10469245 100644 --- a/app.go +++ b/app.go @@ -7,8 +7,10 @@ import ( "net" "net/http" "os" + "os/signal" "path/filepath" "strconv" + "syscall" "time" "github.com/gobuffalo/packr" @@ -164,10 +166,13 @@ func main() { } }() - // Eat all args so that coredns can start happily - if len(os.Args) > 1 { - os.Args = os.Args[:1] - } + signal_channel := make(chan os.Signal) + signal.Notify(signal_channel, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP, syscall.SIGQUIT) + go func() { + <-signal_channel + cleanup() + os.Exit(0) + }() // Save the updated config err := config.write() @@ -192,6 +197,13 @@ func main() { log.Fatal(http.ListenAndServe(address, nil)) } +func cleanup() { + err := stopDNSServer() + if err != nil { + log.Printf("Couldn't stop DNS server: %s", err) + } +} + func getInput() (string, error) { scanner := bufio.NewScanner(os.Stdin) scanner.Scan() diff --git a/coredns.go b/coredns.go index f6940abe..119b2371 100644 --- a/coredns.go +++ b/coredns.go @@ -74,3 +74,16 @@ func reconfigureDNSServer() error { return nil } + +func stopDNSServer() error { + if !isRunning() { + return fmt.Errorf("Refusing to stop forwarding DNS server: not running") + } + + err := dnsServer.Stop() + if err != nil { + return errorx.Decorate(err, "Couldn't stop forwarding DNS server") + } + + return nil +}