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
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
|
/**
* Copyright (C) 2015 MongoDB 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.
*/
#define MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kDefault
#include "mongo/platform/basic.h"
#include <memory>
#include "mongo/client/fetcher.h"
#include "mongo/db/json.h"
#include "mongo/db/repl/base_cloner_test_fixture.h"
#include "mongo/db/repl/data_replicator.h"
#include "mongo/db/repl/member_state.h"
#include "mongo/db/repl/optime.h"
#include "mongo/db/repl/update_position_args.h"
#include "mongo/db/repl/replication_executor_test_fixture.h"
#include "mongo/db/repl/replication_executor.h"
#include "mongo/db/repl/reporter.h"
#include "mongo/db/repl/sync_source_selector.h"
#include "mongo/db/repl/sync_source_resolver.h"
#include "mongo/executor/network_interface_mock.h"
#include "mongo/stdx/mutex.h"
#include "mongo/util/fail_point_service.h"
#include "mongo/util/concurrency/thread_name.h"
#include "mongo/util/log.h"
#include "mongo/util/mongoutils/str.h"
#include "mongo/unittest/barrier.h"
#include "mongo/unittest/unittest.h"
namespace {
using namespace mongo;
using namespace mongo::repl;
using executor::NetworkInterfaceMock;
using executor::RemoteCommandRequest;
using executor::RemoteCommandResponse;
using LockGuard = stdx::lock_guard<stdx::mutex>;
using UniqueLock = stdx::unique_lock<stdx::mutex>;
using mutex = stdx::mutex;
class SyncSourceSelectorMock : public SyncSourceSelector {
MONGO_DISALLOW_COPYING(SyncSourceSelectorMock);
public:
SyncSourceSelectorMock(const HostAndPort& syncSource) : _syncSource(syncSource) {}
void clearSyncSourceBlacklist() override {}
HostAndPort chooseNewSyncSource(const Timestamp& ts) override {
HostAndPort result = _syncSource;
_syncSource = HostAndPort();
return result;
}
void blacklistSyncSource(const HostAndPort& host, Date_t until) override {
_blacklistedSource = host;
}
bool shouldChangeSyncSource(const HostAndPort& currentSource,
const OpTime& sourcesOpTime,
bool syncSourceHasSyncSource) override {
return false;
}
SyncSourceResolverResponse selectSyncSource(OperationContext* txn,
const OpTime& lastOpTimeFetched) override {
return SyncSourceResolverResponse();
}
HostAndPort _syncSource;
HostAndPort _blacklistedSource;
};
class DataReplicatorTest : public ReplicationExecutorTest, public SyncSourceSelector {
public:
DataReplicatorTest() {}
void postExecutorThreadLaunch() override{};
/**
* clear/reset state
*/
void reset() {
_applierFn = [](const MultiApplier::Operations&) -> Status { return Status::OK(); };
_multiApplyFn = [](OperationContext*,
const MultiApplier::Operations& ops,
MultiApplier::ApplyOperationFn)
-> StatusWith<OpTime> { return ops.back().getOpTime(); };
_rollbackFn = [](OperationContext*, const OpTime&, const HostAndPort&)
-> Status { return Status::OK(); };
_setMyLastOptime = [this](const OpTime& opTime) { _myLastOpTime = opTime; };
_myLastOpTime = OpTime();
_memberState = MemberState::RS_UNKNOWN;
_syncSourceSelector.reset(new SyncSourceSelectorMock(HostAndPort("localhost", -1)));
}
// SyncSourceSelector
void clearSyncSourceBlacklist() override {
_syncSourceSelector->clearSyncSourceBlacklist();
}
HostAndPort chooseNewSyncSource(const Timestamp& ts) override {
return _syncSourceSelector->chooseNewSyncSource(ts);
}
void blacklistSyncSource(const HostAndPort& host, Date_t until) override {
_syncSourceSelector->blacklistSyncSource(host, until);
}
bool shouldChangeSyncSource(const HostAndPort& currentSource,
const OpTime& sourcesOpTime,
bool syncSourceHasSyncSource) override {
return _syncSourceSelector->shouldChangeSyncSource(
currentSource, sourcesOpTime, syncSourceHasSyncSource);
}
SyncSourceResolverResponse selectSyncSource(OperationContext* txn,
const OpTime& lastOpTimeFetched) override {
return SyncSourceResolverResponse();
}
void scheduleNetworkResponse(const BSONObj& obj) {
NetworkInterfaceMock* net = getNet();
ASSERT_TRUE(net->hasReadyRequests());
scheduleNetworkResponse(net->getNextReadyRequest(), obj);
}
void scheduleNetworkResponse(NetworkInterfaceMock::NetworkOperationIterator noi,
const BSONObj& obj) {
NetworkInterfaceMock* net = getNet();
Milliseconds millis(0);
RemoteCommandResponse response(obj, BSONObj(), millis);
ReplicationExecutor::ResponseStatus responseStatus(response);
net->scheduleResponse(noi, net->now(), responseStatus);
}
void scheduleNetworkResponse(ErrorCodes::Error code, const std::string& reason) {
NetworkInterfaceMock* net = getNet();
ASSERT_TRUE(net->hasReadyRequests());
ReplicationExecutor::ResponseStatus responseStatus(code, reason);
net->scheduleResponse(net->getNextReadyRequest(), net->now(), responseStatus);
}
void processNetworkResponse(const BSONObj& obj) {
scheduleNetworkResponse(obj);
finishProcessingNetworkResponse();
}
void processNetworkResponse(ErrorCodes::Error code, const std::string& reason) {
scheduleNetworkResponse(code, reason);
finishProcessingNetworkResponse();
}
void finishProcessingNetworkResponse() {
getNet()->runReadyNetworkOperations();
ASSERT_FALSE(getNet()->hasReadyRequests());
}
DataReplicator& getDR() {
return *_dr;
}
protected:
void setUp() override {
ReplicationExecutorTest::setUp();
reset();
launchExecutorThread();
DataReplicatorOptions options;
options.initialSyncRetryWait = Milliseconds(0);
options.applierFn = [this](const MultiApplier::Operations& ops) { return _applierFn(ops); };
options.multiApplyFn =
[this](OperationContext* txn,
const MultiApplier::Operations& ops,
MultiApplier::ApplyOperationFn func) { return _multiApplyFn(txn, ops, func); };
options.rollbackFn = [this](OperationContext* txn,
const OpTime& lastOpTimeWritten,
const HostAndPort& syncSource) -> Status {
return _rollbackFn(txn, lastOpTimeWritten, syncSource);
};
options.prepareReplSetUpdatePositionCommandFn =
[](ReplicationCoordinator::ReplSetUpdatePositionCommandStyle commandStyle)
-> StatusWith<BSONObj> { return BSON(UpdatePositionArgs::kCommandFieldName << 1); };
options.getMyLastOptime = [this]() { return _myLastOpTime; };
options.setMyLastOptime = [this](const OpTime& opTime) { _setMyLastOptime(opTime); };
options.setFollowerMode = [this](const MemberState& state) {
_memberState = state;
return true;
};
options.getSlaveDelay = [this]() { return Seconds(0); };
options.syncSourceSelector = this;
try {
_dr.reset(new DataReplicator(options, &(getReplExecutor())));
} catch (...) {
ASSERT_OK(exceptionToStatus());
}
}
void tearDown() override {
ReplicationExecutorTest::tearDown();
_dr.reset();
// Executor may still invoke callback before shutting down.
}
MultiApplier::ApplyOperationFn _applierFn;
MultiApplier::MultiApplyFn _multiApplyFn;
DataReplicatorOptions::RollbackFn _rollbackFn;
DataReplicatorOptions::SetMyLastOptimeFn _setMyLastOptime;
OpTime _myLastOpTime;
MemberState _memberState;
std::unique_ptr<SyncSourceSelector> _syncSourceSelector;
private:
std::unique_ptr<DataReplicator> _dr;
};
TEST_F(DataReplicatorTest, CreateDestroy) {}
TEST_F(DataReplicatorTest, StartOk) {
ASSERT_EQ(getDR().start().code(), ErrorCodes::OK);
}
TEST_F(DataReplicatorTest, CannotInitialSyncAfterStart) {
ASSERT_EQ(getDR().start().code(), ErrorCodes::OK);
ASSERT_EQ(getDR().initialSync(), ErrorCodes::AlreadyInitialized);
}
// Used to run a Initial Sync in a separate thread, to avoid blocking test execution.
class InitialSyncBackgroundRunner {
public:
InitialSyncBackgroundRunner(DataReplicator* dr)
: _dr(dr), _result(Status(ErrorCodes::BadValue, "failed to set status")) {}
// Could block if _sgr has not finished
TimestampStatus getResult() {
_thread->join();
return _result;
}
void run() {
_thread.reset(new stdx::thread(stdx::bind(&InitialSyncBackgroundRunner::_run, this)));
}
private:
void _run() {
setThreadName("InitialSyncRunner");
_result = _dr->initialSync(); // blocking
}
DataReplicator* _dr;
TimestampStatus _result;
std::unique_ptr<stdx::thread> _thread;
};
class InitialSyncTest : public DataReplicatorTest {
public:
InitialSyncTest()
: _insertCollectionFn([&](OperationContext* txn,
const NamespaceString& theNss,
const std::vector<BSONObj>& theDocuments) {
log() << "insertDoc for " << theNss.toString();
LockGuard lk(_collectionCountMutex);
++(_collectionCounts[theNss.toString()]);
return Status::OK();
}),
_beginCollectionFn([&](OperationContext* txn,
const NamespaceString& theNss,
const CollectionOptions& theOptions,
const std::vector<BSONObj>& theIndexSpecs) {
log() << "beginCollection for " << theNss.toString();
LockGuard lk(_collectionCountMutex);
_collectionCounts[theNss.toString()] = 0;
return Status::OK();
}){};
protected:
void setStorageFuncs(ClonerStorageInterfaceMock::InsertCollectionFn ins,
ClonerStorageInterfaceMock::BeginCollectionFn beg) {
_insertCollectionFn = ins;
_beginCollectionFn = beg;
}
void setResponses(std::vector<BSONObj> resps) {
_responses = resps;
}
void startSync() {
DataReplicator* dr = &(getDR());
_storage.beginCollectionFn = _beginCollectionFn;
_storage.insertDocumentsFn = _insertCollectionFn;
_storage.insertMissingDocFn =
[&](OperationContext* txn, const NamespaceString& nss, const BSONObj& doc) {
return Status::OK();
};
dr->_setInitialSyncStorageInterface(&_storage);
_isbr.reset(new InitialSyncBackgroundRunner(dr));
_isbr->run();
}
void playResponses() {
// TODO: Handle network responses
NetworkInterfaceMock* net = getNet();
int processedRequests(0);
const int expectedResponses(_responses.size());
// counter for oplog entries
int c(0);
while (true) {
net->enterNetwork();
if (!net->hasReadyRequests() && processedRequests < expectedResponses) {
net->exitNetwork();
continue;
}
NetworkInterfaceMock::NetworkOperationIterator noi = net->getNextReadyRequest();
const BSONObj reqBSON = noi->getRequest().cmdObj;
const BSONElement cmdElem = reqBSON.firstElement();
const bool isGetMore = cmdElem.fieldNameStringData().equalCaseInsensitive("getmore");
const long long cursorId = cmdElem.numberLong();
if (isGetMore && cursorId == 1LL) {
// process getmore requests from the oplog fetcher
auto respBSON = fromjson(str::stream()
<< "{ok:1, cursor:{id:NumberLong(1), ns:'local.oplog.rs'"
" , nextBatch:[{ts:Timestamp(" << ++c
<< ",1), h:1, ns:'test.a', v:" << OplogEntry::kOplogVersion
<< ", op:'u', o2:{_id:" << c << "}, o:{$set:{a:1}}}]}}");
net->scheduleResponse(
noi,
net->now(),
ResponseStatus(RemoteCommandResponse(respBSON, BSONObj(), Milliseconds(10))));
net->runReadyNetworkOperations();
net->exitNetwork();
continue;
} else if (isGetMore) {
// TODO: return more data
}
// process fixed set of responses
log() << "processing network request: " << noi->getRequest().dbname << "."
<< noi->getRequest().cmdObj.toString();
net->scheduleResponse(noi,
net->now(),
ResponseStatus(RemoteCommandResponse(
_responses[processedRequests], BSONObj(), Milliseconds(10))));
net->runReadyNetworkOperations();
net->exitNetwork();
if (++processedRequests >= expectedResponses) {
log() << "done processing expected requests ";
break; // once we have processed all requests, continue;
}
}
net->enterNetwork();
if (net->hasReadyRequests()) {
log() << "There are unexpected requests left";
log() << "next cmd: " << net->getNextReadyRequest()->getRequest().cmdObj.toString();
ASSERT_FALSE(net->hasReadyRequests());
}
net->exitNetwork();
}
void verifySync(Status s = Status::OK()) {
verifySync(s.code());
}
void verifySync(ErrorCodes::Error code) {
// Check result
ASSERT_EQ(_isbr->getResult().getStatus().code(), code) << "status codes differ";
}
std::map<std::string, int> getLocalCollectionCounts() {
return _collectionCounts;
}
private:
ClonerStorageInterfaceMock::InsertCollectionFn _insertCollectionFn;
ClonerStorageInterfaceMock::BeginCollectionFn _beginCollectionFn;
std::vector<BSONObj> _responses;
std::unique_ptr<InitialSyncBackgroundRunner> _isbr;
std::map<std::string, int> _collectionCounts; // counts of inserts during cloning
mutex _collectionCountMutex; // used to protect the collectionCount map
ClonerStorageInterfaceMock _storage;
};
TEST_F(InitialSyncTest, Complete) {
/**
* Initial Sync will issue these query/commands
* - startTS = oplog.rs->find().sort({$natural:-1}).limit(-1).next()["ts"]
* - listDatabases (foreach db do below)
* -- cloneDatabase (see DatabaseCloner tests).
* - endTS = oplog.rs->find().sort({$natural:-1}).limit(-1).next()["ts"]
* - ops = oplog.rs->find({ts:{$gte: startTS}}) (foreach op)
* -- if local doc is missing, getCollection(op.ns).findOne(_id:op.o2._id)
* - if any retries were done in the previous loop, endTS query again for minvalid
*
*/
const std::vector<BSONObj> responses = {
// get latest oplog ts
fromjson(
str::stream() << "{ok:1, cursor:{id:NumberLong(0), ns:'local.oplog.rs', firstBatch:["
"{ts:Timestamp(1,1), h:1, ns:'a.a', v:" << OplogEntry::kOplogVersion
<< ", op:'i', o:{_id:1, a:1}}]}}"),
// oplog fetcher find
fromjson(
str::stream() << "{ok:1, cursor:{id:NumberLong(1), ns:'local.oplog.rs', firstBatch:["
"{ts:Timestamp(1,1), h:1, ns:'a.a', v:" << OplogEntry::kOplogVersion
<< ", op:'i', o:{_id:1, a:1}}]}}"),
// Clone Start
// listDatabases
fromjson("{ok:1, databases:[{name:'a'}]}"),
// listCollections for "a"
fromjson(
"{ok:1, cursor:{id:NumberLong(0), ns:'a.$cmd.listCollections', firstBatch:["
"{name:'a', options:{}} "
"]}}"),
// listIndexes:a
fromjson(str::stream()
<< "{ok:1, cursor:{id:NumberLong(0), ns:'a.$cmd.listIndexes.a', firstBatch:["
"{v:" << OplogEntry::kOplogVersion
<< ", key:{_id:1}, name:'_id_', ns:'a.a'}]}}"),
// find:a
fromjson(
"{ok:1, cursor:{id:NumberLong(0), ns:'a.a', firstBatch:["
"{_id:1, a:1} "
"]}}"),
// Clone Done
// get latest oplog ts
fromjson(
str::stream() << "{ok:1, cursor:{id:NumberLong(0), ns:'local.oplog.rs', firstBatch:["
"{ts:Timestamp(2,2), h:1, ns:'b.c', v:" << OplogEntry::kOplogVersion
<< ", op:'i', o:{_id:1, c:1}}]}}"),
// Applier starts ...
};
startSync();
setResponses(responses);
playResponses();
verifySync();
}
TEST_F(InitialSyncTest, MissingDocOnMultiApplyCompletes) {
DataReplicatorOptions opts;
int applyCounter{0};
_multiApplyFn =
[&](OperationContext*, const MultiApplier::Operations& ops, MultiApplier::ApplyOperationFn)
-> StatusWith<OpTime> {
if (++applyCounter == 1) {
return Status(ErrorCodes::NoMatchingDocument, "failed: missing doc.");
}
return ops.back().getOpTime();
};
const std::vector<BSONObj> responses = {
// get latest oplog ts
fromjson(
str::stream() << "{ok:1, cursor:{id:NumberLong(0), ns:'local.oplog.rs', firstBatch:["
"{ts:Timestamp(1,1), h:1, ns:'a.a', v:" << OplogEntry::kOplogVersion
<< ", op:'i', o:{_id:1, a:1}}]}}"),
// oplog fetcher find
fromjson(
str::stream() << "{ok:1, cursor:{id:NumberLong(1), ns:'local.oplog.rs', firstBatch:["
"{ts:Timestamp(1,1), h:1, ns:'a.a', v:" << OplogEntry::kOplogVersion
<< ", op:'u', o2:{_id:1}, o:{$set:{a:1}}}]}}"),
// Clone Start
// listDatabases
fromjson("{ok:1, databases:[{name:'a'}]}"),
// listCollections for "a"
fromjson(
"{ok:1, cursor:{id:NumberLong(0), ns:'a.$cmd.listCollections', firstBatch:["
"{name:'a', options:{}} "
"]}}"),
// listIndexes:a
fromjson(str::stream()
<< "{ok:1, cursor:{id:NumberLong(0), ns:'a.$cmd.listIndexes.a', firstBatch:["
"{v:" << OplogEntry::kOplogVersion
<< ", key:{_id:1}, name:'_id_', ns:'a.a'}]}}"),
// find:a -- empty
fromjson("{ok:1, cursor:{id:NumberLong(0), ns:'a.a', firstBatch:[]}}"),
// Clone Done
// get latest oplog ts
fromjson(
str::stream() << "{ok:1, cursor:{id:NumberLong(0), ns:'local.oplog.rs', firstBatch:["
"{ts:Timestamp(2,2), h:1, ns:'b.c', v:" << OplogEntry::kOplogVersion
<< ", op:'i', o:{_id:1, c:1}}]}}"),
// Applier starts ...
// missing doc fetch -- find:a {_id:1}
fromjson(
"{ok:1, cursor:{id:NumberLong(0), ns:'a.a', firstBatch:["
"{_id:1, a:1} "
"]}}"),
};
startSync();
setResponses(responses);
playResponses();
verifySync(ErrorCodes::OK);
}
TEST_F(InitialSyncTest, Failpoint) {
mongo::getGlobalFailPointRegistry()
->getFailPoint("failInitialSyncWithBadHost")
->setMode(FailPoint::alwaysOn);
BSONObj configObj = BSON("_id"
<< "mySet"
<< "version" << 1 << "members"
<< BSON_ARRAY(BSON("_id" << 1 << "host"
<< "node1:12345")
<< BSON("_id" << 2 << "host"
<< "node2:12345")
<< BSON("_id" << 3 << "host"
<< "node3:12345")));
Timestamp time1(100, 1);
OpTime opTime1(time1, OpTime::kInitialTerm);
_myLastOpTime = opTime1;
_memberState = MemberState::RS_SECONDARY;
DataReplicator* dr = &(getDR());
InitialSyncBackgroundRunner isbr(dr);
isbr.run();
ASSERT_EQ(isbr.getResult().getStatus().code(), ErrorCodes::InitialSyncFailure);
mongo::getGlobalFailPointRegistry()
->getFailPoint("failInitialSyncWithBadHost")
->setMode(FailPoint::off);
}
TEST_F(InitialSyncTest, FailsOnClone) {
const std::vector<BSONObj> responses = {
// get latest oplog ts
fromjson(
str::stream() << "{ok:1, cursor:{id:NumberLong(0), ns:'local.oplog.rs', firstBatch:["
"{ts:Timestamp(1,1), h:1, ns:'a.a', v:" << OplogEntry::kOplogVersion
<< ", op:'i', o:{_id:1, a:1}}]}}"),
// oplog fetcher find
fromjson(
str::stream() << "{ok:1, cursor:{id:NumberLong(1), ns:'local.oplog.rs', firstBatch:["
"{ts:Timestamp(1,1), h:1, ns:'a.a', v:" << OplogEntry::kOplogVersion
<< ", op:'i', o:{_id:1, a:1}}]}}"),
// Clone Start
// listDatabases
fromjson("{ok:0}")};
startSync();
setResponses(responses);
playResponses();
verifySync(ErrorCodes::InitialSyncFailure);
}
class TestSyncSourceSelector2 : public SyncSourceSelector {
public:
void clearSyncSourceBlacklist() override {}
HostAndPort chooseNewSyncSource(const Timestamp& ts) override {
LockGuard lk(_mutex);
auto result = HostAndPort(str::stream() << "host-" << _nextSourceNum++, -1);
_condition.notify_all();
return result;
}
void blacklistSyncSource(const HostAndPort& host, Date_t until) override {
LockGuard lk(_mutex);
_blacklistedSource = host;
}
bool shouldChangeSyncSource(const HostAndPort& currentSource,
const OpTime& sourcesOpTime,
bool syncSourceHasSyncSource) override {
return false;
}
SyncSourceResolverResponse selectSyncSource(OperationContext* txn,
const OpTime& lastOpTimeFetched) override {
return SyncSourceResolverResponse();
}
mutable stdx::mutex _mutex;
stdx::condition_variable _condition;
int _nextSourceNum{0};
HostAndPort _blacklistedSource;
};
class SteadyStateTest : public DataReplicatorTest {
protected:
void _setUpOplogFetcherFailed() {
DataReplicator& dr = getDR();
_syncSourceSelector.reset(new TestSyncSourceSelector2());
_memberState = MemberState::RS_UNKNOWN;
auto net = getNet();
net->enterNetwork();
ASSERT_OK(dr.start());
}
void _testOplogFetcherFailed(const BSONObj& oplogFetcherResponse,
const Status& rollbackStatus,
const HostAndPort& expectedRollbackSource,
const HostAndPort& expectedBlacklistedSource,
const HostAndPort& expectedFinalSource,
const MemberState& expectedFinalState,
const DataReplicatorState& expectedDataReplicatorState,
int expectedNextSourceNum) {
stdx::mutex mutex;
OperationContext* rollbackTxn = nullptr;
HostAndPort rollbackSource;
unittest::Barrier barrier(2U);
_rollbackFn = [&](OperationContext* txn,
const OpTime& lastOpTimeWritten,
const HostAndPort& syncSource) -> Status {
stdx::lock_guard<stdx::mutex> lock(mutex);
rollbackTxn = txn;
rollbackSource = syncSource;
barrier.countDownAndWait();
return rollbackStatus;
};
auto net = getNet();
ASSERT_TRUE(net->hasReadyRequests());
auto noi = net->getNextReadyRequest();
ASSERT_EQUALS("find", std::string(noi->getRequest().cmdObj.firstElementFieldName()));
scheduleNetworkResponse(noi, oplogFetcherResponse);
net->runReadyNetworkOperations();
// Replicator state should be ROLLBACK before rollback function returns.
DataReplicator& dr = getDR();
ASSERT_EQUALS(toString(DataReplicatorState::Rollback), toString(dr.getState()));
// Wait for rollback function to be called.
barrier.countDownAndWait();
{
stdx::lock_guard<stdx::mutex> lock(mutex);
ASSERT_TRUE(rollbackTxn);
ASSERT_EQUALS(expectedRollbackSource, rollbackSource);
}
dr.waitForState(expectedDataReplicatorState);
// Wait for data replicator to request a new sync source if rollback is expected to fail.
if (!rollbackStatus.isOK()) {
TestSyncSourceSelector2* syncSourceSelector =
static_cast<TestSyncSourceSelector2*>(_syncSourceSelector.get());
UniqueLock lk(syncSourceSelector->_mutex);
while (syncSourceSelector->_nextSourceNum < expectedNextSourceNum) {
syncSourceSelector->_condition.wait(lk);
}
ASSERT_EQUALS(expectedBlacklistedSource, syncSourceSelector->_blacklistedSource);
}
ASSERT_EQUALS(expectedFinalSource, dr.getSyncSource());
ASSERT_EQUALS(expectedFinalState.toString(), _memberState.toString());
}
};
TEST_F(SteadyStateTest, StartWhenInSteadyState) {
DataReplicator& dr = getDR();
ASSERT_EQUALS(toString(DataReplicatorState::Uninitialized), toString(dr.getState()));
ASSERT_OK(dr.start());
ASSERT_EQUALS(toString(DataReplicatorState::Steady), toString(dr.getState()));
ASSERT_EQUALS(ErrorCodes::IllegalOperation, dr.start().code());
}
TEST_F(SteadyStateTest, ShutdownAfterStart) {
DataReplicator& dr = getDR();
ASSERT_EQUALS(toString(DataReplicatorState::Uninitialized), toString(dr.getState()));
auto net = getNet();
net->enterNetwork();
ASSERT_OK(dr.start());
ASSERT_TRUE(net->hasReadyRequests());
getReplExecutor().shutdown();
ASSERT_EQUALS(toString(DataReplicatorState::Steady), toString(dr.getState()));
ASSERT_EQUALS(ErrorCodes::IllegalOperation, dr.start().code());
}
TEST_F(SteadyStateTest, RequestShutdownAfterStart) {
DataReplicator& dr = getDR();
ASSERT_EQUALS(toString(DataReplicatorState::Uninitialized), toString(dr.getState()));
auto net = getNet();
net->enterNetwork();
ASSERT_OK(dr.start());
ASSERT_TRUE(net->hasReadyRequests());
ASSERT_EQUALS(toString(DataReplicatorState::Steady), toString(dr.getState()));
// Simulating an invalid remote oplog query response. This will invalidate the existing
// sync source but that's fine because we're not testing oplog processing.
scheduleNetworkResponse(BSON("ok" << 0));
net->runReadyNetworkOperations();
ASSERT_OK(dr.scheduleShutdown());
net->exitNetwork(); // runs work item scheduled in 'scheduleShutdown()).
dr.waitForShutdown();
ASSERT_EQUALS(toString(DataReplicatorState::Uninitialized), toString(dr.getState()));
}
class ShutdownExecutorSyncSourceSelector : public SyncSourceSelector {
public:
ShutdownExecutorSyncSourceSelector(ReplicationExecutor* exec) : _exec(exec) {}
void clearSyncSourceBlacklist() override {}
HostAndPort chooseNewSyncSource(const Timestamp& ts) override {
_exec->shutdown();
return HostAndPort();
}
void blacklistSyncSource(const HostAndPort& host, Date_t until) override {}
bool shouldChangeSyncSource(const HostAndPort& currentSource,
const OpTime& sourcesOpTime,
bool syncSourceHasSyncSource) override {
return false;
}
SyncSourceResolverResponse selectSyncSource(OperationContext* txn,
const OpTime& lastOpTimeFetched) override {
return SyncSourceResolverResponse();
}
ReplicationExecutor* _exec;
};
TEST_F(SteadyStateTest, ScheduleNextActionFailsAfterChoosingEmptySyncSource) {
_syncSourceSelector.reset(new ShutdownExecutorSyncSourceSelector(&getReplExecutor()));
DataReplicator& dr = getDR();
ASSERT_EQUALS(toString(DataReplicatorState::Uninitialized), toString(dr.getState()));
auto net = getNet();
net->enterNetwork();
ASSERT_OK(dr.start());
ASSERT_EQUALS(HostAndPort(), dr.getSyncSource());
ASSERT_EQUALS(toString(DataReplicatorState::Uninitialized), toString(dr.getState()));
}
TEST_F(SteadyStateTest, ChooseNewSyncSourceAfterFailedNetworkRequest) {
TestSyncSourceSelector2* testSyncSourceSelector = new TestSyncSourceSelector2();
_syncSourceSelector.reset(testSyncSourceSelector);
_memberState = MemberState::RS_UNKNOWN;
DataReplicator& dr = getDR();
ASSERT_EQUALS(toString(DataReplicatorState::Uninitialized), toString(dr.getState()));
auto net = getNet();
net->enterNetwork();
ASSERT_OK(dr.start());
ASSERT_TRUE(net->hasReadyRequests());
ASSERT_EQUALS(toString(DataReplicatorState::Steady), toString(dr.getState()));
// Simulating an invalid remote oplog query response to cause the data replicator to
// blacklist the existing sync source and request a new one.
scheduleNetworkResponse(BSON("ok" << 0));
net->runReadyNetworkOperations();
// Wait for data replicator to request a new sync source.
{
UniqueLock lk(testSyncSourceSelector->_mutex);
while (testSyncSourceSelector->_nextSourceNum < 2) {
testSyncSourceSelector->_condition.wait(lk);
}
ASSERT_EQUALS(HostAndPort("host-0", -1), testSyncSourceSelector->_blacklistedSource);
}
ASSERT_EQUALS(HostAndPort("host-1", -1), dr.getSyncSource());
ASSERT_EQUALS(MemberState(MemberState::RS_UNKNOWN).toString(), _memberState.toString());
ASSERT_EQUALS(toString(DataReplicatorState::Steady), toString(dr.getState()));
}
TEST_F(SteadyStateTest, RemoteOplogEmptyRollbackSucceeded) {
_setUpOplogFetcherFailed();
auto oplogFetcherResponse =
fromjson("{ok:1, cursor:{id:NumberLong(0), ns:'local.oplog.rs', firstBatch: []}}");
_testOplogFetcherFailed(oplogFetcherResponse,
Status::OK(),
HostAndPort("host-0", -1), // rollback source
HostAndPort(), // sync source should not be blacklisted.
HostAndPort("host-0", -1),
MemberState::RS_SECONDARY,
DataReplicatorState::Steady,
2);
}
TEST_F(SteadyStateTest, RemoteOplogEmptyRollbackFailed) {
_setUpOplogFetcherFailed();
auto oplogFetcherResponse =
fromjson("{ok:1, cursor:{id:NumberLong(0), ns:'local.oplog.rs', firstBatch: []}}");
_testOplogFetcherFailed(oplogFetcherResponse,
Status(ErrorCodes::OperationFailed, "rollback failed"),
HostAndPort("host-0", -1), // rollback source
HostAndPort("host-0", -1),
HostAndPort("host-1", -1),
MemberState::RS_UNKNOWN,
DataReplicatorState::Rollback,
2);
}
TEST_F(SteadyStateTest, RemoteOplogFirstOperationMissingTimestampRollbackFailed) {
_setUpOplogFetcherFailed();
auto oplogFetcherResponse =
fromjson("{ok:1, cursor:{id:NumberLong(0), ns:'local.oplog.rs', firstBatch: [{}]}}");
_testOplogFetcherFailed(oplogFetcherResponse,
Status(ErrorCodes::OperationFailed, "rollback failed"),
HostAndPort("host-0", -1), // rollback source
HostAndPort("host-0", -1),
HostAndPort("host-1", -1),
MemberState::RS_UNKNOWN,
DataReplicatorState::Rollback,
2);
}
TEST_F(SteadyStateTest, RemoteOplogFirstOperationTimestampDoesNotMatchRollbackFailed) {
_setUpOplogFetcherFailed();
auto oplogFetcherResponse = fromjson(
"{ok:1, cursor:{id:NumberLong(0), ns:'local.oplog.rs', firstBatch:[{ts:Timestamp(1,1)}]}}");
_testOplogFetcherFailed(oplogFetcherResponse,
Status(ErrorCodes::OperationFailed, "rollback failed"),
HostAndPort("host-0", -1), // rollback source
HostAndPort("host-0", -1),
HostAndPort("host-1", -1),
MemberState::RS_UNKNOWN,
DataReplicatorState::Rollback,
2);
}
TEST_F(SteadyStateTest, RollbackTwoSyncSourcesBothFailed) {
_setUpOplogFetcherFailed();
auto oplogFetcherResponse =
fromjson("{ok:1, cursor:{id:NumberLong(0), ns:'local.oplog.rs', firstBatch: []}}");
_testOplogFetcherFailed(oplogFetcherResponse,
Status(ErrorCodes::OperationFailed, "rollback failed"),
HostAndPort("host-0", -1), // rollback source
HostAndPort("host-0", -1),
HostAndPort("host-1", -1),
MemberState::RS_UNKNOWN,
DataReplicatorState::Rollback,
2);
_testOplogFetcherFailed(oplogFetcherResponse,
Status(ErrorCodes::OperationFailed, "rollback failed"),
HostAndPort("host-1", -1), // rollback source
HostAndPort("host-1", -1),
HostAndPort("host-2", -1),
MemberState::RS_UNKNOWN,
DataReplicatorState::Rollback,
3);
}
TEST_F(SteadyStateTest, RollbackTwoSyncSourcesSecondRollbackSucceeds) {
_setUpOplogFetcherFailed();
auto oplogFetcherResponse =
fromjson("{ok:1, cursor:{id:NumberLong(0), ns:'local.oplog.rs', firstBatch: []}}");
_testOplogFetcherFailed(oplogFetcherResponse,
Status(ErrorCodes::OperationFailed, "rollback failed"),
HostAndPort("host-0", -1), // rollback source
HostAndPort("host-0", -1),
HostAndPort("host-1", -1),
MemberState::RS_UNKNOWN,
DataReplicatorState::Rollback,
2);
_testOplogFetcherFailed(oplogFetcherResponse,
Status::OK(),
HostAndPort("host-1", -1), // rollback source
HostAndPort("host-0", -1), // blacklisted source unchanged
HostAndPort("host-1", -1),
MemberState::RS_SECONDARY,
DataReplicatorState::Steady,
2); // not used when rollback is expected to succeed
}
TEST_F(SteadyStateTest, PauseDataReplicator) {
auto operationToApply = BSON("op"
<< "a"
<< "v" << OplogEntry::kOplogVersion << "ts"
<< Timestamp(Seconds(123), 0));
stdx::mutex mutex;
unittest::Barrier barrier(2U);
Timestamp lastTimestampApplied;
BSONObj operationApplied;
_multiApplyFn =
[&](OperationContext*, const MultiApplier::Operations& ops, MultiApplier::ApplyOperationFn)
-> StatusWith<OpTime> {
stdx::lock_guard<stdx::mutex> lock(mutex);
operationApplied = ops.back().raw;
barrier.countDownAndWait();
return ops.back().getOpTime();
};
DataReplicatorOptions::SetMyLastOptimeFn oldSetMyLastOptime = _setMyLastOptime;
_setMyLastOptime = [&](const OpTime& opTime) {
oldSetMyLastOptime(opTime);
stdx::lock_guard<stdx::mutex> lock(mutex);
lastTimestampApplied = opTime.getTimestamp();
barrier.countDownAndWait();
};
auto& dr = getDR();
_myLastOpTime = OpTime(operationToApply["ts"].timestamp(), OpTime::kInitialTerm);
_memberState = MemberState::RS_SECONDARY;
auto net = getNet();
net->enterNetwork();
ASSERT_OK(dr.start());
ASSERT_TRUE(net->hasReadyRequests());
{
auto networkRequest = net->getNextReadyRequest();
auto commandResponse = BSON(
"ok" << 1 << "cursor" << BSON("id" << 0LL << "ns"
<< "local.oplog.rs"
<< "firstBatch" << BSON_ARRAY(operationToApply)));
scheduleNetworkResponse(networkRequest, commandResponse);
}
dr.pause();
ASSERT_EQUALS(0U, dr.getOplogBufferCount());
// Data replication will process the fetcher response but will not schedule the applier.
net->runReadyNetworkOperations();
ASSERT_EQUALS(operationToApply["ts"].timestamp(), dr.getLastTimestampFetched());
// Schedule a bogus work item to ensure that the operation applier function
// is not scheduled.
auto& exec = getReplExecutor();
exec.scheduleWork(
[&barrier](const executor::TaskExecutor::CallbackArgs&) { barrier.countDownAndWait(); });
// Wake up executor thread and wait for bogus work callback to be invoked.
net->exitNetwork();
barrier.countDownAndWait();
// Oplog buffer should contain fetched operations since applier is not scheduled.
ASSERT_EQUALS(1U, dr.getOplogBufferCount());
dr.resume();
// Wait for applier function.
barrier.countDownAndWait();
// Run scheduleWork() work item scheduled in DataReplicator::_onApplyBatchFinish().
net->exitNetwork();
// Wait for batch completion callback.
barrier.countDownAndWait();
ASSERT_EQUALS(MemberState(MemberState::RS_SECONDARY).toString(), _memberState.toString());
{
stdx::lock_guard<stdx::mutex> lock(mutex);
ASSERT_EQUALS(operationToApply, operationApplied);
ASSERT_EQUALS(operationToApply["ts"].timestamp(), lastTimestampApplied);
}
}
TEST_F(SteadyStateTest, ApplyOneOperation) {
auto operationToApply = BSON("op"
<< "a"
<< "v" << OplogEntry::kOplogVersion << "ts"
<< Timestamp(Seconds(123), 0));
stdx::mutex mutex;
unittest::Barrier barrier(2U);
Timestamp lastTimestampApplied;
BSONObj operationApplied;
_multiApplyFn =
[&](OperationContext*, const MultiApplier::Operations& ops, MultiApplier::ApplyOperationFn)
-> StatusWith<OpTime> {
stdx::lock_guard<stdx::mutex> lock(mutex);
operationApplied = ops.back().raw;
barrier.countDownAndWait();
return ops.back().getOpTime();
};
DataReplicatorOptions::SetMyLastOptimeFn oldSetMyLastOptime = _setMyLastOptime;
_setMyLastOptime = [&](const OpTime& opTime) {
oldSetMyLastOptime(opTime);
stdx::lock_guard<stdx::mutex> lock(mutex);
lastTimestampApplied = opTime.getTimestamp();
barrier.countDownAndWait();
};
_myLastOpTime = OpTime(operationToApply["ts"].timestamp(), OpTime::kInitialTerm);
_memberState = MemberState::RS_SECONDARY;
auto net = getNet();
net->enterNetwork();
auto& dr = getDR();
ASSERT_OK(dr.start());
ASSERT_TRUE(net->hasReadyRequests());
{
auto networkRequest = net->getNextReadyRequest();
auto commandResponse = BSON(
"ok" << 1 << "cursor" << BSON("id" << 0LL << "ns"
<< "local.oplog.rs"
<< "firstBatch" << BSON_ARRAY(operationToApply)));
scheduleNetworkResponse(networkRequest, commandResponse);
}
ASSERT_EQUALS(0U, dr.getOplogBufferCount());
// Oplog buffer should be empty because contents are transferred to applier.
net->runReadyNetworkOperations();
ASSERT_EQUALS(0U, dr.getOplogBufferCount());
// Wait for applier function.
barrier.countDownAndWait();
ASSERT_EQUALS(operationToApply["ts"].timestamp(), dr.getLastTimestampFetched());
// Run scheduleWork() work item scheduled in DataReplicator::_onApplyBatchFinish().
net->exitNetwork();
// Wait for batch completion callback.
barrier.countDownAndWait();
ASSERT_EQUALS(MemberState(MemberState::RS_SECONDARY).toString(), _memberState.toString());
{
stdx::lock_guard<stdx::mutex> lock(mutex);
ASSERT_EQUALS(operationToApply, operationApplied);
ASSERT_EQUALS(operationToApply["ts"].timestamp(), lastTimestampApplied);
}
// Ensure that we send position information upstream after completing batch.
net->enterNetwork();
bool found = false;
while (net->hasReadyRequests()) {
auto networkRequest = net->getNextReadyRequest();
auto commandRequest = networkRequest->getRequest();
const auto& cmdObj = commandRequest.cmdObj;
if (str::equals(cmdObj.firstElementFieldName(), UpdatePositionArgs::kCommandFieldName) &&
commandRequest.dbname == "admin") {
found = true;
break;
} else {
net->blackHole(networkRequest);
}
}
ASSERT_TRUE(found);
}
} // namespace
|