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
|
|
|
|
|
|
|
"github.com/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
|
|
|
|
|
|
|
return func() {
|
|
|
|
if err := syscall.Close(fd); err != nil {
|
|
|
|
t.Logf("Warning: netns closing failed (%v)", err)
|
|
|
|
}
|
|
|
|
runtime.UnlockOSThread()
|
|
|
|
}
|
|
|
|
}
|