summaryrefslogtreecommitdiff
path: root/src/mongo/client/dbclient_rs_test.cpp
blob: 0b3a39975faf93652e5eafe435a876a317d2634d (plain)
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
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
/**
 *    Copyright (C) 2013 10gen Inc.
 *
 *    This program is free software: you can redistribute it and/or  modify
 *    it under the terms of the GNU Affero General Public License, version 3,
 *    as published by the Free Software Foundation.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *    As a special exception, the copyright holders give permission to link the
 *    code of portions of this program with the OpenSSL library under certain
 *    conditions as described in each individual source file and distribute
 *    linked combinations including the program with the OpenSSL library. You
 *    must comply with the GNU Affero General Public License in all respects
 *    for all of the code used other than as permitted herein. If you modify
 *    file(s) with this exception, you may extend this exception to your
 *    version of the file(s), but you are not obligated to do so. If you do not
 *    wish to do so, delete this exception statement from your version. If you
 *    delete this exception statement from all source files in the program,
 *    then also delete it in the license file.
 */

/**
 * This file contains tests for DBClientReplicaSet. The tests mocks the servers
 * the DBClientReplicaSet talks to, so the tests only covers the client side logic.
 */

#include "mongo/platform/basic.h"

#include <map>
#include <memory>
#include <string>
#include <vector>

#include "mongo/base/init.h"
#include "mongo/base/string_data.h"
#include "mongo/client/connpool.h"
#include "mongo/client/dbclient_rs.h"
#include "mongo/client/dbclientinterface.h"
#include "mongo/client/replica_set_monitor.h"
#include "mongo/db/jsobj.h"
#include "mongo/dbtests/mock/mock_conn_registry.h"
#include "mongo/dbtests/mock/mock_replica_set.h"
#include "mongo/stdx/unordered_set.h"
#include "mongo/unittest/unittest.h"
#include "mongo/util/assert_util.h"

namespace mongo {
namespace {

using std::make_pair;
using std::map;
using std::pair;
using std::string;
using std::unique_ptr;
using std::vector;

MONGO_INITIALIZER(DisableReplicaSetMonitorRefreshRetries)(InitializerContext*) {
    ReplicaSetMonitor::disableRefreshRetries_forTest();
    return Status::OK();
}

/**
 * Constructs a metadata object containing the passed server selection metadata.
 */
BSONObj makeMetadata(ReadPreference rp, TagSet tagSet) {
    return ReadPreferenceSetting(rp, std::move(tagSet)).toContainingBSON();
}

/**
 * Basic fixture with one primary and one secondary.
 */
class BasicRS : public unittest::Test {
protected:
    void setUp() {
        ReplicaSetMonitor::cleanup();

        _replSet.reset(new MockReplicaSet("test", 2));
        ConnectionString::setConnectionHook(mongo::MockConnRegistry::get()->getConnStrHook());
    }

    void tearDown() {
        ReplicaSetMonitor::cleanup();
        _replSet.reset();

        mongo::ScopedDbConnection::clearPool();
    }

