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 +}