stop DNS server properly when interrupted with ctrl+c, SIGTERM, SIGHUP or SIGQUIT

This commit is contained in:
Eugene Bujak 2018-12-05 15:36:18 +03:00
parent b0149972cc
commit 7ddc71006b
2 changed files with 29 additions and 4 deletions

20
app.go
View File

@ -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()

View File

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