context_unix.go 920 B

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