Debian Codegraph @

udp/netchange_darwin_test.go

raw
1 //go:build darwin && !ios && !e2e_testing
2 // +build darwin,!ios,!e2e_testing
3
4 package udp
5
6 import (
7 "context"
8 "encoding/binary"
9 "os"
10 "testing"
11 "time"
12
13 "github.com/slackhq/nebula/config"
14 "github.com/slackhq/nebula/test"
15 "github.com/stretchr/testify/assert"
16 "github.com/stretchr/testify/require"
17 "go.uber.org/goleak"
18 "golang.org/x/sys/unix"
19 )
20
21 // routeMsg builds the first four bytes of a routing message, which is all isNetworkChange reads.
22 func routeMsg(msgType uint8, extra int) []byte {
23 msg := make([]byte, 4+extra)
24 binary.NativeEndian.PutUint16(msg[0:2], uint16(len(msg)))
25 msg[2] = unix.RTM_VERSION
26 msg[3] = msgType
27 return msg
28 }
29
30 func TestIsNetworkChange(t *testing.T) {
31 // The three that mean our addressing may have moved
32 assert.True(t, isNetworkChange(routeMsg(unix.RTM_NEWADDR, 0)))
33 assert.True(t, isNetworkChange(routeMsg(unix.RTM_DELADDR, 0)))
34 assert.True(t, isNetworkChange(routeMsg(unix.RTM_IFINFO, 0)))
35
36 // Route churn is not something a rebind helps with
37 assert.False(t, isNetworkChange(routeMsg(unix.RTM_ADD, 0)))
38 assert.False(t, isNetworkChange(routeMsg(unix.RTM_DELETE, 0)))
39 assert.False(t, isNetworkChange(routeMsg(unix.RTM_GET, 0)))
40
41 // Garbage must not be mistaken for a change
42 assert.False(t, isNetworkChange(nil), "empty")
43 assert.False(t, isNetworkChange([]byte{0, 0, 0}), "short header")
44
45 wrongVersion := routeMsg(unix.RTM_NEWADDR, 0)
46 wrongVersion[2] = unix.RTM_VERSION + 1
47 assert.False(t, isNetworkChange(wrongVersion), "wrong rtm_version")
48
49 lying := routeMsg(unix.RTM_NEWADDR, 0)
50 binary.NativeEndian.PutUint16(lying[0:2], 512)
51 assert.False(t, isNetworkChange(lying), "msglen longer than what we read")
52 }
53
54 // socketPair returns a connected pair of datagram sockets, the first wrapped the same way the routing socket is. It
55 // stands in for the kernel so the watch loop can be driven with synthetic messages.
56 func socketPair(t *testing.T) (*os.File, int) {
57 t.Helper()
58
59 fds, err := unix.Socketpair(unix.AF_UNIX, unix.SOCK_DGRAM, 0)
60 require.NoError(t, err)
61 require.NoError(t, unix.SetNonblock(fds[0], true))
62
63 f := os.NewFile(uintptr(fds[0]), "route")
64 t.Cleanup(func() {
65 _ = f.Close()
66 _ = unix.Close(fds[1])
67 })
68
69 return f, fds[1]
70 }
71
72 func TestWatchRouteSocketCoalescesABurst(t *testing.T) {
73 sock, kernel := socketPair(t)
74 changes := make(chan struct{}, 1)
75
76 done := make(chan struct{})
77 go func() {
78 watchRouteSocket(test.NewLogger(), sock, changes)
79 close(done)
80 }()
81
82 // One network change is a burst of messages. All of these land inside the settle window, so they must produce
83 // exactly one report rather than one apiece.
84 for range 5 {
85 _, err := unix.Write(kernel, routeMsg(unix.RTM_NEWADDR, 8))
86 require.NoError(t, err)
87 }
88 // Uninteresting messages in the middle of a burst must not add a report of their own either.
89 _, err := unix.Write(kernel, routeMsg(unix.RTM_ADD, 8))
90 require.NoError(t, err)
91
92 select {
93 case <-changes:
94 case <-time.After(netChangeSettleWindow * 4):
95 t.Fatal("a burst should have reported a change")
96 }
97
98 // Nothing more from that burst
99 select {
100 case <-changes:
101 t.Fatal("a burst should report exactly once")
102 case <-time.After(netChangeSettleWindow):
103 }
104
105 // A change after the window has closed is a separate event and gets its own report.
106 _, err = unix.Write(kernel, routeMsg(unix.RTM_IFINFO, 8))
107 require.NoError(t, err)
108 select {
109 case <-changes:
110 case <-time.After(netChangeSettleWindow * 4):
111 t.Fatal("a later change should report again")
112 }
113
114 // Closing the socket is how the real thing shuts down
115 require.NoError(t, sock.Close())
116 select {
117 case <-done:
118 case <-time.After(time.Second * 5):
119 t.Fatal("watchRouteSocket did not return after the socket was closed")
120 }
121 }
122
123 func TestWatchRouteSocketIgnoresUninterestingMessages(t *testing.T) {
124 sock, kernel := socketPair(t)
125 changes := make(chan struct{}, 1)
126
127 done := make(chan struct{})
128 go func() {
129 watchRouteSocket(test.NewLogger(), sock, changes)
130 close(done)
131 }()
132
133 for _, msgType := range []uint8{unix.RTM_ADD, unix.RTM_DELETE, unix.RTM_GET, unix.RTM_MISS} {
134 _, err := unix.Write(kernel, routeMsg(msgType, 8))
135 require.NoError(t, err)
136 }
137
138 select {
139 case <-changes:
140 t.Fatal("route churn alone must not report a change")
141 case <-time.After(netChangeSettleWindow * 2):
142 }
143
144 require.NoError(t, sock.Close())
145 select {
146 case <-done:
147 case <-time.After(time.Second * 5):
148 t.Fatal("watchRouteSocket did not return after the socket was closed")
149 }
150 }
151
152 // TestWatchRouteSocketDropsRatherThanBlocks covers the coalescing send. A reader that is busy rebinding must not
153 // wedge the watcher, and a second pending "the network moved" tells it nothing new anyway.
154 func TestWatchRouteSocketDropsRatherThanBlocks(t *testing.T) {
155 sock, kernel := socketPair(t)
156 changes := make(chan struct{}, 1)
157
158 done := make(chan struct{})
159 go func() {
160 watchRouteSocket(test.NewLogger(), sock, changes)
161 close(done)
162 }()
163
164 // Nobody is reading changes, so after the first report the buffer is full for the rest of this test
165 for range 3 {
166 _, err := unix.Write(kernel, routeMsg(unix.RTM_NEWADDR, 8))
167 require.NoError(t, err)
168 time.Sleep(netChangeSettleWindow + time.Millisecond*250)
169 }
170
171 // The watcher must still be alive and responsive to a close
172 require.NoError(t, sock.Close())
173 select {
174 case <-done:
175 case <-time.After(time.Second * 5):
176 t.Fatal("watchRouteSocket wedged on a full channel")
177 }
178
179 assert.Len(t, changes, 1, "the pending report should have coalesced, not queued")
180 }
181
182 // TestWatchNetworkChangesStopsWithContext covers the detection path against a real routing socket, including that
183 // cancelling the context closes the channel so a ranging caller falls out of its loop.
184 func TestWatchNetworkChangesStopsWithContext(t *testing.T) {
185 ctx, cancel := context.WithCancel(context.Background())
186
187 changes, err := watchNetworkChanges(ctx, test.NewLogger())
188 require.NoError(t, err)
189 require.NotNil(t, changes, "darwin should support watching")
190
191 drained := make(chan struct{})
192 go func() {
193 for range changes {
194 }
195 close(drained)
196 }()
197
198 cancel()
199 select {
200 case <-drained:
201 case <-time.After(time.Second * 5):
202 t.Fatal("cancelling the context should close the changes channel")
203 }
204 }
205
206 // TestNetworkChangeMonitorStopsWithContext drives the whole monitor against a real routing socket: Start must block
207 // watching, and cancelling the context (which is all Control does on shutdown, it never stops the monitor directly)
208 // must return it and clean up the watch goroutines.
209 func TestNetworkChangeMonitorStopsWithContext(t *testing.T) {
210 // IgnoreCurrent because other tests in this package leave readers running; we only care about what this test
211 // leaks itself.
212 defer goleak.VerifyNone(t, goleak.IgnoreCurrent())
213
214 ctx, cancel := context.WithCancel(context.Background())
215
216 l := test.NewLogger()
217 c := config.NewC(l)
218 require.NoError(t, c.LoadString("listen:\n rebind_on_network_change: true\n"))
219 m := NewNetworkChangeMonitor(ctx, l, c)
220
221 done := make(chan struct{})
222 go func() {
223 m.Start(func() {})
224 close(done)
225 }()
226
227 // Start should be sitting on the routing socket, not have fallen out. If it returned early it either failed to
228 // watch or no-op'd, both of which we want to catch.
229 select {
230 case <-done:
231 t.Fatal("Start returned instead of watching")
232 case <-time.After(time.Millisecond * 250):
233 }
234
235 cancel()
236 select {
237 case <-done:
238 case <-time.After(time.Second * 5):
239 t.Fatal("Start did not return after the context was cancelled")
240 }
241
242 // Starting again after the context is dead must not open anything.
243 m.Start(func() {})
244 }