github.com/jfrazelle/docker@v1.1.2-0.20210712172922-bf78e25fe508/libnetwork/testutils/context_unix.go (about) 1 // +build linux freebsd 2 3 package testutils 4 5 import ( 6 "runtime" 7 "syscall" 8 "testing" 9 10 "github.com/docker/docker/libnetwork/ns" 11 ) 12 13 // SetupTestOSContext joins a new network namespace, and returns its associated 14 // teardown function. 15 // 16 // Example usage: 17 // 18 // defer SetupTestOSContext(t)() 19 // 20 func SetupTestOSContext(t *testing.T) func() { 21 runtime.LockOSThread() 22 if err := syscall.Unshare(syscall.CLONE_NEWNET); err != nil { 23 t.Fatalf("Failed to enter netns: %v", err) 24 } 25 26 fd, err := syscall.Open("/proc/self/ns/net", syscall.O_RDONLY, 0) 27 if err != nil { 28 t.Fatal("Failed to open netns file") 29 } 30 31 // Since we are switching to a new test namespace make 32 // sure to re-initialize initNs context 33 ns.Init() 34 35 runtime.LockOSThread() 36 37 return func() { 38 if err := syscall.Close(fd); err != nil { 39 t.Logf("Warning: netns closing failed (%v)", err) 40 } 41 runtime.UnlockOSThread() 42 } 43 }