    MockReplicaSet* getReplSet() {
        return _replSet.get();
    }

private:
    std::unique_ptr<MockReplicaSet> _replSet;
};

void assertOneOfNodesSelected(MockReplicaSet* replSet,
                              ReadPreference rp,
                              const std::vector<std::string> hostNames) {
    DBClientReplicaSet replConn(replSet->getSetName(), replSet->getHosts(), StringData());
    ReplicaSetMonitor::get(replSet->getSetName())->startOrContinueRefresh().refreshAll();
    bool secondaryOk = (rp != ReadPreference::PrimaryOnly);
    auto tagSet = secondaryOk ? TagSet() : TagSet::primaryOnly();
    // We need the command to be a "SecOk command"
    auto res = replConn.runCommand(
        OpMsgRequest::fromDBAndBody("foo", BSON("dbStats" << 1), makeMetadata(rp, tagSet)));
    stdx::unordered_set<HostAndPort> hostSet;
    for (const auto& hostName : hostNames) {
        hostSet.emplace(hostName);
    }
    ASSERT_EQ(hostSet.count(HostAndPort{res->getCommandReply()["host"].str()}), 1u);
}

void assertNodeSelected(MockReplicaSet* replSet, ReadPreference rp, StringData host) {
    assertOneOfNodesSelected(replSet, rp, std::vector<std::string>{host.toString()});
}

TEST_F(BasicRS, QueryPrimary) {
    MockReplicaSet* replSet = getReplSet();
    DBClientReplicaSet replConn(replSet->getSetName(), replSet->getHosts(), StringData());

    Query query;
    query.readPref(mongo::ReadPreference::PrimaryOnly, BSONArray());

    // Note: IdentityNS contains the name of the server.
    unique_ptr<DBClientCursor> cursor = replConn.query(IdentityNS, query);
    BSONObj doc = cursor->next();
    ASSERT_EQUALS(replSet->getPrimary(), doc[HostField.name()].str());
}

TEST_F(BasicRS, CommandPrimary) {
    assertNodeSelected(getReplSet(), ReadPreference::PrimaryOnly, getReplSet()->getPrimary());
}

TEST_F(BasicRS, QuerySecondaryOnly) {
    MockReplicaSet* replSet = getReplSet();
    DBClientReplicaSet replConn(replSet->getSetName(), replSet->getHosts(), StringData());

    Query query;
    query.readPref(mongo::ReadPreference::SecondaryOnly, BSONArray());

    // Note: IdentityNS contains the name of the server.
    unique_ptr<DBClientCursor> cursor = replConn.query(IdentityNS, query);
    BSONObj doc = cursor->next();
    ASSERT_EQUALS(replSet->getSecondaries().front(), doc[HostField.name()].str());
}

TEST_F(BasicRS, CommandSecondaryOnly) {
    assertOneOfNodesSelected(
        getReplSet(), ReadPreference::SecondaryOnly, getReplSet()->getSecondaries());
}

TEST_F(BasicRS, QueryPrimaryPreferred) {
    MockReplicaSet* replSet = getReplSet();
    DBClientReplicaSet replConn(replSet->getSetName(), replSet->getHosts(), StringData());

    // Need up-to-date view, since either host is valid if view is stale.
    ReplicaSetMonitor::get(replSet->getSetName())->startOrContinueRefresh().refreshAll();

    Query query;
    query.readPref(mongo::ReadPreference::PrimaryPreferred, BSONArray());

    // Note: IdentityNS contains the name of the server.
    unique_ptr<DBClientCursor> cursor = replConn.query(IdentityNS, query);
    BSONObj doc = cursor->next();
    ASSERT_EQUALS(replSet->getPrimary(), doc[HostField.name()].str());
}

TEST_F(BasicRS, CommandPrimaryPreferred) {
    assertNodeSelected(getReplSet(), ReadPreference::PrimaryPreferred, getReplSet()->getPrimary());
}

TEST_F(BasicRS, QuerySecondaryPreferred) {
    MockReplicaSet* replSet = getReplSet();
    DBClientReplicaSet replConn(replSet->getSetName(), replSet->getHosts(), StringData());

    // Need up-to-date view, since either host is valid if view is stale.
    ReplicaSetMonitor::get(replSet->getSetName())->startOrContinueRefresh().refreshAll();

    Query query;
    query.readPref(mongo::ReadPreference::SecondaryPreferred, BSONArray());

    // Note: IdentityNS contains the name of the server.
    unique_ptr<DBClientCursor> cursor = replConn.query(IdentityNS, query);
    BSONObj doc = cursor->next();
    ASSERT_EQUALS(replSet->getSecondaries().front(), doc[HostField.name()].str());
}

TEST_F(BasicRS, CommandSecondaryPreferred) {
    assertOneOfNodesSelected(
        getReplSet(), ReadPreference::SecondaryPreferred, getReplSet()->getSecondaries());
}

/**
 * Setup for 2 member replica set will all of the nodes down.
 */
class AllNodesDown : public unittest::Test {
protected:
    void setUp() {
        ReplicaSetMonitor::cleanup();

        _replSet.reset(new MockReplicaSet("test", 2));
        ConnectionString::setConnectionHook(mongo::MockConnRegistry::get()->getConnStrHook());

        vector<HostAndPort> hostList(_replSet->getHosts());
        for (vector<HostAndPort>::const_iterator iter = hostList.begin(); iter != hostList.end();
             ++iter) {
            _replSet->kill(iter->toString());
        }
    }

