Debian Codegraph @

x/mongo/driver/topology/polling_srv_records_test.go

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 // Copyright (C) MongoDB, Inc. 2017-present.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may
4 // not use this file except in compliance with the License. You may obtain
5 // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
6
•7 //go:build ignore
8
9 package topology
10
11 import (
12 "context"
13 "net"
14 "sort"
15 "strings"
16 "sync/atomic"
17 "testing"
18 "time"
19
20 "go.mongodb.org/mongo-driver/internal/assert"
21 "go.mongodb.org/mongo-driver/internal/require"
22 "go.mongodb.org/mongo-driver/mongo/address"
23 "go.mongodb.org/mongo-driver/mongo/description"
24 "go.mongodb.org/mongo-driver/mongo/options"
25 "go.mongodb.org/mongo-driver/x/mongo/driver/dns"
26 )
27
28 type mockResolver struct {
29 recordsToAdd []*net.SRV
30 recordsToRemove []*net.SRV
31 lookupFail bool
32 lookupTimeout bool
33 ranLookup int32
34 fail int32
35 }
36
37 func newMockResolver(recordsToAdd []*net.SRV, recordsToRemove []*net.SRV, lookupFail bool, lookupTimeout bool) mockResolver {
38 res := mockResolver{
39 recordsToAdd: recordsToAdd,
40 recordsToRemove: recordsToRemove,
41 lookupFail: lookupFail,
42 lookupTimeout: lookupTimeout,
43 }
44 return res
45 }
46
47 func (r *mockResolver) LookupSRV(service, proto, name string) (string, []*net.SRV, error) {
48 atomic.AddInt32(&r.ranLookup, 1)
49 if r.lookupFail {
50 return "", nil, &net.DNSError{}
51 }
52 if r.lookupTimeout {
53 return "", nil, &net.DNSError{IsTimeout: true}
54 }
55 str, addresses, err := net.LookupSRV(service, proto, name)
56 if err != nil {
57 return str, addresses, err
58 }
59 if r.fail > 0 {
60 r.fail--
61 return str, nil, nil
62 }
63
64 // Add/remove records to mimic changing the DNS records.
65 if r.recordsToAdd != nil {
66 addresses = append(addresses, r.recordsToAdd...)
67 }
68 if r.recordsToRemove != nil {
69 for _, removeAddr := range r.recordsToRemove {
70 for j, addr := range addresses {
71 if removeAddr.Target == addr.Target && removeAddr.Port == addr.Port {
72 addresses = append(addresses[:j], addresses[j+1:]...)
73 }
74 }
75 }
76 }
77 return str, addresses, err
78 }
79
80 func (r *mockResolver) LookupTXT(string) ([]string, error) { return nil, nil }
81
82 var srvPollingTests = []struct {
83 name string
84 recordsToAdd []*net.SRV
85 recordsToRemove []*net.SRV
86 lookupFail bool
87 lookupTimeout bool
88 expectedHosts []string
89 heartbeatTime bool
90 }{
91 {"Add new record", []*net.SRV{{"localhost.test.build.10gen.cc.", 27019, 0, 0}}, nil, false, false, []string{"localhost.test.build.10gen.cc:27017", "localhost.test.build.10gen.cc:27018", "localhost.test.build.10gen.cc:27019"}, false},
92 {"Remove existing record", nil, []*net.SRV{{"localhost.test.build.10gen.cc.", 27018, 0, 0}}, false, false, []string{"localhost.test.build.10gen.cc:27017"}, false},
93 {"Replace existing record", []*net.SRV{{"localhost.test.build.10gen.cc.", 27019, 0, 0}}, []*net.SRV{{"localhost.test.build.10gen.cc.", 27018, 0, 0}}, false, false, []string{"localhost.test.build.10gen.cc:27017", "localhost.test.build.10gen.cc:27019"}, false},
94 {"Replace both with one new", []*net.SRV{{"localhost.test.build.10gen.cc.", 27019, 0, 0}}, []*net.SRV{{"localhost.test.build.10gen.cc.", 27017, 0, 0}, {"localhost.test.build.10gen.cc.", 27018, 0, 0}}, false, false, []string{"localhost.test.build.10gen.cc:27019"}, false},
95 {"Replace both with two new", []*net.SRV{{"localhost.test.build.10gen.cc.", 27019, 0, 0}, {"localhost.test.build.10gen.cc.", 27020, 0, 0}}, []*net.SRV{{"localhost.test.build.10gen.cc.", 27017, 0, 0}, {"localhost.test.build.10gen.cc.", 27018, 0, 0}}, false, false, []string{"localhost.test.build.10gen.cc:27019", "localhost.test.build.10gen.cc:27020"}, false},
96 {"DNS lookup timeout", nil, nil, false, true, []string{"localhost.test.build.10gen.cc:27017", "localhost.test.build.10gen.cc:27018"}, true},
97 {"DNS lookup failure", nil, nil, true, false, []string{"localhost.test.build.10gen.cc:27017", "localhost.test.build.10gen.cc:27018"}, true},
98 {"Remove all", nil, []*net.SRV{{"localhost.test.build.10gen.cc.", 27017, 0, 0}, {"localhost.test.build.10gen.cc.", 27018, 0, 0}}, false, false, []string{"localhost.test.build.10gen.cc:27017", "localhost.test.build.10gen.cc:27018"}, true},
99 }
100
101 type serverSorter []description.Server
102
103 func (ss serverSorter) Len() int { return len(ss) }
104 func (ss serverSorter) Swap(i, j int) { ss[i], ss[j] = ss[j], ss[i] }
105 func (ss serverSorter) Less(i, j int) bool {
106 return strings.Compare(ss[i].Addr.String(), ss[j].Addr.String()) < 0
107 }
108
109 func compareHosts(t *testing.T, received []description.Server, expected []string) {
110 t.Helper()
111 if len(received) != len(expected) {
112 t.Fatalf("Number of hosts in topology does not match expected value. Got %v; want %v.", len(received), len(expected))
113 }
114
115 // Take a copy of servers so we don't risk a data race similar to GODRIVER-1301.
116 servers := make([]description.Server, len(received))
117 copy(servers, received)
118 actual := serverSorter(servers)
119 sort.Sort(actual)
120 sort.Strings(expected)
121
122 for i := range servers {
123 if servers[i].Addr.String() != expected[i] {
124 t.Errorf("Hosts in topology differ from expected values. Got %v; want %v.",
125 servers[i].Addr.String(), expected[i])
126 }
127 }
128 }
129
130 func TestPollingSRVRecordsSpec(t *testing.T) {
131 for _, uri := range []string{
132 "mongodb+srv://test1.test.build.10gen.cc/?heartbeatFrequencyMS=100",
133 // Test with user:pass as a regression test for GODRIVER-2620
134 "mongodb+srv://user:[email protected]/?heartbeatFrequencyMS=100",
135 } {
136 t.Run(uri, func(t *testing.T) {
137 testPollingSRVRecordsSpec(t, uri)
138 })
139 }
140 }
141
142 func testPollingSRVRecordsSpec(t *testing.T, uri string) {
143 t.Helper()
144 for _, tt := range srvPollingTests {
145 t.Run(tt.name, func(t *testing.T) {
146 cfg, err := NewConfig(options.Client().ApplyURI(uri), nil)
147 require.NoError(t, err, "error constructing topology configs: %v", err)
148
149 topo, err := New(cfg)
150 require.NoError(t, err, "Could not create the topology: %v", err)
151 mockRes := newMockResolver(tt.recordsToAdd, tt.recordsToRemove, tt.lookupFail, tt.lookupTimeout)
152 topo.dnsResolver = &dns.Resolver{mockRes.LookupSRV, mockRes.LookupTXT}
153 topo.rescanSRVInterval = time.Millisecond * 5
154 err = topo.Connect()
155 require.NoError(t, err, "Could not Connect to the topology: %v", err)
156
157 // wait for description to update
158 sub, err := topo.Subscribe()
159 require.NoError(t, err, "Couldn't subscribe: %v", err)
160 var desc description.Topology
161 for atomic.LoadInt32(&mockRes.ranLookup) < 2 {
162 desc = <-sub.Updates
163 }
164
165 require.True(t, tt.heartbeatTime == topo.pollHeartbeatTime.Load().(bool), "Not polling on correct intervals")
166 compareHosts(t, desc.Servers, tt.expectedHosts)
167 _ = topo.Disconnect(context.Background())
168 })
169 }
170 }
171
172 func TestPollSRVRecords(t *testing.T) {
173 t.Run("Not unknown or sharded topology", func(t *testing.T) {
174 uri := "mongodb+srv://test1.test.build.10gen.cc/?heartbeatFrequencyMS=100"
175 cfg, err := NewConfig(options.Client().ApplyURI(uri), nil)
176 require.NoError(t, err, "error constructing topology config: %v", err)
177
178 topo, err := New(cfg)
179 require.NoError(t, err, "Could not create the topology: %v", err)
180 mockRes := newMockResolver(nil, nil, false, false)
181 topo.dnsResolver = &dns.Resolver{mockRes.LookupSRV, mockRes.LookupTXT}
182 topo.rescanSRVInterval = time.Millisecond * 5
183 err = topo.Connect()
184 require.NoError(t, err, "Could not Connect to the topology: %v", err)
185 topo.serversLock.Lock()
186 topo.fsm.Kind = description.Single
187 topo.desc.Store(description.Topology{
188 Kind: topo.fsm.Kind,
189 Servers: topo.fsm.Servers,
190 SessionTimeoutMinutesPtr: topo.fsm.SessionTimeoutMinutesPtr,
191
192 // TODO(GODRIVER-2885): This field can be removed once
193 // legacy SessionTimeoutMinutes is removed.
194 SessionTimeoutMinutes: topo.fsm.SessionTimeoutMinutes,
195 })
196 topo.serversLock.Unlock()
197
198 // wait for description to update
199 sub, err := topo.Subscribe()
200 if err != nil {
201 t.Fatalf("Couldn't subscribe: %v", err)
202 }
203
204 for i := 0; i < 4; i++ {
205 <-sub.Updates
206 }
207 require.False(t, atomic.LoadInt32(&mockRes.ranLookup) > 0)
208
209 actualHosts := topo.Description().Servers
210 expectedHosts := []string{"localhost.test.build.10gen.cc:27017", "localhost.test.build.10gen.cc:27018"}
211 compareHosts(t, actualHosts, expectedHosts)
212 _ = topo.Disconnect(context.Background())
213
214 })
215 t.Run("Failed Hostname Verification", func(t *testing.T) {
216 uri := "mongodb+srv://test1.test.build.10gen.cc/?heartbeatFrequencyMS=100"
217 cfg, err := NewConfig(options.Client().ApplyURI(uri), nil)
218 require.NoError(t, err, "error constructing topology config: %v", err)
219
220 topo, err := New(cfg)
221 require.NoError(t, err, "Could not create the topology: %v", err)
222 mockRes := newMockResolver([]*net.SRV{{"blah.bleh", 27019, 0, 0}, {"localhost.test.build.10gen.cc.", 27020, 0, 0}}, nil, false, false)
223 topo.dnsResolver = &dns.Resolver{mockRes.LookupSRV, mockRes.LookupTXT}
224 topo.rescanSRVInterval = time.Millisecond * 5
225 err = topo.Connect()
226 require.NoError(t, err, "Could not Connect to the topology: %v", err)
227
228 // wait for description to update
229 sub, err := topo.Subscribe()
230 require.NoError(t, err, "Couldn't subscribe: %v", err)
231 var desc description.Topology
232 for atomic.LoadInt32(&mockRes.ranLookup) < 2 {
233 desc = <-sub.Updates
234 }
235
236 require.False(t, topo.pollHeartbeatTime.Load().(bool))
237 expectedHosts := []string{"localhost.test.build.10gen.cc:27017", "localhost.test.build.10gen.cc:27018", "localhost.test.build.10gen.cc:27020"}
238 compareHosts(t, desc.Servers, expectedHosts)
239 _ = topo.Disconnect(context.Background())
240
241 })
242 t.Run("Return to polling time", func(t *testing.T) {
243 uri := "mongodb+srv://test1.test.build.10gen.cc/?heartbeatFrequencyMS=100"
244 cfg, err := NewConfig(options.Client().ApplyURI(uri), nil)
245 require.NoError(t, err, "error constructing topology config: %v", err)
246
247 topo, err := New(cfg)
248 require.NoError(t, err, "Could not create the topology: %v", err)
249 mockRes := newMockResolver(nil, nil, false, false)
250 mockRes.fail = 1
251 topo.dnsResolver = &dns.Resolver{mockRes.LookupSRV, mockRes.LookupTXT}
252 topo.rescanSRVInterval = time.Millisecond * 5
253 err = topo.Connect()
254 require.NoError(t, err, "Could not Connect to the topology: %v", err)
255
256 // wait for description to update
257 sub, err := topo.Subscribe()
258 require.NoError(t, err, "Couldn't subscribe: %v", err)
259 var desc description.Topology
260 for atomic.LoadInt32(&mockRes.ranLookup) < 3 {
261 desc = <-sub.Updates
262 }
263
264 require.False(t, topo.pollHeartbeatTime.Load().(bool))
265 expectedHosts := []string{"localhost.test.build.10gen.cc:27017", "localhost.test.build.10gen.cc:27018"}
266 compareHosts(t, desc.Servers, expectedHosts)
267 _ = topo.Disconnect(context.Background())
268 })
269 }
270
271 func TestPollingSRVRecordsLoadBalanced(t *testing.T) {
272 createLBTopology := func(t *testing.T, uri string) *Topology {
273 t.Helper()
274
275 cfg, err := NewConfig(options.Client().ApplyURI(uri).SetLoadBalanced(true), nil)
276 require.NoError(t, err, "error constructing topology config: %v", err)
277
278 topo, err := New(cfg)
279 require.NoError(t, err, "Could not create the topology: %v", err)
280
281 return topo
282 }
283
284 t.Run("pollingRequired is set to false", func(t *testing.T) {
285 topo := createLBTopology(t, "mongodb+srv://test24.test.build.10gen.cc/?heartbeatFrequencyMS=100")
286 assert.False(t, topo.pollingRequired, "expected SRV polling to not be required, but it is")
287 })
288
289 t.Run("new records are not detected", func(t *testing.T) {
290 recordsToAdd := []*net.SRV{{"localhost.test.build.10gen.cc.", 27019, 0, 0}}
291 mockResolver := newMockResolver(recordsToAdd, nil, false, false)
292 dnsResolver := &dns.Resolver{
293 LookupSRV: mockResolver.LookupSRV,
294 LookupTXT: mockResolver.LookupTXT,
295 }
296
297 topo := createLBTopology(t, "mongodb+srv://test3.test.build.10gen.cc")
298 topo.dnsResolver = dnsResolver
299 topo.rescanSRVInterval = time.Millisecond * 5
300 err := topo.Connect()
301 assert.Nil(t, err, "Connect error: %v", err)
302 defer func() {
303 _ = topo.Disconnect(context.Background())
304 }()
305
306 // Wait for 2*rescanInterval and assert that polling was not done and the final host list only contains the
307 // original host.
308 time.Sleep(2 * topo.rescanSRVInterval)
309 lookupCalledTimes := atomic.LoadInt32(&mockResolver.ranLookup)
310 assert.Equal(t, int32(0), lookupCalledTimes, "expected SRV lookup to occur 0 times, got %d", lookupCalledTimes)
311 expectedHosts := []string{"localhost.test.build.10gen.cc:27017"}
312 compareHosts(t, topo.Description().Servers, expectedHosts)
313 })
314 }
315
316 func TestPollSRVRecordsMaxHosts(t *testing.T) {
317 // simulateSRVPoll creates a topology with srvMaxHosts, mocks the DNS changes described by
318 // recordsToAdd and recordsToRemove, and returns the topology.
319 simulateSRVPoll := func(srvMaxHosts int, recordsToAdd []*net.SRV, recordsToRemove []*net.SRV) (*Topology, func(ctx context.Context) error) {
320 t.Helper()
321
322 uri := "mongodb+srv://test1.test.build.10gen.cc/?heartbeatFrequencyMS=100"
323 cfg, err := NewConfig(options.Client().ApplyURI(uri).SetSRVMaxHosts(srvMaxHosts), nil)
324 require.NoError(t, err, "error constructing topology config: %v", err)
325
326 topo, err := New(cfg)
327 require.NoError(t, err, "Could not create the topology: %v", err)
328
329 mockRes := newMockResolver(recordsToAdd, recordsToRemove, false, false)
330 topo.dnsResolver = &dns.Resolver{mockRes.LookupSRV, mockRes.LookupTXT}
331 topo.rescanSRVInterval = time.Millisecond * 5
332 err = topo.Connect()
333 assert.Nil(t, err, "Connect error: %v", err)
334
335 // Wait for description to update.
336 sub, err := topo.Subscribe()
337 assert.Nil(t, err, "Subscribe error: %v", err)
338 for atomic.LoadInt32(&mockRes.ranLookup) < 2 {
339 <-sub.Updates
340 }
341
342 return topo, topo.Disconnect
343 }
344
345 t.Run("SRVMaxHosts is 0", func(t *testing.T) {
346 recordsToAdd := []*net.SRV{{"localhost.test.build.10gen.cc.", 27019, 0, 0}, {"localhost.test.build.10gen.cc.", 27020, 0, 0}}
347 recordsToRemove := []*net.SRV{{"localhost.test.build.10gen.cc.", 27018, 0, 0}}
348 topo, disconnect := simulateSRVPoll(0, recordsToAdd, recordsToRemove)
349 defer func() { _ = disconnect(context.Background()) }()
350
351 actualHosts := topo.Description().Servers
352 expectedHosts := []string{
353 "localhost.test.build.10gen.cc:27017",
354 "localhost.test.build.10gen.cc:27019",
355 "localhost.test.build.10gen.cc:27020",
356 }
357 compareHosts(t, actualHosts, expectedHosts)
358 })
359 t.Run("SRVMaxHosts is number of hosts", func(t *testing.T) {
360 recordsToAdd := []*net.SRV{{"localhost.test.build.10gen.cc.", 27019, 0, 0}, {"localhost.test.build.10gen.cc.", 27020, 0, 0}}
361 recordsToRemove := []*net.SRV{{"localhost.test.build.10gen.cc.", 27017, 0, 0}, {"localhost.test.build.10gen.cc.", 27018, 0, 0}}
362 topo, disconnect := simulateSRVPoll(2, recordsToAdd, recordsToRemove)
363 defer func() { _ = disconnect(context.Background()) }()
364
365 actualHosts := topo.Description().Servers
366 expectedHosts := []string{
367 "localhost.test.build.10gen.cc:27019",
368 "localhost.test.build.10gen.cc:27020",
369 }
370 compareHosts(t, actualHosts, expectedHosts)
371 })
372 t.Run("SRVMaxHosts is less than number of hosts", func(t *testing.T) {
373 recordsToAdd := []*net.SRV{{"localhost.test.build.10gen.cc.", 27019, 0, 0}, {"localhost.test.build.10gen.cc.", 27020, 0, 0}}
374 recordsToRemove := []*net.SRV{{"localhost.test.build.10gen.cc.", 27018, 0, 0}}
375 topo, disconnect := simulateSRVPoll(2, recordsToAdd, recordsToRemove)
376 defer func() { _ = disconnect(context.Background()) }()
377
378 actualHosts := topo.Description().Servers
379 assert.Equal(t, 2, len(actualHosts), "expected 2 hosts in topology server list, got %v", len(actualHosts))
380
381 expectedHost := "localhost.test.build.10gen.cc:27017"
382 addr := address.Address(expectedHost).Canonicalize()
383 _, ok := topo.servers[addr]
384 assert.True(t, ok, "topology server list did not contain expected host %v", expectedHost)
385 })
386 }
387
388 func TestPollSRVRecordsServiceName(t *testing.T) {
389 // simulateSRVPoll creates a topology with srvServiceName, mocks the DNS changes described by
390 // recordsToAdd and recordsToRemove, and returns the topology.
391 simulateSRVPoll := func(srvServiceName string, recordsToAdd []*net.SRV, recordsToRemove []*net.SRV) (*Topology, func(ctx context.Context) error) {
392 t.Helper()
393
394 uri := "mongodb+srv://test22.test.build.10gen.cc/?heartbeatFrequencyMS=100&srvServiceName=customname"
395 cfg, err := NewConfig(options.Client().ApplyURI(uri).SetSRVServiceName(srvServiceName), nil)
396 require.NoError(t, err, "error constructing topology config: %v", err)
397
398 topo, err := New(cfg)
399 require.NoError(t, err, "Could not create the topology: %v", err)
400
401 mockRes := newMockResolver(recordsToAdd, recordsToRemove, false, false)
402 topo.dnsResolver = &dns.Resolver{mockRes.LookupSRV, mockRes.LookupTXT}
403 topo.rescanSRVInterval = time.Millisecond * 5
404 err = topo.Connect()
405 assert.Nil(t, err, "Connect error: %v", err)
406
407 // Wait for description to update.
408 sub, err := topo.Subscribe()
409 assert.Nil(t, err, "Subscribe error: %v", err)
410 for atomic.LoadInt32(&mockRes.ranLookup) < 2 {
411 <-sub.Updates
412 }
413
414 return topo, topo.Disconnect
415 }
416
417 t.Run("SRVServiceName is customname", func(t *testing.T) {
418 recordsToAdd := []*net.SRV{{"localhost.test.build.10gen.cc.", 27019, 0, 0}, {"localhost.test.build.10gen.cc.", 27020, 0, 0}}
419 recordsToRemove := []*net.SRV{{"localhost.test.build.10gen.cc.", 27017, 0, 0}, {"localhost.test.build.10gen.cc.", 27018, 0, 0}}
420 topo, disconnect := simulateSRVPoll("customname", recordsToAdd, recordsToRemove)
421 defer func() { _ = disconnect(context.Background()) }()
422
423 actualHosts := topo.Description().Servers
424 expectedHosts := []string{
425 "localhost.test.build.10gen.cc:27019",
426 "localhost.test.build.10gen.cc:27020",
427 }
428 compareHosts(t, actualHosts, expectedHosts)
429 })
430 }