control_lifecycle_test.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. package nebula
  2. import (
  3. "context"
  4. "errors"
  5. "io"
  6. "net/netip"
  7. "sync"
  8. "testing"
  9. "time"
  10. "github.com/gaissmai/bart"
  11. "github.com/slackhq/nebula/config"
  12. "github.com/slackhq/nebula/overlay/tio"
  13. "github.com/slackhq/nebula/routing"
  14. "github.com/slackhq/nebula/test"
  15. "github.com/slackhq/nebula/udp"
  16. "github.com/stretchr/testify/assert"
  17. "github.com/stretchr/testify/require"
  18. )
  19. type fakeDevice struct {
  20. closeOnce sync.Once
  21. closedCh chan struct{}
  22. closed bool
  23. }
  24. func newFakeDevice() *fakeDevice {
  25. return &fakeDevice{closedCh: make(chan struct{})}
  26. }
  27. // Read blocks until Close like a real tun with no traffic, then reports EOF
  28. // the same way a closed device does
  29. func (d *fakeDevice) Read() ([]tio.Packet, error) {
  30. <-d.closedCh
  31. return nil, io.EOF
  32. }
  33. func (d *fakeDevice) Write(p []byte) (int, error) { return len(p), nil }
  34. func (d *fakeDevice) Close() error {
  35. d.closeOnce.Do(func() {
  36. d.closed = true
  37. close(d.closedCh)
  38. })
  39. return nil
  40. }
  41. func (d *fakeDevice) Activate() error { return nil }
  42. func (d *fakeDevice) Networks() []netip.Prefix { return nil }
  43. func (d *fakeDevice) Name() string { return "fake" }
  44. func (d *fakeDevice) RoutesFor(netip.Addr) routing.Gateways { return nil }
  45. func (d *fakeDevice) Queues(int) ([]tio.Queue, error) { return []tio.Queue{d}, nil }
  46. // newReadyControl hand-builds the minimum Control that Main would have
  47. // produced right before Start, including the construction token NewInterface
  48. // takes so waiters block until Close releases the resources
  49. func newReadyControl(t *testing.T) (*Control, *fakeDevice, *fakeConn) {
  50. l := test.NewLogger()
  51. dev := newFakeDevice()
  52. conn := &fakeConn{}
  53. ctx, cancel := context.WithCancel(context.Background())
  54. myVpnNet := netip.MustParsePrefix("10.128.0.1/16")
  55. nt := new(bart.Lite)
  56. nt.Insert(myVpnNet)
  57. cs := &CertState{
  58. myVpnNetworks: []netip.Prefix{myVpnNet},
  59. myVpnNetworksTable: nt,
  60. }
  61. lh, err := NewLightHouseFromConfig(ctx, l, config.NewC(l), cs, nil, nil)
  62. require.NoError(t, err)
  63. f := &Interface{
  64. ctx: ctx,
  65. inside: dev,
  66. outside: conn,
  67. writers: []udp.Conn{conn},
  68. routines: 1,
  69. hostMap: newHostMap(l),
  70. lightHouse: lh,
  71. l: l,
  72. }
  73. f.wg.Add(1)
  74. return &Control{
  75. state: StateReady,
  76. f: f,
  77. l: l,
  78. ctx: ctx,
  79. cancel: cancel,
  80. }, dev, conn
  81. }
  82. func TestControl_StopBeforeStart(t *testing.T) {
  83. c, dev, conn := newReadyControl(t)
  84. // A Stop on a never started control must release everything Main acquired
  85. c.Stop()
  86. assert.Equal(t, StateStopped, c.State())
  87. assert.True(t, dev.closed, "the tun device should have been closed")
  88. assert.True(t, conn.closed, "the udp socket should have been closed")
  89. require.ErrorIs(t, c.ctx.Err(), context.Canceled, "the service context should have been cancelled")
  90. // Wait must return promptly now that the resources are released
  91. require.NoError(t, c.Wait())
  92. // A stopped control can never be started
  93. require.ErrorIs(t, c.Start(), ErrAlreadyStopped)
  94. // A second Stop is a harmless no-op
  95. c.Stop()
  96. assert.Equal(t, StateStopped, c.State())
  97. require.NoError(t, c.Wait())
  98. }
  99. func TestControl_WaitBlocksUntilStop(t *testing.T) {
  100. c, _, _ := newReadyControl(t)
  101. done := make(chan error, 1)
  102. go func() { done <- c.Wait() }()
  103. select {
  104. case <-done:
  105. t.Fatal("Wait returned before Stop")
  106. case <-time.After(50 * time.Millisecond):
  107. }
  108. c.Stop()
  109. select {
  110. case err := <-done:
  111. require.NoError(t, err)
  112. case <-time.After(time.Second):
  113. t.Fatal("Wait did not return after Stop")
  114. }
  115. }
  116. type fakeConn struct {
  117. closed bool
  118. rebinds int
  119. }
  120. func (c *fakeConn) Rebind() error { c.rebinds++; return nil }
  121. func (c *fakeConn) LocalAddr() (netip.AddrPort, error) { return netip.AddrPort{}, nil }
  122. func (c *fakeConn) ListenOut(_ udp.EncReader) error { return nil }
  123. func (c *fakeConn) WriteTo(_ []byte, _ netip.AddrPort) error { return nil }
  124. func (c *fakeConn) ReloadConfig(_ *config.C) {}
  125. func (c *fakeConn) SupportsMultipleReaders() bool { return true }
  126. func (c *fakeConn) Close() error { c.closed = true; return nil }
  127. type multiqueueDevice struct {
  128. *fakeDevice
  129. }
  130. // Queues claims multiqueue support but fails to open the second queue,
  131. // exercising the activation error path.
  132. func (d *multiqueueDevice) Queues(n int) ([]tio.Queue, error) {
  133. if n > 1 {
  134. return nil, errors.New("second queue failed to open")
  135. }
  136. return d.fakeDevice.Queues(n)
  137. }
  138. func TestControl_StartMultiqueueFailureReleases(t *testing.T) {
  139. dev := &multiqueueDevice{fakeDevice: newFakeDevice()}
  140. conn := &fakeConn{}
  141. ctx, cancel := context.WithCancel(context.Background())
  142. f := &Interface{
  143. ctx: ctx,
  144. inside: dev,
  145. outside: conn,
  146. writers: []udp.Conn{conn},
  147. routines: 2,
  148. l: test.NewLogger(),
  149. }
  150. f.wg.Add(1)
  151. c := &Control{
  152. state: StateReady,
  153. f: f,
  154. l: test.NewLogger(),
  155. ctx: ctx,
  156. cancel: cancel,
  157. }
  158. // The second reader fails to open, everything must be released
  159. require.Error(t, c.Start())
  160. assert.Equal(t, StateStopped, c.State())
  161. assert.True(t, dev.closed, "the tun device should have been closed")
  162. assert.True(t, conn.closed, "the udp socket should have been closed")
  163. require.ErrorIs(t, c.ctx.Err(), context.Canceled)
  164. // And Wait must not hang on the construction token
  165. require.NoError(t, c.Wait())
  166. }
  167. func TestInterface_CloseIsIdempotent(t *testing.T) {
  168. dev := newFakeDevice()
  169. f := &Interface{
  170. inside: dev,
  171. l: test.NewLogger(),
  172. }
  173. f.wg.Add(1)
  174. require.NoError(t, f.Close())
  175. assert.True(t, dev.closed)
  176. // A second Close must not double release the wg token or the device
  177. require.NoError(t, f.Close())
  178. require.NoError(t, f.wait())
  179. }
  180. func TestControl_FatalErrorReportsThroughWait(t *testing.T) {
  181. c, dev, conn := newReadyControl(t)
  182. // Mirror what Start wires up, without needing real packet readers
  183. c.f.triggerShutdown = c.Stop
  184. c.state = StateStarted
  185. boom := errors.New("boom")
  186. c.f.onFatal(boom)
  187. require.ErrorIs(t, c.Wait(), boom)
  188. assert.Equal(t, StateStopped, c.State())
  189. assert.True(t, dev.closed)
  190. assert.True(t, conn.closed)
  191. // A second fatal error must not fire the shutdown again or replace the first
  192. c.f.onFatal(errors.New("later"))
  193. require.ErrorIs(t, c.Wait(), boom)
  194. // Wait stays factual, a Stop after the death does not mask the error
  195. c.Stop()
  196. require.ErrorIs(t, c.Wait(), boom)
  197. }
  198. func TestControl_ConcurrentStopAndStart(t *testing.T) {
  199. c, _, _ := newReadyControl(t)
  200. var wg sync.WaitGroup
  201. for i := 0; i < 2; i++ {
  202. wg.Go(func() { c.Stop() })
  203. }
  204. wg.Go(func() { _ = c.Start() })
  205. wg.Go(func() {
  206. _ = c.Wait()
  207. // A returned Wait must always observe the final state, no matter how
  208. // the race resolved
  209. assert.Equal(t, StateStopped, c.State())
  210. })
  211. wg.Wait()
  212. // However the race resolves, the control must end fully stopped with no
  213. // panic and Wait must observe the final state
  214. require.NoError(t, c.Wait())
  215. assert.Equal(t, StateStopped, c.State())
  216. require.ErrorIs(t, c.Start(), ErrAlreadyStopped)
  217. }
  218. func TestControl_StartStopLifecycle(t *testing.T) {
  219. c, dev, conn := newReadyControl(t)
  220. require.NoError(t, c.Start())
  221. assert.Equal(t, StateStarted, c.State())
  222. require.ErrorIs(t, c.Start(), ErrAlreadyStarted)
  223. // Stop must unpark the reader blocked in the device and release everything
  224. c.Stop()
  225. assert.Equal(t, StateStopped, c.State())
  226. assert.True(t, dev.closed, "the tun device should have been closed")
  227. assert.True(t, conn.closed, "the udp socket should have been closed")
  228. require.ErrorIs(t, c.ctx.Err(), context.Canceled)
  229. // The reader drained off a closed device, that is not a fatal error
  230. require.NoError(t, c.Wait())
  231. require.ErrorIs(t, c.Start(), ErrAlreadyStopped)
  232. }
  233. func TestControl_RebindIsGatedByState(t *testing.T) {
  234. c, _, conn := newReadyControl(t)
  235. // A rebind before Start reaches nothing, the interface is not up
  236. c.RebindUDPServer()
  237. assert.Equal(t, 0, conn.rebinds, "rebind before start must be a no-op")
  238. require.NoError(t, c.Start())
  239. c.RebindUDPServer()
  240. assert.Equal(t, 1, conn.rebinds, "rebind while started must reach the conn")
  241. // A rebind racing a completed stop must not touch the closed conn
  242. c.Stop()
  243. require.NoError(t, c.Wait())
  244. c.RebindUDPServer()
  245. assert.Equal(t, 1, conn.rebinds, "rebind after stop must be a no-op")
  246. }