1
0

control_lifecycle_test.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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) Queues(int) ([]tio.Queue, error) { return []tio.Queue{d}, nil }
  47. // newReadyControl hand-builds the minimum Control that Main would have
  48. // produced right before Start, including the construction token NewInterface
  49. // takes so waiters block until Close releases the resources
  50. func newReadyControl(t *testing.T) (*Control, *fakeDevice, *fakeConn) {
  51. l := test.NewLogger()
  52. dev := newFakeDevice()
  53. conn := &fakeConn{}
  54. ctx, cancel := context.WithCancel(context.Background())
  55. myVpnNet := netip.MustParsePrefix("10.128.0.1/16")
  56. nt := new(bart.Lite)
  57. nt.Insert(myVpnNet)
  58. cs := &CertState{
  59. myVpnNetworks: []netip.Prefix{myVpnNet},
  60. myVpnNetworksTable: nt,
  61. }
  62. lh, err := NewLightHouseFromConfig(ctx, l, config.NewC(l), cs, nil, nil)
  63. require.NoError(t, err)
  64. f := &Interface{
  65. ctx: ctx,
  66. inside: dev,
  67. outside: conn,
  68. writers: []udp.Conn{conn},
  69. batchers: make([]*batch.MultiCoalescer, 1),
  70. routines: 1,
  71. hostMap: newHostMap(l),
  72. lightHouse: lh,
  73. l: l,
  74. }
  75. f.wg.Add(1)
  76. return &Control{
  77. state: StateReady,
  78. f: f,
  79. l: l,
  80. ctx: ctx,
  81. cancel: cancel,
  82. }, dev, conn
  83. }
  84. func TestControl_StopBeforeStart(t *testing.T) {
  85. c, dev, conn := newReadyControl(t)
  86. // A Stop on a never started control must release everything Main acquired
  87. c.Stop()
  88. assert.Equal(t, StateStopped, c.State())
  89. assert.True(t, dev.closed, "the tun device should have been closed")
  90. assert.True(t, conn.closed, "the udp socket should have been closed")
  91. require.ErrorIs(t, c.ctx.Err(), context.Canceled, "the service context should have been cancelled")
  92. // Wait must return promptly now that the resources are released
  93. require.NoError(t, c.Wait())
  94. // A stopped control can never be started
  95. err := c.Start()
  96. require.ErrorIs(t, err, 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, _ func()) error { return nil }
  126. func (c *fakeConn) WriteTo(_ []byte, _ netip.AddrPort) error { return nil }
  127. func (c *fakeConn) WriteBatch(bufs [][]byte, _ []netip.AddrPort) (int, error) {
  128. return len(bufs), nil
  129. }
  130. func (c *fakeConn) ReloadConfig(_ *config.C) {}
  131. func (c *fakeConn) SupportsMultipleReaders() bool { return true }
  132. func (c *fakeConn) Close() error { c.closed = true; return nil }
  133. type multiqueueDevice struct {
  134. *fakeDevice
  135. }
  136. // Queues claims multiqueue support but fails to open the second queue,
  137. // exercising the activation error path.
  138. func (d *multiqueueDevice) Queues(n int) ([]tio.Queue, error) {
  139. if n > 1 {
  140. return nil, errors.New("second queue failed to open")
  141. }
  142. return d.fakeDevice.Queues(n)
  143. }
  144. func TestControl_StartMultiqueueFailureReleases(t *testing.T) {
  145. dev := &multiqueueDevice{fakeDevice: newFakeDevice()}
  146. conn := &fakeConn{}
  147. ctx, cancel := context.WithCancel(context.Background())
  148. f := &Interface{
  149. ctx: ctx,
  150. inside: dev,
  151. outside: conn,
  152. writers: []udp.Conn{conn},
  153. batchers: make([]*batch.MultiCoalescer, 2),
  154. routines: 2,
  155. l: test.NewLogger(),
  156. }
  157. f.wg.Add(1)
  158. c := &Control{
  159. state: StateReady,
  160. f: f,
  161. l: test.NewLogger(),
  162. ctx: ctx,
  163. cancel: cancel,
  164. }
  165. // The second reader fails to open, everything must be released
  166. err := c.Start()
  167. require.Error(t, err)
  168. assert.Equal(t, StateStopped, c.State())
  169. assert.True(t, dev.closed, "the tun device should have been closed")
  170. assert.True(t, conn.closed, "the udp socket should have been closed")
  171. require.ErrorIs(t, c.ctx.Err(), context.Canceled)
  172. // And Wait must not hang on the construction token
  173. require.NoError(t, c.Wait())
  174. }
  175. func TestInterface_CloseIsIdempotent(t *testing.T) {
  176. dev := newFakeDevice()
  177. f := &Interface{
  178. inside: dev,
  179. l: test.NewLogger(),
  180. }
  181. f.wg.Add(1)
  182. require.NoError(t, f.Close())
  183. assert.True(t, dev.closed)
  184. // A second Close must not double release the wg token or the device
  185. require.NoError(t, f.Close())
  186. require.NoError(t, f.wait())
  187. }
  188. func TestControl_FatalErrorReportsThroughWait(t *testing.T) {
  189. c, dev, conn := newReadyControl(t)
  190. // Mirror what Start wires up, without needing real packet readers
  191. c.f.triggerShutdown = c.Stop
  192. c.state = StateStarted
  193. boom := errors.New("boom")
  194. c.f.onFatal(boom)
  195. require.ErrorIs(t, c.Wait(), boom)
  196. assert.Equal(t, StateStopped, c.State())
  197. assert.True(t, dev.closed)
  198. assert.True(t, conn.closed)
  199. // A second fatal error must not fire the shutdown again or replace the first
  200. c.f.onFatal(errors.New("later"))
  201. require.ErrorIs(t, c.Wait(), boom)
  202. // Wait stays factual, a Stop after the death does not mask the error
  203. c.Stop()
  204. require.ErrorIs(t, c.Wait(), boom)
  205. }
  206. func TestControl_ConcurrentStopAndStart(t *testing.T) {
  207. c, _, _ := newReadyControl(t)
  208. var wg sync.WaitGroup
  209. for range 2 {
  210. wg.Go(func() { c.Stop() })
  211. }
  212. wg.Go(func() { _ = c.Start() })
  213. wg.Go(func() {
  214. _ = c.Wait()
  215. // A returned Wait must always observe the final state, no matter how
  216. // the race resolved
  217. assert.Equal(t, StateStopped, c.State())
  218. })
  219. wg.Wait()
  220. // However the race resolves, the control must end fully stopped with no
  221. // panic and Wait must observe the final state
  222. require.NoError(t, c.Wait())
  223. assert.Equal(t, StateStopped, c.State())
  224. err := c.Start()
  225. require.ErrorIs(t, err, ErrAlreadyStopped)
  226. }
  227. func TestControl_StartStopLifecycle(t *testing.T) {
  228. c, dev, conn := newReadyControl(t)
  229. err := c.Start()
  230. require.NoError(t, err)
  231. assert.Equal(t, StateStarted, c.State())
  232. err = c.Start()
  233. require.ErrorIs(t, err, ErrAlreadyStarted)
  234. // Stop must unpark the reader blocked in the device and release everything
  235. c.Stop()
  236. assert.Equal(t, StateStopped, c.State())
  237. assert.True(t, dev.closed, "the tun device should have been closed")
  238. assert.True(t, conn.closed, "the udp socket should have been closed")
  239. require.ErrorIs(t, c.ctx.Err(), context.Canceled)
  240. // The reader drained off a closed device, that is not a fatal error
  241. require.NoError(t, c.Wait())
  242. err = c.Start()
  243. require.ErrorIs(t, err, ErrAlreadyStopped)
  244. }
  245. func TestControl_RebindIsGatedByState(t *testing.T) {
  246. c, _, conn := newReadyControl(t)
  247. // A rebind before Start reaches nothing, the interface is not up
  248. c.RebindUDPServer()
  249. assert.Equal(t, 0, conn.rebinds, "rebind before start must be a no-op")
  250. err := c.Start()
  251. require.NoError(t, err)
  252. c.RebindUDPServer()
  253. assert.Equal(t, 1, conn.rebinds, "rebind while started must reach the conn")
  254. // A rebind racing a completed stop must not touch the closed conn
  255. c.Stop()
  256. require.NoError(t, c.Wait())
  257. c.RebindUDPServer()
  258. assert.Equal(t, 1, conn.rebinds, "rebind after stop must be a no-op")
  259. }