    void tearDown() {
        ReplicaSetMonitor::cleanup();
        _replSet.reset();

        mongo::ScopedDbConnection::clearPool();
    }

    MockReplicaSet* getReplSet() {
        return _replSet.get();
    }

private:
    std::unique_ptr<MockReplicaSet> _replSet;
};

void assertRunCommandWithReadPrefThrows(MockReplicaSet* replSet, ReadPreference rp) {
    bool isPrimaryOnly = (rp == ReadPreference::PrimaryOnly);
    TagSet ts = isPrimaryOnly ? TagSet::primaryOnly() : TagSet();

    DBClientReplicaSet replConn(replSet->getSetName(), replSet->getHosts(), StringData());
    ASSERT_THROWS(replConn.runCommand(OpMsgRequest::fromDBAndBody(
                      "foo", BSON("dbStats" << 1), makeMetadata(rp, ts))),
                  AssertionException);
}

TEST_F(AllNodesDown, QueryPrimary) {
    MockReplicaSet* replSet = getReplSet();
    DBClientReplicaSet replConn(replSet->getSetName(), replSet->getHosts(), StringData());

    Query query;
    query.readPref(mongo::ReadPreference::PrimaryOnly, BSONArray());
    ASSERT_THROWS(replConn.query(IdentityNS, query), AssertionException);
}

TEST_F(AllNodesDown, CommandPrimary) {
    assertRunCommandWithReadPrefThrows(getReplSet(), ReadPreference::PrimaryOnly);
}

TEST_F(AllNodesDown, QuerySecondaryOnly) {
    MockReplicaSet* replSet = getReplSet();
    DBClientReplicaSet replConn(replSet->getSetName(), replSet->getHosts(), StringData());

    Query query;
    query.readPref(mongo::ReadPreference::SecondaryOnly, BSONArray());
    ASSERT_THROWS(replConn.query(IdentityNS, query), AssertionException);
}

TEST_F(AllNodesDown, CommandSecondaryOnly) {
    assertRunCommandWithReadPrefThrows(getReplSet(), ReadPreference::SecondaryOnly);
}

TEST_F(AllNodesDown, QueryPrimaryPreferred) {
    MockReplicaSet* replSet = getReplSet();
    DBClientReplicaSet replConn(replSet->getSetName(), replSet->getHosts(), StringData());

    Query query;
    query.readPref(mongo::ReadPreference::PrimaryPreferred, BSONArray());
    ASSERT_THROWS(replConn.query(IdentityNS, query), AssertionException);
}

TEST_F(AllNodesDown, CommandPrimaryPreferred) {
    assertRunCommandWithReadPrefThrows(getReplSet(), ReadPreference::PrimaryPreferred);
}

TEST_F(AllNodesDown, QuerySecondaryPreferred) {
    MockReplicaSet* replSet = getReplSet();
    DBClientReplicaSet replConn(replSet->getSetName(), replSet->getHosts(), StringData());

    Query query;
    query.readPref(mongo::ReadPreference::SecondaryPreferred, BSONArray());
    ASSERT_THROWS(replConn.query(IdentityNS, query), AssertionException);
}

TEST_F(AllNodesDown, CommandSecondaryPreferred) {
    assertRunCommandWithReadPrefThrows(getReplSet(), ReadPreference::SecondaryPreferred);
}

TEST_F(AllNodesDown, QueryNearest) {
    MockReplicaSet* replSet = getReplSet();
    DBClientReplicaSet replConn(replSet->getSetName(), replSet->getHosts(), StringData());

    Query query;
    query.readPref(mongo::ReadPreference::Nearest, BSONArray());
    ASSERT_THROWS(replConn.query(IdentityNS, query), AssertionException);
}

TEST_F(AllNodesDown, CommandNearest) {
    assertRunCommandWithReadPrefThrows(getReplSet(), ReadPreference::Nearest);
}

/**
 * Setup for 2 member replica set with the primary down.
 */
class PrimaryDown : public unittest::Test {
protected:
    void setUp() {
        ReplicaSetMonitor::cleanup();

        _replSet.reset(new MockReplicaSet("test", 2));
        ConnectionString::setConnectionHook(mongo::MockConnRegistry::get()->getConnStrHook());
        _replSet->kill(_replSet->getPrimary());
    }

