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