context_unix.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. //go:build linux || freebsd
  2. package netnsutils
  3. import (
  4. "fmt"
  5. "runtime"
  6. "strconv"
  7. "testing"
  8. "github.com/docker/docker/internal/testutils"
  9. "github.com/docker/docker/libnetwork/ns"
  10. "github.com/pkg/errors"
  11. "github.com/vishvananda/netns"
  12. "golang.org/x/sys/unix"
  13. )
  14. // OSContext is a handle to a test OS context.
  15. type OSContext struct {
  16. origNS, newNS netns.NsHandle
  17. tid int
  18. caller string // The file:line where SetupTestOSContextEx was called, for interpolating into error messages.
  19. }
  20. // SetupTestOSContextEx joins the current goroutine to a new network namespace.
  21. //
  22. // Compared to [SetupTestOSContext], this function allows goroutines to be
  23. // spawned which are associated with the same OS context via the returned
  24. // OSContext value.
  25. //
  26. // Example usage:
  27. //
  28. // c := SetupTestOSContext(t)
  29. // defer c.Cleanup(t)
  30. func SetupTestOSContextEx(t *testing.T) *OSContext {
  31. runtime.LockOSThread()
  32. origNS, err := netns.Get()
  33. if err != nil {
  34. runtime.UnlockOSThread()
  35. t.Fatalf("Failed to open initial netns: %v", err)
  36. }
  37. c := OSContext{
  38. tid: unix.Gettid(),
  39. origNS: origNS,
  40. }
  41. c.newNS, err = netns.New()
  42. if err != nil {
  43. // netns.New() is not atomic: it could have encountered an error
  44. // after unsharing the current thread's network namespace.
  45. c.restore(t)
  46. t.Fatalf("Failed to enter netns: %v", err)
  47. }
  48. // Since we are switching to a new test namespace make
  49. // sure to re-initialize initNs context
  50. ns.Init()
  51. nl := ns.NlHandle()
  52. lo, err := nl.LinkByName("lo")
  53. if err != nil {
  54. c.restore(t)
  55. t.Fatalf("Failed to get handle to loopback interface 'lo' in new netns: %v", err)
  56. }
  57. if err := nl.LinkSetUp(lo); err != nil {
  58. c.restore(t)
  59. t.Fatalf("Failed to enable loopback interface in new netns: %v", err)
  60. }
  61. _, file, line, ok := runtime.Caller(0)
  62. if ok {
  63. c.caller = file + ":" + strconv.Itoa(line)
  64. }
  65. return &c
  66. }
  67. // Cleanup tears down the OS context. It must be called from the same goroutine
  68. // as the [SetupTestOSContextEx] call which returned c.
  69. //
  70. // Explicit cleanup is required as (*testing.T).Cleanup() makes no guarantees
  71. // about which goroutine the cleanup functions are invoked on.
  72. func (c *OSContext) Cleanup(t *testing.T) {
  73. t.Helper()
  74. if unix.Gettid() != c.tid {
  75. t.Fatalf("c.Cleanup() must be called from the same goroutine as SetupTestOSContextEx() (%s)", c.caller)
  76. }
  77. if err := c.newNS.Close(); err != nil {
  78. t.Logf("Warning: netns closing failed (%v)", err)
  79. }
  80. c.restore(t)
  81. ns.Init()
  82. }
  83. func (c *OSContext) restore(t *testing.T) {
  84. t.Helper()
  85. if err := netns.Set(c.origNS); err != nil {
  86. t.Logf("Warning: failed to restore thread netns (%v)", err)
  87. } else {
  88. runtime.UnlockOSThread()
  89. }
  90. if err := c.origNS.Close(); err != nil {
  91. t.Logf("Warning: netns closing failed (%v)", err)
  92. }
  93. }
  94. // Set sets the OS context of the calling goroutine to c and returns a teardown
  95. // function to restore the calling goroutine's OS context and release resources.
  96. // The teardown function accepts an optional Logger argument.
  97. //
  98. // This is a lower-level interface which is less ergonomic than c.Go() but more
  99. // composable with other goroutine-spawning utilities such as [sync.WaitGroup]
  100. // or [golang.org/x/sync/errgroup.Group].
  101. //
  102. // Example usage:
  103. //
  104. // func TestFoo(t *testing.T) {
  105. // osctx := testutils.SetupTestOSContextEx(t)
  106. // defer osctx.Cleanup(t)
  107. // var eg errgroup.Group
  108. // eg.Go(func() error {
  109. // teardown, err := osctx.Set()
  110. // if err != nil {
  111. // return err
  112. // }
  113. // defer teardown(t)
  114. // // ...
  115. // })
  116. // if err := eg.Wait(); err != nil {
  117. // t.Fatalf("%+v", err)
  118. // }
  119. // }
  120. func (c *OSContext) Set() (func(testutils.Logger), error) {
  121. runtime.LockOSThread()
  122. orig, err := netns.Get()
  123. if err != nil {
  124. runtime.UnlockOSThread()
  125. return nil, errors.Wrap(err, "failed to open initial netns for goroutine")
  126. }
  127. if err := errors.WithStack(netns.Set(c.newNS)); err != nil {
  128. runtime.UnlockOSThread()
  129. return nil, errors.Wrap(err, "failed to set goroutine network namespace")
  130. }
  131. tid := unix.Gettid()
  132. _, file, line, callerOK := runtime.Caller(0)
  133. return func(log testutils.Logger) {
  134. if unix.Gettid() != tid {
  135. msg := "teardown function must be called from the same goroutine as c.Set()"
  136. if callerOK {
  137. msg += fmt.Sprintf(" (%s:%d)", file, line)
  138. }
  139. panic(msg)
  140. }
  141. if err := netns.Set(orig); err != nil && log != nil {
  142. log.Logf("Warning: failed to restore goroutine thread netns (%v)", err)
  143. } else {
  144. runtime.UnlockOSThread()
  145. }
  146. if err := orig.Close(); err != nil && log != nil {
  147. log.Logf("Warning: netns closing failed (%v)", err)
  148. }
  149. }, nil
  150. }