    void tearDown() {
        ReplicaSetMonitor::cleanup();
        _replSet.reset();

        mongo::ScopedDbConnection::clearPool();
    }

    MockReplicaSet* getReplSet() {
        return _replSet.get();
    }

private:
    std::unique_ptr<MockReplicaSet> _replSet;
};

TEST_F(PrimaryDown, QueryPrimary) {
    MockReplicaSet* replSet = getReplSet();
    DBClientReplicaSet replConn(replSet->getSetName(), replSet->getHosts(), StringData());

    Query query;
    query.readPref(mongo::ReadPreference::PrimaryOnly, BSONArray());
    ASSERT_THROWS(replConn.query(IdentityNS, query), AssertionException);
}

TEST_F(PrimaryDown, CommandPrimary) {
    assertRunCommandWithReadPrefThrows(getReplSet(), ReadPreference::PrimaryOnly);
}

TEST_F(PrimaryDown, QuerySecondaryOnly) {
    MockReplicaSet* replSet = getReplSet();
    DBClientReplicaSet replConn(replSet->getSetName(), replSet->getHosts(), StringData());

    Query query;
    query.readPref(mongo::ReadPreference::SecondaryOnly, BSONArray());

    // Note: IdentityNS contains the name of the server.
    unique_ptr<DBClientCursor> cursor = replConn.query(IdentityNS, query);
    BSONObj doc = cursor->next();
    ASSERT_EQUALS(replSet->getSecondaries().front(), doc[HostField.name()].str());
}

TEST_F(PrimaryDown, CommandSecondaryOnly) {
    assertOneOfNodesSelected(
        getReplSet(), ReadPreference::SecondaryOnly, getReplSet()->getSecondaries());
}

TEST_F(PrimaryDown, QueryPrimaryPreferred) {
    MockReplicaSet* replSet = getReplSet();
    DBClientReplicaSet replConn(replSet->getSetName(), replSet->getHosts(), StringData());

    Query query;
    query.readPref(mongo::ReadPreference::PrimaryPreferred, BSONArray());

    // Note: IdentityNS contains the name of the server.
    unique_ptr<DBClientCursor> cursor = replConn.query(IdentityNS, query);
    BSONObj doc = cursor->next();
    ASSERT_EQUALS(replSet->getSecondaries().front(), doc[HostField.name()].str());
}

TEST_F(PrimaryDown, CommandPrimaryPreferred) {
    assertOneOfNodesSelected(
        getReplSet(), ReadPreference::PrimaryPreferred, getReplSet()->getSecondaries());
}

TEST_F(PrimaryDown, QuerySecondaryPreferred) {
    MockReplicaSet* replSet = getReplSet();
    DBClientReplicaSet replConn(replSet->getSetName(), replSet->getHosts(), StringData());

    Query query;
    query.readPref(mongo::ReadPreference::SecondaryPreferred, BSONArray());

    // Note: IdentityNS contains the name of the server.
    unique_ptr<DBClientCursor> cursor = replConn.query(IdentityNS, query);
    BSONObj doc = cursor->next();
    ASSERT_EQUALS(replSet->getSecondaries().front(), doc[HostField.name()].str());
}

TEST_F(PrimaryDown, CommandSecondaryPreferred) {
    assertOneOfNodesSelected(
        getReplSet(), ReadPreference::SecondaryPreferred, getReplSet()->getSecondaries());
}

TEST_F(PrimaryDown, Nearest) {
    MockReplicaSet* replSet = getReplSet();
    DBClientReplicaSet replConn(replSet->getSetName(), replSet->getHosts(), StringData());

    Query query;
    query.readPref(mongo::ReadPreference::Nearest, BSONArray());
    unique_ptr<DBClientCursor> cursor = replConn.query(IdentityNS, query);
    BSONObj doc = cursor->next();
    ASSERT_EQUALS(replSet->getSecondaries().front(), doc[HostField.name()].str());
}

/**
 * Setup for 2 member replica set with the secondary down.
 */
class SecondaryDown : public unittest::Test {
protected:
    void setUp() {
        ReplicaSetMonitor::cleanup();

        _replSet.reset(new MockReplicaSet("test", 2));
        ConnectionString::setConnectionHook(mongo::MockConnRegistry::get()->getConnStrHook());

        _replSet->kill(_replSet->getSecondaries().front());
    }

