From 048616fb8df9b9601b2551da0052d598c98b2b47 Mon Sep 17 00:00:00 2001 From: Sebastien Boeuf Date: Tue, 18 Sep 2018 23:10:51 -0700 Subject: [PATCH] netmon: Add signals handler After the signals package has been created and shared with the CLI, this commit calls into it in order to properly handle the signals directed to the network monitor process. Fixes #718 Signed-off-by: Sebastien Boeuf --- netmon/netmon.go | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/netmon/netmon.go b/netmon/netmon.go index 9ba6d0ecca..d401e75ada 100644 --- a/netmon/netmon.go +++ b/netmon/netmon.go @@ -7,6 +7,7 @@ package main import ( "encoding/json" + "errors" "flag" "fmt" "io/ioutil" @@ -14,10 +15,13 @@ import ( "net" "os" "os/exec" + "os/signal" "path/filepath" "strings" + "syscall" "time" + "github.com/kata-containers/runtime/pkg/signals" "github.com/sirupsen/logrus" lSyslog "github.com/sirupsen/logrus/hooks/syslog" "github.com/vishvananda/netlink" @@ -203,6 +207,39 @@ func (n *netmon) cleanup() { close(n.rtDoneCh) } +// setupSignalHandler sets up signal handling, starting a go routine to deal +// with signals as they arrive. +func (n *netmon) setupSignalHandler() { + signals.SetLogger(n.logger()) + + sigCh := make(chan os.Signal, 8) + + for _, sig := range signals.HandledSignals() { + signal.Notify(sigCh, sig) + } + + go func() { + for { + sig := <-sigCh + + nativeSignal, ok := sig.(syscall.Signal) + if !ok { + err := errors.New("unknown signal") + netmonLog.WithError(err).WithField("signal", sig.String()).Error() + continue + } + + if signals.FatalSignal(nativeSignal) { + netmonLog.WithField("signal", sig).Error("received fatal signal") + signals.Die(nil) + } else if n.debug && signals.NonFatalSignal(nativeSignal) { + netmonLog.WithField("signal", sig).Debug("handling signal") + signals.Backtrace() + } + } + }() +} + func (n *netmon) logger() *logrus.Entry { fields := logrus.Fields{ "name": netmonName, @@ -641,6 +678,9 @@ func main() { os.Exit(1) } + // Setup signal handlers + n.setupSignalHandler() + // Scan the current interfaces. if err := n.scanNetwork(); err != nil { n.logger().WithError(err).Fatal("scanNetwork()")