Handle namespaces with care

- After creating new netns, switch back to main netns
- Lock thread during test and test setup
This commit is contained in:
zachgersh 2016-02-21 19:23:14 -08:00
parent 2708bdf2f5
commit 1e3d680d13
2 changed files with 27 additions and 8 deletions

View File

@ -1,7 +1,9 @@
package main_test
import (
"fmt"
"os"
"runtime"
"github.com/onsi/gomega/gexec"
@ -32,21 +34,38 @@ var _ = AfterSuite(func() {
func makeNetworkNS(containerID string) string {
namespace := "/var/run/netns/" + containerID
pid := unix.Getpid()
tid := unix.Gettid()
err := os.MkdirAll("/var/run/netns", 0600)
Expect(err).NotTo(HaveOccurred())
err = unix.Unshare(unix.CLONE_NEWNET)
runtime.LockOSThread()
defer runtime.UnlockOSThread()
go (func() {
defer GinkgoRecover()
err = unix.Unshare(unix.CLONE_NEWNET)
Expect(err).NotTo(HaveOccurred())
fd, err := os.Create(namespace)
Expect(err).NotTo(HaveOccurred())
defer fd.Close()
err = unix.Mount("/proc/self/ns/net", namespace, "none", unix.MS_BIND, "")
Expect(err).NotTo(HaveOccurred())
})()
Eventually(namespace).Should(BeAnExistingFile())
fd, err := unix.Open(fmt.Sprintf("/proc/%d/task/%d/ns/net", pid, tid), unix.O_RDONLY, 0)
Expect(err).NotTo(HaveOccurred())
fd, err := os.Create(namespace)
Expect(err).NotTo(HaveOccurred())
defer fd.Close()
defer unix.Close(fd)
err = unix.Mount("/proc/self/ns/net", namespace, "none", unix.MS_BIND, "")
Expect(err).NotTo(HaveOccurred())
_, _, e1 := unix.Syscall(unix.SYS_SETNS, uintptr(fd), uintptr(unix.CLONE_NEWNET), 0)
Expect(e1).To(BeZero())
Expect(namespace).To(BeAnExistingFile())
return namespace
}

View File

@ -57,7 +57,7 @@ var _ = Describe("Loopback", func() {
Eventually(session).Should(gexec.Exit(0))
var lo *net.Interface
err = ns.WithNetNSPath(networkNS, false, func(hostNS *os.File) error {
err = ns.WithNetNSPath(networkNS, true, func(hostNS *os.File) error {
var err error
lo, err = net.InterfaceByName("lo")
return err