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