control_lifecycle_test.go 8.1 KB

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