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 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631
|
// 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"
"errors"
"fmt"
"sync/atomic"
"testing"
"time"
"go.mongodb.org/mongo-driver/internal"
"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/x/mongo/driver"
"go.mongodb.org/mongo-driver/x/mongo/driver/connstring"
)
const testTimeout = 2 * time.Second
func noerr(t *testing.T, err error) {
t.Helper()
if err != nil {
t.Errorf("Unexpected error: %v", err)
t.FailNow()
}
}
func compareErrors(err1, err2 error) bool {
if err1 == nil && err2 == nil {
return true
}
if err1 == nil || err2 == nil {
return false
}
if err1.Error() != err2.Error() {
return false
}
return true
}
func TestServerSelection(t *testing.T) {
var selectFirst description.ServerSelectorFunc = func(_ description.Topology, candidates []description.Server) ([]description.Server, error) {
if len(candidates) == 0 {
return []description.Server{}, nil
}
return candidates[0:1], nil
}
var selectNone description.ServerSelectorFunc = func(description.Topology, []description.Server) ([]description.Server, error) {
return []description.Server{}, nil
}
var errSelectionError = errors.New("encountered an error in the selector")
var selectError description.ServerSelectorFunc = func(description.Topology, []description.Server) ([]description.Server, error) {
return nil, errSelectionError
}
t.Run("Success", func(t *testing.T) {
topo, err := New()
noerr(t, err)
desc := description.Topology{
Servers: []description.Server{
{Addr: address.Address("one"), Kind: description.Standalone},
{Addr: address.Address("two"), Kind: description.Standalone},
{Addr: address.Address("three"), Kind: description.Standalone},
},
}
subCh := make(chan description.Topology, 1)
subCh <- desc
state := newServerSelectionState(selectFirst, nil)
srvs, err := topo.selectServerFromSubscription(context.Background(), subCh, state)
noerr(t, err)
if len(srvs) != 1 {
t.Errorf("Incorrect number of descriptions returned. got %d; want %d", len(srvs), 1)
}
if srvs[0].Addr != desc.Servers[0].Addr {
t.Errorf("Incorrect sever selected. got %s; want %s", srvs[0].Addr, desc.Servers[0].Addr)
}
})
t.Run("Compatibility Error Min Version Too High", func(t *testing.T) {
topo, err := New()
noerr(t, err)
desc := description.Topology{
Kind: description.Single,
Servers: []description.Server{
{Addr: address.Address("one:27017"), Kind: description.Standalone, WireVersion: &description.VersionRange{Max: 11, Min: 11}},
{Addr: address.Address("two:27017"), Kind: description.Standalone, WireVersion: &description.VersionRange{Max: 9, Min: 2}},
{Addr: address.Address("three:27017"), Kind: description.Standalone, WireVersion: &description.VersionRange{Max: 9, Min: 2}},
},
}
want := fmt.Errorf(
"server at %s requires wire version %d, but this version of the Go driver only supports up to %d",
desc.Servers[0].Addr.String(),
desc.Servers[0].WireVersion.Min,
SupportedWireVersions.Max,
)
desc.CompatibilityErr = want
atomic.StoreInt64(&topo.connectionstate, connected)
topo.desc.Store(desc)
_, err = topo.SelectServer(context.Background(), selectFirst)
assert.Equal(t, err, want, "expected %v, got %v", want, err)
})
t.Run("Compatibility Error Max Version Too Low", func(t *testing.T) {
topo, err := New()
noerr(t, err)
desc := description.Topology{
Kind: description.Single,
Servers: []description.Server{
{Addr: address.Address("one:27017"), Kind: description.Standalone, WireVersion: &description.VersionRange{Max: 1, Min: 1}},
{Addr: address.Address("two:27017"), Kind: description.Standalone, WireVersion: &description.VersionRange{Max: 9, Min: 2}},
{Addr: address.Address("three:27017"), Kind: description.Standalone, WireVersion: &description.VersionRange{Max: 9, Min: 2}},
},
}
want := fmt.Errorf(
"server at %s reports wire version %d, but this version of the Go driver requires "+
"at least %d (MongoDB %s)",
desc.Servers[0].Addr.String(),
desc.Servers[0].WireVersion.Max,
SupportedWireVersions.Min,
MinSupportedMongoDBVersion,
)
desc.CompatibilityErr = want
atomic.StoreInt64(&topo.connectionstate, connected)
topo.desc.Store(desc)
_, err = topo.SelectServer(context.Background(), selectFirst)
assert.Equal(t, err, want, "expected %v, got %v", want, err)
})
t.Run("Updated", func(t *testing.T) {
topo, err := New()
noerr(t, err)
desc := description.Topology{Servers: []description.Server{}}
subCh := make(chan description.Topology, 1)
subCh <- desc
resp := make(chan []description.Server)
go func() {
state := newServerSelectionState(selectFirst, nil)
srvs, err := topo.selectServerFromSubscription(context.Background(), subCh, state)
noerr(t, err)
resp <- srvs
}()
desc = description.Topology{
Servers: []description.Server{
{Addr: address.Address("one"), Kind: description.Standalone},
{Addr: address.Address("two"), Kind: description.Standalone},
{Addr: address.Address("three"), Kind: description.Standalone},
},
}
select {
case subCh <- desc:
case <-time.After(100 * time.Millisecond):
t.Error("Timed out while trying to send topology description")
}
var srvs []description.Server
select {
case srvs = <-resp:
case <-time.After(100 * time.Millisecond):
t.Errorf("Timed out while trying to retrieve selected servers")
}
if len(srvs) != 1 {
t.Errorf("Incorrect number of descriptions returned. got %d; want %d", len(srvs), 1)
}
if srvs[0].Addr != desc.Servers[0].Addr {
t.Errorf("Incorrect sever selected. got %s; want %s", srvs[0].Addr, desc.Servers[0].Addr)
}
})
t.Run("Cancel", func(t *testing.T) {
desc := description.Topology{
Servers: []description.Server{
{Addr: address.Address("one"), Kind: description.Standalone},
{Addr: address.Address("two"), Kind: description.Standalone},
{Addr: address.Address("three"), Kind: description.Standalone},
},
}
topo, err := New()
noerr(t, err)
subCh := make(chan description.Topology, 1)
subCh <- desc
resp := make(chan error)
ctx, cancel := context.WithCancel(context.Background())
go func() {
state := newServerSelectionState(selectNone, nil)
_, err := topo.selectServerFromSubscription(ctx, subCh, state)
resp <- err
}()
select {
case err := <-resp:
t.Errorf("Received error from server selection too soon: %v", err)
case <-time.After(100 * time.Millisecond):
}
cancel()
select {
case err = <-resp:
case <-time.After(100 * time.Millisecond):
t.Errorf("Timed out while trying to retrieve selected servers")
}
want := ServerSelectionError{Wrapped: context.Canceled, Desc: desc}
assert.Equal(t, err, want, "Incorrect error received. got %v; want %v", err, want)
})
t.Run("Timeout", func(t *testing.T) {
desc := description.Topology{
Servers: []description.Server{
{Addr: address.Address("one"), Kind: description.Standalone},
{Addr: address.Address("two"), Kind: description.Standalone},
{Addr: address.Address("three"), Kind: description.Standalone},
},
}
topo, err := New()
noerr(t, err)
subCh := make(chan description.Topology, 1)
subCh <- desc
resp := make(chan error)
timeout := make(chan time.Time)
go func() {
state := newServerSelectionState(selectNone, timeout)
_, err := topo.selectServerFromSubscription(context.Background(), subCh, state)
resp <- err
}()
select {
case err := <-resp:
t.Errorf("Received error from server selection too soon: %v", err)
case timeout <- time.Now():
}
select {
case err = <-resp:
case <-time.After(100 * time.Millisecond):
t.Errorf("Timed out while trying to retrieve selected servers")
}
if err == nil {
t.Fatalf("did not receive error from server selection")
}
})
t.Run("Error", func(t *testing.T) {
desc := description.Topology{
Servers: []description.Server{
{Addr: address.Address("one"), Kind: description.Standalone},
{Addr: address.Address("two"), Kind: description.Standalone},
{Addr: address.Address("three"), Kind: description.Standalone},
},
}
topo, err := New()
noerr(t, err)
subCh := make(chan description.Topology, 1)
subCh <- desc
resp := make(chan error)
timeout := make(chan time.Time)
go func() {
state := newServerSelectionState(selectError, timeout)
_, err := topo.selectServerFromSubscription(context.Background(), subCh, state)
resp <- err
}()
select {
case err = <-resp:
case <-time.After(100 * time.Millisecond):
t.Errorf("Timed out while trying to retrieve selected servers")
}
if err == nil {
t.Fatalf("did not receive error from server selection")
}
})
t.Run("findServer returns topology kind", func(t *testing.T) {
topo, err := New()
noerr(t, err)
atomic.StoreInt64(&topo.connectionstate, connected)
srvr, err := ConnectServer(address.Address("one"), topo.updateCallback, topo.id)
noerr(t, err)
topo.servers[address.Address("one")] = srvr
desc := topo.desc.Load().(description.Topology)
desc.Kind = description.Single
topo.desc.Store(desc)
selected := description.Server{Addr: address.Address("one")}
ss, err := topo.FindServer(selected)
noerr(t, err)
if ss.Kind != description.Single {
t.Errorf("findServer does not properly set the topology description kind. got %v; want %v", ss.Kind, description.Single)
}
})
t.Run("Update on not primary error", func(t *testing.T) {
topo, err := New()
noerr(t, err)
topo.cfg.cs.HeartbeatInterval = time.Minute
atomic.StoreInt64(&topo.connectionstate, connected)
addr1 := address.Address("one")
addr2 := address.Address("two")
addr3 := address.Address("three")
desc := description.Topology{
Servers: []description.Server{
{Addr: addr1, Kind: description.RSPrimary},
{Addr: addr2, Kind: description.RSSecondary},
{Addr: addr3, Kind: description.RSSecondary},
},
}
// manually add the servers to the topology
for _, srv := range desc.Servers {
s, err := ConnectServer(srv.Addr, topo.updateCallback, topo.id)
noerr(t, err)
topo.servers[srv.Addr] = s
}
// Send updated description
desc = description.Topology{
Servers: []description.Server{
{Addr: addr1, Kind: description.RSSecondary},
{Addr: addr2, Kind: description.RSPrimary},
{Addr: addr3, Kind: description.RSSecondary},
},
}
subCh := make(chan description.Topology, 1)
subCh <- desc
// send a not primary error to the server forcing an update
serv, err := topo.FindServer(desc.Servers[0])
noerr(t, err)
atomic.StoreInt64(&serv.connectionstate, connected)
_ = serv.ProcessError(driver.Error{Message: internal.LegacyNotPrimary}, initConnection{})
resp := make(chan []description.Server)
go func() {
// server selection should discover the new topology
state := newServerSelectionState(description.WriteSelector(), nil)
srvs, err := topo.selectServerFromSubscription(context.Background(), subCh, state)
noerr(t, err)
resp <- srvs
}()
var srvs []description.Server
select {
case srvs = <-resp:
case <-time.After(100 * time.Millisecond):
t.Errorf("Timed out while trying to retrieve selected servers")
}
if len(srvs) != 1 {
t.Errorf("Incorrect number of descriptions returned. got %d; want %d", len(srvs), 1)
}
if srvs[0].Addr != desc.Servers[1].Addr {
t.Errorf("Incorrect sever selected. got %s; want %s", srvs[0].Addr, desc.Servers[1].Addr)
}
})
t.Run("fast path does not subscribe or check timeouts", func(t *testing.T) {
// Assert that the server selection fast path does not create a Subscription or check for timeout errors.
topo, err := New()
noerr(t, err)
topo.cfg.cs.HeartbeatInterval = time.Minute
atomic.StoreInt64(&topo.connectionstate, connected)
primaryAddr := address.Address("one")
desc := description.Topology{
Servers: []description.Server{
{Addr: primaryAddr, Kind: description.RSPrimary},
},
}
topo.desc.Store(desc)
for _, srv := range desc.Servers {
s, err := ConnectServer(srv.Addr, topo.updateCallback, topo.id)
noerr(t, err)
topo.servers[srv.Addr] = s
}
// Manually close subscriptions so calls to Subscribe will error and pass in a cancelled context to ensure the
// fast path ignores timeout errors.
topo.subscriptionsClosed = true
ctx, cancel := context.WithCancel(context.Background())
cancel()
selectedServer, err := topo.SelectServer(ctx, description.WriteSelector())
noerr(t, err)
selectedAddr := selectedServer.(*SelectedServer).address
assert.Equal(t, primaryAddr, selectedAddr, "expected address %v, got %v", primaryAddr, selectedAddr)
})
t.Run("default to selecting from subscription if fast path fails", func(t *testing.T) {
topo, err := New()
noerr(t, err)
topo.cfg.cs.HeartbeatInterval = time.Minute
atomic.StoreInt64(&topo.connectionstate, connected)
desc := description.Topology{
Servers: []description.Server{},
}
topo.desc.Store(desc)
topo.subscriptionsClosed = true
_, err = topo.SelectServer(context.Background(), description.WriteSelector())
assert.Equal(t, ErrSubscribeAfterClosed, err, "expected error %v, got %v", ErrSubscribeAfterClosed, err)
})
}
func TestSessionTimeout(t *testing.T) {
t.Run("UpdateSessionTimeout", func(t *testing.T) {
topo, err := New()
noerr(t, err)
topo.servers["foo"] = nil
topo.fsm.Servers = []description.Server{
{Addr: address.Address("foo").Canonicalize(), Kind: description.RSPrimary, SessionTimeoutMinutes: 60},
}
ctx, cancel := context.WithTimeout(context.Background(), testTimeout)
defer cancel()
desc := description.Server{
Addr: "foo",
Kind: description.RSPrimary,
SessionTimeoutMinutes: 30,
}
topo.apply(ctx, desc)
currDesc := topo.desc.Load().(description.Topology)
if currDesc.SessionTimeoutMinutes != 30 {
t.Errorf("session timeout minutes mismatch. got: %d. expected: 30", currDesc.SessionTimeoutMinutes)
}
})
t.Run("MultipleUpdates", func(t *testing.T) {
topo, err := New()
noerr(t, err)
topo.fsm.Kind = description.ReplicaSetWithPrimary
topo.servers["foo"] = nil
topo.servers["bar"] = nil
topo.fsm.Servers = []description.Server{
{Addr: address.Address("foo").Canonicalize(), Kind: description.RSPrimary, SessionTimeoutMinutes: 60},
{Addr: address.Address("bar").Canonicalize(), Kind: description.RSSecondary, SessionTimeoutMinutes: 60},
}
ctx, cancel := context.WithTimeout(context.Background(), testTimeout)
defer cancel()
desc1 := description.Server{
Addr: "foo",
Kind: description.RSPrimary,
SessionTimeoutMinutes: 30,
Members: []address.Address{address.Address("foo").Canonicalize(), address.Address("bar").Canonicalize()},
}
// should update because new timeout is lower
desc2 := description.Server{
Addr: "bar",
Kind: description.RSPrimary,
SessionTimeoutMinutes: 20,
Members: []address.Address{address.Address("foo").Canonicalize(), address.Address("bar").Canonicalize()},
}
topo.apply(ctx, desc1)
topo.apply(ctx, desc2)
currDesc := topo.Description()
if currDesc.SessionTimeoutMinutes != 20 {
t.Errorf("session timeout minutes mismatch. got: %d. expected: 20", currDesc.SessionTimeoutMinutes)
}
})
t.Run("NoUpdate", func(t *testing.T) {
topo, err := New()
noerr(t, err)
topo.servers["foo"] = nil
topo.servers["bar"] = nil
topo.fsm.Servers = []description.Server{
{Addr: address.Address("foo").Canonicalize(), Kind: description.RSPrimary, SessionTimeoutMinutes: 60},
{Addr: address.Address("bar").Canonicalize(), Kind: description.RSSecondary, SessionTimeoutMinutes: 60},
}
ctx, cancel := context.WithTimeout(context.Background(), testTimeout)
defer cancel()
desc1 := description.Server{
Addr: "foo",
Kind: description.RSPrimary,
SessionTimeoutMinutes: 20,
Members: []address.Address{address.Address("foo").Canonicalize(), address.Address("bar").Canonicalize()},
}
// should not update because new timeout is higher
desc2 := description.Server{
Addr: "bar",
Kind: description.RSPrimary,
SessionTimeoutMinutes: 30,
Members: []address.Address{address.Address("foo").Canonicalize(), address.Address("bar").Canonicalize()},
}
topo.apply(ctx, desc1)
topo.apply(ctx, desc2)
currDesc := topo.desc.Load().(description.Topology)
if currDesc.SessionTimeoutMinutes != 20 {
t.Errorf("session timeout minutes mismatch. got: %d. expected: 20", currDesc.SessionTimeoutMinutes)
}
})
t.Run("TimeoutDataBearing", func(t *testing.T) {
topo, err := New()
noerr(t, err)
topo.servers["foo"] = nil
topo.servers["bar"] = nil
topo.fsm.Servers = []description.Server{
{Addr: address.Address("foo").Canonicalize(), Kind: description.RSPrimary, SessionTimeoutMinutes: 60},
{Addr: address.Address("bar").Canonicalize(), Kind: description.RSSecondary, SessionTimeoutMinutes: 60},
}
ctx, cancel := context.WithTimeout(context.Background(), testTimeout)
defer cancel()
desc1 := description.Server{
Addr: "foo",
Kind: description.RSPrimary,
SessionTimeoutMinutes: 20,
Members: []address.Address{address.Address("foo").Canonicalize(), address.Address("bar").Canonicalize()},
}
// should not update because not a data bearing server
desc2 := description.Server{
Addr: "bar",
Kind: description.Unknown,
SessionTimeoutMinutes: 10,
Members: []address.Address{address.Address("foo").Canonicalize(), address.Address("bar").Canonicalize()},
}
topo.apply(ctx, desc1)
topo.apply(ctx, desc2)
currDesc := topo.desc.Load().(description.Topology)
if currDesc.SessionTimeoutMinutes != 20 {
t.Errorf("session timeout minutes mismatch. got: %d. expected: 20", currDesc.SessionTimeoutMinutes)
}
})
t.Run("MixedSessionSupport", func(t *testing.T) {
topo, err := New()
noerr(t, err)
topo.fsm.Kind = description.ReplicaSetWithPrimary
topo.servers["one"] = nil
topo.servers["two"] = nil
topo.servers["three"] = nil
topo.fsm.Servers = []description.Server{
{Addr: address.Address("one").Canonicalize(), Kind: description.RSPrimary, SessionTimeoutMinutes: 20},
{Addr: address.Address("two").Canonicalize(), Kind: description.RSSecondary}, // does not support sessions
{Addr: address.Address("three").Canonicalize(), Kind: description.RSPrimary, SessionTimeoutMinutes: 60},
}
ctx, cancel := context.WithTimeout(context.Background(), testTimeout)
defer cancel()
desc := description.Server{
Addr: address.Address("three"), Kind: description.RSSecondary, SessionTimeoutMinutes: 30}
topo.apply(ctx, desc)
currDesc := topo.desc.Load().(description.Topology)
if currDesc.SessionTimeoutMinutes != 0 {
t.Errorf("session timeout minutes mismatch. got: %d. expected: 0", currDesc.SessionTimeoutMinutes)
}
})
}
func TestMinPoolSize(t *testing.T) {
connStr := connstring.ConnString{
Hosts: []string{"localhost:27017"},
MinPoolSize: 10,
MinPoolSizeSet: true,
}
topo, err := New(WithConnString(func(connstring.ConnString) connstring.ConnString { return connStr }))
if err != nil {
t.Errorf("topology.New shouldn't error. got: %v", err)
}
err = topo.Connect()
if err != nil {
t.Errorf("topology.Connect shouldn't error. got: %v", err)
}
}
func TestTopology_String_Race(t *testing.T) {
ch := make(chan bool)
topo := &Topology{
servers: make(map[address.Address]*Server),
}
go func() {
topo.serversLock.Lock()
srv := &Server{}
srv.desc.Store(description.Server{})
topo.servers[address.Address("127.0.0.1:27017")] = srv
topo.serversLock.Unlock()
ch <- true
}()
go func() {
_ = topo.String()
ch <- true
}()
<-ch
<-ch
}
func TestTopologyConstruction(t *testing.T) {
t.Run("construct with URI", func(t *testing.T) {
testCases := []struct {
name string
uri string
pollingRequired bool
}{
{"normal", "mongodb://localhost:27017", false},
{"srv", "mongodb+srv://localhost:27017", true},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
topo, err := New(
WithURI(func(string) string { return tc.uri }),
)
assert.Nil(t, err, "topology.New error: %v", err)
assert.Equal(t, tc.uri, topo.cfg.uri, "expected topology URI to be %v, got %v", tc.uri, topo.cfg.uri)
assert.Equal(t, tc.pollingRequired, topo.pollingRequired,
"expected topo.pollingRequired to be %v, got %v", tc.pollingRequired, topo.pollingRequired)
})
}
})
}
|