From ad6ac9391c4635745d44d186cba97745ea0f2097 Mon Sep 17 00:00:00 2001 From: Samuel Ortiz Date: Wed, 14 Dec 2016 19:47:05 +0100 Subject: [PATCH] sandbox: Force netns unmount and removal when restoring ns.Close() will not remove and unmount the networking namespace if it's not currently marked as mounted. When we restore a sandbox, we generate the sandbox netns from ns.GetNS() which does not mark the sandbox as mounted. There currently is a PR open to fix that in the ns package: https://github.com/containernetworking/cni/pull/342 but meanwhile this patch fixes a netns leak when restoring a pod. Signed-off-by: Samuel Ortiz --- server/sandbox.go | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/server/sandbox.go b/server/sandbox.go index 7e9a38b5..83c0eef5 100644 --- a/server/sandbox.go +++ b/server/sandbox.go @@ -14,13 +14,15 @@ import ( "github.com/containernetworking/cni/pkg/ns" "k8s.io/kubernetes/pkg/fields" pb "k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/runtime" + "golang.org/x/sys/unix" ) type sandboxNetNs struct { sync.Mutex - ns ns.NetNS - symlink *os.File - closed bool + ns ns.NetNS + symlink *os.File + closed bool + restored bool } func (ns *sandboxNetNs) symlinkCreate(name string) error { @@ -94,7 +96,7 @@ func netNsGet(nspath, name string) (*sandboxNetNs, error) { return nil, err } - netNs := &sandboxNetNs{ns: netNS, closed: false,} + netNs := &sandboxNetNs{ns: netNS, closed: false, restored: true} if symlink { fd, err := os.Open(nspath) @@ -228,6 +230,16 @@ func (s *sandbox) netNsRemove() error { return err } + if s.netns.restored { + if err := unix.Unmount(s.netns.ns.Path(), unix.MNT_DETACH); err != nil { + return err + } + + if err := os.RemoveAll(s.netns.ns.Path()); err != nil { + return err + } + } + s.netns.closed = true return nil }