github.com/kata-containers/runtime@v0.0.0-20210505125100-04f29832a923/virtcontainers/netmon.go (about) 1 // Copyright (c) 2018 Intel Corporation 2 // 3 // SPDX-License-Identifier: Apache-2.0 4 // 5 6 package virtcontainers 7 8 import ( 9 "fmt" 10 "os/exec" 11 "syscall" 12 13 "github.com/sirupsen/logrus" 14 ) 15 16 // NetmonConfig is the structure providing specific configuration 17 // for the network monitor. 18 type NetmonConfig struct { 19 Path string 20 Debug bool 21 Enable bool 22 } 23 24 // netmonParams is the structure providing specific parameters needed 25 // for the execution of the network monitor binary. 26 type netmonParams struct { 27 netmonPath string 28 debug bool 29 logLevel string 30 runtime string 31 sandboxID string 32 } 33 34 func netmonLogger() *logrus.Entry { 35 return virtLog.WithField("subsystem", "netmon") 36 } 37 38 func prepareNetMonParams(params netmonParams) ([]string, error) { 39 if params.netmonPath == "" { 40 return []string{}, fmt.Errorf("Netmon path is empty") 41 } 42 if params.runtime == "" { 43 return []string{}, fmt.Errorf("Netmon runtime path is empty") 44 } 45 if params.sandboxID == "" { 46 return []string{}, fmt.Errorf("Netmon sandbox ID is empty") 47 } 48 49 args := []string{params.netmonPath, 50 "-r", params.runtime, 51 "-s", params.sandboxID, 52 } 53 54 if params.debug { 55 args = append(args, "-d") 56 } 57 if params.logLevel != "" { 58 args = append(args, []string{"-log", params.logLevel}...) 59 } 60 61 return args, nil 62 } 63 64 func startNetmon(params netmonParams) (int, error) { 65 args, err := prepareNetMonParams(params) 66 if err != nil { 67 return -1, err 68 } 69 70 cmd := exec.Command(args[0], args[1:]...) 71 if err := cmd.Start(); err != nil { 72 return -1, err 73 } 74 75 return cmd.Process.Pid, nil 76 } 77 78 func stopNetmon(pid int) error { 79 if pid <= 0 { 80 return nil 81 } 82 83 sig := syscall.SIGKILL 84 85 netmonLogger().WithFields( 86 logrus.Fields{ 87 "netmon-pid": pid, 88 "netmon-signal": sig, 89 }).Info("Stopping netmon") 90 91 if err := syscall.Kill(pid, sig); err != nil && err != syscall.ESRCH { 92 return err 93 } 94 95 return nil 96 }