    void tearDown() {
        ReplicaSetMonitor::cleanup();
        _replSet.reset();

        mongo::ScopedDbConnection::clearPool();
    }

    MockReplicaSet* getReplSet() {
        return _replSet.get();
    }

private:
    std::unique_ptr<MockReplicaSet> _replSet;
};

TEST_F(SecondaryDown, QueryPrimary) {
    MockReplicaSet* replSet = getReplSet();
    DBClientReplicaSet replConn(replSet->getSetName(), replSet->getHosts(), StringData());

    Query query;
    query.readPref(mongo::ReadPreference::PrimaryOnly, BSONArray());

    // Note: IdentityNS contains the name of the server.
    unique_ptr<DBClientCursor> cursor = replConn.query(IdentityNS, query);
    BSONObj doc = cursor->next();
    ASSERT_EQUALS(replSet->getPrimary(), doc[HostField.name()].str());
}

TEST_F(SecondaryDown, CommandPrimary) {
    assertNodeSelected(getReplSet(), ReadPreference::PrimaryOnly, getReplSet()->getPrimary());
}

TEST_F(SecondaryDown, QuerySecondaryOnly) {
    MockReplicaSet* replSet = getReplSet();
    DBClientReplicaSet replConn(replSet->getSetName(), replSet->getHosts(), StringData());

    Query query;
    query.readPref(mongo::ReadPreference::SecondaryOnly, BSONArray());
    ASSERT_THROWS(replConn.query(IdentityNS, query), AssertionException);
}

TEST_F(SecondaryDown, CommandSecondaryOnly) {
    assertRunCommandWithReadPrefThrows(getReplSet(), ReadPreference::SecondaryOnly);
}

TEST_F(SecondaryDown, QueryPrimaryPreferred) {
    MockReplicaSet* replSet = getReplSet();
    DBClientReplicaSet replConn(replSet->getSetName(), replSet->getHosts(), StringData());

    Query query;
    query.readPref(mongo::ReadPreference::PrimaryPreferred, BSONArray());

    // Note: IdentityNS contains the name of the server.
    unique_ptr<DBClientCursor> cursor = replConn.query(IdentityNS, query);
    BSONObj doc = cursor->next();
    ASSERT_EQUALS(replSet->getPrimary(), doc[HostField.name()].str());
}

TEST_F(SecondaryDown, CommandPrimaryPreferred) {
    assertNodeSelected(getReplSet(), ReadPreference::PrimaryPreferred, getReplSet()->getPrimary());
}

TEST_F(SecondaryDown, QuerySecondaryPreferred) {
    MockReplicaSet* replSet = getReplSet();
    DBClientReplicaSet replConn(replSet->getSetName(), replSet->getHosts(), StringData());

    Query query;
    query.readPref(mongo::ReadPreference::SecondaryPreferred, BSONArray());

    // Note: IdentityNS contains the name of the server.
    unique_ptr<DBClientCursor> cursor = replConn.query(IdentityNS, query);
    BSONObj doc = cursor->next();
    ASSERT_EQUALS(replSet->getPrimary(), doc[HostField.name()].str());
}

TEST_F(SecondaryDown, CommandSecondaryPreferred) {
    assertNodeSelected(getReplSet(), ReadPreference::PrimaryPreferred, getReplSet()->getPrimary());
}

TEST_F(SecondaryDown, QueryNearest) {
    MockReplicaSet* replSet = getReplSet();
    DBClientReplicaSet replConn(replSet->getSetName(), replSet->getHosts(), StringData());

    Query query;
    query.readPref(mongo::ReadPreference::Nearest, BSONArray());

    // Note: IdentityNS contains the name of the server.
    unique_ptr<DBClientCursor> cursor = replConn.query(IdentityNS, query);
    BSONObj doc = cursor->next();
    ASSERT_EQUALS(replSet->getPrimary(), doc[HostField.name()].str());
}

TEST_F(SecondaryDown, CommandNearest) {
    assertNodeSelected(getReplSet(), ReadPreference::Nearest, getReplSet()->getPrimary());
}

/**
 * Warning: Tests running this fixture cannot be run in parallel with other tests
 * that uses ConnectionString::setConnectionHook
 */
class TaggedFiveMemberRS : public unittest::Test {
protected:
    void setUp() {
        // Tests for pinning behavior require this.
        ReplicaSetMonitor::useDeterministicHostSelection = true;

        // This shuts down the background RSMWatcher thread and prevents it from running. These
        // tests depend on controlling when the RSMs are updated.
        ReplicaSetMonitor::cleanup();

        _replSet.reset(new MockReplicaSet("test", 5));
        _originalConnectionHook = ConnectionString::getConnectionHook();
        ConnectionString::setConnectionHook(mongo::MockConnRegistry::get()->getConnStrHook());

        {
            mongo::repl::ReplSetConfig oldConfig = _replSet->getReplConfig();

            mongo::BSONObjBuilder newConfigBuilder;
            newConfigBuilder.append("_id", oldConfig.getReplSetName());
            newConfigBuilder.append("version", oldConfig.getConfigVersion());
            newConfigBuilder.append("protocolVersion", 1);

            mongo::BSONArrayBuilder membersBuilder(newConfigBuilder.subarrayStart("members"));
            {
                const string host(_replSet->getPrimary());
                const mongo::repl::MemberConfig* member =
                    oldConfig.findMemberByHostAndPort(HostAndPort(host));
                membersBuilder.append(
                    BSON("_id" << member->getId() << "host" << host << "tags" << BSON("dc"
                                                                                      << "ny"
                                                                                      << "p"
                                                                                      << "1")));
                _replSet->getNode(host)->insert(IdentityNS, BSON(HostField(host)));
            }

            vector<string> secNodes = _replSet->getSecondaries();
            vector<string>::const_iterator secIter = secNodes.begin();

            {
                const string host(*secIter);
                const mongo::repl::MemberConfig* member =
                    oldConfig.findMemberByHostAndPort(HostAndPort(host));
                membersBuilder.append(
                    BSON("_id" << member->getId() << "host" << host << "tags" << BSON("dc"
                                                                                      << "sf"
                                                                                      << "s"
                                                                                      << "1"
                                                                                      << "group"
                                                                                      << "1")));
                _replSet->getNode(host)->insert(IdentityNS, BSON(HostField(host)));
            }

            {
                ++secIter;
                const string host(*secIter);
                const mongo::repl::MemberConfig* member =
                    oldConfig.findMemberByHostAndPort(HostAndPort(host));
                membersBuilder.append(
                    BSON("_id" << member->getId() << "host" << host << "tags" << BSON("dc"
                                                                                      << "ma"
                                                                                      << "s"
                                                                                      << "2"
                                                                                      << "group"
                                                                                      << "1")));
                _replSet->getNode(host)->insert(IdentityNS, BSON(HostField(host)));
            }

            {
                ++secIter;
                const string host(*secIter);
                const mongo::repl::MemberConfig* member =
                    oldConfig.findMemberByHostAndPort(HostAndPort(host));
                membersBuilder.append(
                    BSON("_id" << member->getId() << "host" << host << "tags" << BSON("dc"
                                                                                      << "eu"
                                                                                      << "s"
                                                                                      << "3")));
                _replSet->getNode(host)->insert(IdentityNS, BSON(HostField(host)));
            }

            {
                ++secIter;
                const string host(*secIter);
                const mongo::repl::MemberConfig* member =
                    oldConfig.findMemberByHostAndPort(HostAndPort(host));
                membersBuilder.append(
                    BSON("_id" << member->getId() << "host" << host << "tags" << BSON("dc"
                                                                                      << "jp"
                                                                                      << "s"
                                                                                      << "4")));
                _replSet->getNode(host)->insert(IdentityNS, BSON(HostField(host)));
            }

            membersBuilder.done();
            mongo::repl::ReplSetConfig newConfig;
            fassert(28569, newConfig.initialize(newConfigBuilder.done()));
            fassert(28568, newConfig.validate());
            _replSet->setConfig(newConfig);
        }
    }

