From 7f92c8c4c629e99fd00c4ade296c34b8bd2d9c2d Mon Sep 17 00:00:00 2001 From: Martynas Pumputis Date: Wed, 13 Jul 2016 17:41:23 +0100 Subject: [PATCH] Add a safer version of WithNetNS* The introduced functions are executing the work function via a process which executes "nsenter --net=path weaveutil ...". --- net/netns.go | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/net/netns.go b/net/netns.go index 25e956d0..a501f158 100644 --- a/net/netns.go +++ b/net/netns.go @@ -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= weaveutil [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) +}