control_lifecycle_test.go 8.3 KB

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