    void tearDown() {
        ReplicaSetMonitor::useDeterministicHostSelection = false;

        ConnectionString::setConnectionHook(_originalConnectionHook);
        ReplicaSetMonitor::cleanup();
        _replSet.reset();

        mongo::ScopedDbConnection::clearPool();
    }

    MockReplicaSet* getReplSet() {
        return _replSet.get();
    }

private:
    ConnectionString::ConnectionHook* _originalConnectionHook;
    std::unique_ptr<MockReplicaSet> _replSet;
};

TEST_F(TaggedFiveMemberRS, ConnShouldPinIfSameSettings) {
    MockReplicaSet* replSet = getReplSet();
    vector<HostAndPort> seedList;
    seedList.push_back(HostAndPort(replSet->getPrimary()));

    DBClientReplicaSet replConn(replSet->getSetName(), seedList, StringData());

    string dest;
    {
        Query query;
        query.readPref(mongo::ReadPreference::PrimaryPreferred, BSONArray());

        // Note: IdentityNS contains the name of the server.
        unique_ptr<DBClientCursor> cursor = replConn.query(IdentityNS, query);
        BSONObj doc = cursor->next();
        dest = doc[HostField.name()].str();
    }

    {
        Query query;
        query.readPref(mongo::ReadPreference::PrimaryPreferred, BSONArray());
        unique_ptr<DBClientCursor> cursor = replConn.query(IdentityNS, query);
        BSONObj doc = cursor->next();
        const string newDest = doc[HostField.name()].str();
        ASSERT_EQUALS(dest, newDest);
    }
}

TEST_F(TaggedFiveMemberRS, ConnShouldNotPinIfHostMarkedAsFailed) {
    MockReplicaSet* replSet = getReplSet();
    vector<HostAndPort> seedList;
    seedList.push_back(HostAndPort(replSet->getPrimary()));

    DBClientReplicaSet replConn(replSet->getSetName(), seedList, StringData());

    string dest;
    {
        Query query;
        query.readPref(mongo::ReadPreference::PrimaryPreferred, BSONArray());

        // Note: IdentityNS contains the name of the server.
        unique_ptr<DBClientCursor> cursor = replConn.query(IdentityNS, query);
        BSONObj doc = cursor->next();
        dest = doc[HostField.name()].str();
    }

    // This is the only difference from ConnShouldPinIfSameSettings which tests that we *do* pin
    // in if the host is still marked as up. Note that this only notifies the RSM, and does not
    // directly effect the DBClientRS.
    ReplicaSetMonitor::get(replSet->getSetName())
        ->failedHost(HostAndPort(dest), {ErrorCodes::InternalError, "Test error"});

    {
        Query query;
        query.readPref(mongo::ReadPreference::PrimaryPreferred, BSONArray());
        unique_ptr<DBClientCursor> cursor = replConn.query(IdentityNS, query);
        BSONObj doc = cursor->next();
        const string newDest = doc[HostField.name()].str();
        ASSERT_NOT_EQUALS(dest, newDest);
    }
}

TEST_F(TaggedFiveMemberRS, ConnShouldNotPinIfDiffMode) {
    MockReplicaSet* replSet = getReplSet();
    vector<HostAndPort> seedList;
    seedList.push_back(HostAndPort(replSet->getPrimary()));

    DBClientReplicaSet replConn(replSet->getSetName(), seedList, StringData());

    // Need up-to-date view to ensure there are multiple valid choices.
    ReplicaSetMonitor::get(replSet->getSetName())->startOrContinueRefresh().refreshAll();

    string dest;
    {
        Query query;
        query.readPref(mongo::ReadPreference::SecondaryPreferred, BSONArray());

        // Note: IdentityNS contains the name of the server.
        unique_ptr<DBClientCursor> cursor = replConn.query(IdentityNS, query);
        BSONObj doc = cursor->next();
        dest = doc[HostField.name()].str();
        ASSERT_NOT_EQUALS(dest, replSet->getPrimary());
    }

    {
        Query query;
        query.readPref(mongo::ReadPreference::SecondaryOnly, BSONArray());
        unique_ptr<DBClientCursor> cursor = replConn.query(IdentityNS, query);
        BSONObj doc = cursor->next();
        const string newDest = doc[HostField.name()].str();
        ASSERT_NOT_EQUALS(dest, newDest);
    }
}

TEST_F(TaggedFiveMemberRS, ConnShouldNotPinIfDiffTag) {
    MockReplicaSet* replSet = getReplSet();
    vector<HostAndPort> seedList;
    seedList.push_back(HostAndPort(replSet->getPrimary()));

    DBClientReplicaSet replConn(replSet->getSetName(), seedList, StringData());

    // Need up-to-date view to ensure there are multiple valid choices.
    ReplicaSetMonitor::get(replSet->getSetName())->startOrContinueRefresh().refreshAll();

    string dest;
    {
        Query query;
        query.readPref(mongo::ReadPreference::SecondaryPreferred,
                       BSON_ARRAY(BSON("dc"
                                       << "sf")));

        // Note: IdentityNS contains the name of the server.
        unique_ptr<DBClientCursor> cursor = replConn.query(IdentityNS, query);
        BSONObj doc = cursor->next();
        dest = doc[HostField.name()].str();
        ASSERT_NOT_EQUALS(dest, replSet->getPrimary());
    }

    {
        Query query;
        vector<pair<string, string>> tagSet;
        query.readPref(mongo::ReadPreference::SecondaryPreferred, BSON_ARRAY(BSON("group" << 1)));
        unique_ptr<DBClientCursor> cursor = replConn.query(IdentityNS, query);
        BSONObj doc = cursor->next();
        const string newDest = doc[HostField.name()].str();
        ASSERT_NOT_EQUALS(dest, newDest);
    }
}

// Note: slaveConn is dangerous and should be deprecated! Also see SERVER-7801.
TEST_F(TaggedFiveMemberRS, SlaveConnReturnsSecConn) {
    MockReplicaSet* replSet = getReplSet();
    vector<HostAndPort> seedList;
    seedList.push_back(HostAndPort(replSet->getPrimary()));

    DBClientReplicaSet replConn(replSet->getSetName(), seedList, StringData());

    // Need up-to-date view since slaveConn() uses SecondaryPreferred, and this test assumes it
    // knows about at least one secondary.
    ReplicaSetMonitor::get(replSet->getSetName())->startOrContinueRefresh().refreshAll();

    string dest;
    mongo::DBClientConnection& secConn = replConn.slaveConn();

    // Note: IdentityNS contains the name of the server.
    unique_ptr<DBClientCursor> cursor = secConn.query(IdentityNS, Query());
    BSONObj doc = cursor->next();
    dest = doc[HostField.name()].str();
    ASSERT_NOT_EQUALS(dest, replSet->getPrimary());
}

}  // namespace
}  // namespace mongo