Add a safer version of WithNetNS*
The introduced functions are executing the work function via a process which executes "nsenter --net=path weaveutil ...".
This commit is contained in:
1 parent
eb5b16614c
commit
7f92c8c4c6
1 file changed
+27
@@ -1,7 +1,10 @@
|
||||
package net
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os/exec"
|
||||
"runtime"
|
||||
|
||||
"github.com/vishvananda/netlink"
|
||||
@@ -63,3 +66,27 @@ func WithNetNSLinkByPidUnsafe(pid int, ifName string, work func(link netlink.Lin
|
||||
|
||||
return WithNetNSLinkUnsafe(ns, ifName, work)
|
||||
}
|
||||
|
||||
// A safe version of WithNetNS* which creates a process executing
|
||||
// "nsenter --net=<ns-path> weaveutil <cmd> [args]".
|
||||
func WithNetNS(nsPath string, cmd string, args ...string) (string, error) {
|
||||
var stdout, stderr bytes.Buffer
|
||||
|
||||
args = append([]string{"--net=" + nsPath, "weaveutil", cmd}, args...)
|
||||
c := exec.Command("nsenter", args...)
|
||||
c.Stdout = &stdout
|
||||
c.Stderr = &stderr
|
||||
if err := c.Run(); err != nil {
|
||||
return "", fmt.Errorf("%s: %s", string(stderr.Bytes()), err)
|
||||
}
|
||||
|
||||
return string(stdout.Bytes()), nil
|
||||
}
|
||||
|
||||
func WithNetNSByPid(pid int, cmd string, args ...string) (string, error) {
|
||||
return WithNetNS(NSPathByPid(pid), cmd, args...)
|
||||
}
|
||||
|
||||
func NSPathByPid(pid int) string {
|
||||
return fmt.Sprintf("/proc/%d/ns/net", pid)
|
||||
}
|
||||
Reference in new issue
Block a user