context_unix.go 913 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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. func SetupTestOSContext(t *testing.T) func() {
  17. runtime.LockOSThread()
  18. if err := syscall.Unshare(syscall.CLONE_NEWNET); err != nil {
  19. t.Fatalf("Failed to enter netns: %v", err)
  20. }
  21. fd, err := syscall.Open("/proc/self/ns/net", syscall.O_RDONLY, 0)
  22. if err != nil {
  23. t.Fatal("Failed to open netns file")
  24. }
  25. // Since we are switching to a new test namespace make
  26. // sure to re-initialize initNs context
  27. ns.Init()
  28. runtime.LockOSThread()
  29. return func() {
  30. if err := syscall.Close(fd); err != nil {
  31. t.Logf("Warning: netns closing failed (%v)", err)
  32. }
  33. runtime.UnlockOSThread()
  34. }
  35. }