context_unix.go 1019 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. // +build linux freebsd
  2. package testutils
  3. import (
  4. "os"
  5. "runtime"
  6. "syscall"
  7. "testing"
  8. "github.com/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. 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. }
  36. // RunningOnCircleCI returns true if being executed on libnetwork Circle CI setup
  37. func RunningOnCircleCI() bool {
  38. return os.Getenv("CIRCLECI") != ""
  39. }