2021-08-23 09:14:53 -04:00
|
|
|
//go:build linux || freebsd
|
2016-02-17 14:24:43 -05:00
|
|
|
// +build linux freebsd
|
2016-01-29 20:08:11 -05:00
|
|
|
|
2015-09-07 13:33:28 -04:00
|
|
|
package testutils
|
2015-08-31 14:55:58 -04:00
|
|
|
|
|
|
|
import (
|
|
|
|
"runtime"
|
|
|
|
"syscall"
|
|
|
|
"testing"
|
2015-09-07 13:33:28 -04:00
|
|
|
|
2021-04-05 20:24:47 -04:00
|
|
|
"github.com/docker/docker/libnetwork/ns"
|
2015-08-31 14:55:58 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
// SetupTestOSContext joins a new network namespace, and returns its associated
|
|
|
|
// teardown function.
|
|
|
|
//
|
|
|
|
// Example usage:
|
|
|
|
//
|
|
|
|
// defer SetupTestOSContext(t)()
|
|
|
|
//
|
|
|
|
func SetupTestOSContext(t *testing.T) func() {
|
|
|
|
runtime.LockOSThread()
|
|
|
|
if err := syscall.Unshare(syscall.CLONE_NEWNET); err != nil {
|
|
|
|
t.Fatalf("Failed to enter netns: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
fd, err := syscall.Open("/proc/self/ns/net", syscall.O_RDONLY, 0)
|
|
|
|
if err != nil {
|
|
|
|
t.Fatal("Failed to open netns file")
|
|
|
|
}
|
|
|
|
|
|
|
|
// Since we are switching to a new test namespace make
|
|
|
|
// sure to re-initialize initNs context
|
2015-09-07 13:33:28 -04:00
|
|
|
ns.Init()
|
2015-08-31 14:55:58 -04:00
|
|
|
|
2019-08-15 16:39:14 -04:00
|
|
|
runtime.LockOSThread()
|
|
|
|
|
2015-08-31 14:55:58 -04:00
|
|
|
return func() {
|
|
|
|
if err := syscall.Close(fd); err != nil {
|
|
|
|
t.Logf("Warning: netns closing failed (%v)", err)
|
|
|
|
}
|
|
|
|
runtime.UnlockOSThread()
|
|
|
|
}
|
|
|
|
}
|