Debian Codegraph @

control_lifecycle_test.go

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