/
replication_coordinator_impl.cpp
6322 lines (5493 loc) · 281 KB
/
replication_coordinator_impl.cpp
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
/**
* Copyright (C) 2018-present MongoDB, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Server Side Public License, version 1,
* as published by MongoDB, Inc.
*
* 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
* Server Side Public License for more details.
*
* You should have received a copy of the Server Side Public License
* along with this program. If not, see
* <http://www.mongodb.com/licensing/server-side-public-license>.
*
* 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 Server Side 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 LOGV2_FOR_ELECTION(ID, DLEVEL, MESSAGE, ...) \
LOGV2_DEBUG_OPTIONS( \
ID, DLEVEL, {logv2::LogComponent::kReplicationElection}, MESSAGE, ##__VA_ARGS__)
#include "mongo/db/repl/replication_coordinator_impl.h"
#include <algorithm>
#include <fmt/format.h>
#include <functional>
#include <limits>
#include "mongo/base/status.h"
#include "mongo/bson/json.h"
#include "mongo/bson/timestamp.h"
#include "mongo/client/fetcher.h"
#include "mongo/client/read_preference.h"
#include "mongo/db/audit.h"
#include "mongo/db/catalog/collection_catalog.h"
#include "mongo/db/catalog/commit_quorum_options.h"
#include "mongo/db/catalog/local_oplog_info.h"
#include "mongo/db/client.h"
#include "mongo/db/commands.h"
#include "mongo/db/commands/feature_compatibility_version.h"
#include "mongo/db/concurrency/d_concurrency.h"
#include "mongo/db/concurrency/lock_state.h"
#include "mongo/db/concurrency/replication_state_transition_lock_guard.h"
#include "mongo/db/curop.h"
#include "mongo/db/curop_failpoint_helpers.h"
#include "mongo/db/dbdirectclient.h"
#include "mongo/db/index/index_descriptor.h"
#include "mongo/db/index_builds_coordinator.h"
#include "mongo/db/mongod_options_storage_gen.h"
#include "mongo/db/prepare_conflict_tracker.h"
#include "mongo/db/read_write_concern_defaults.h"
#include "mongo/db/repl/always_allow_non_local_writes.h"
#include "mongo/db/repl/check_quorum_for_config_change.h"
#include "mongo/db/repl/data_replicator_external_state_initial_sync.h"
#include "mongo/db/repl/hello_response.h"
#include "mongo/db/repl/initial_syncer_factory.h"
#include "mongo/db/repl/isself.h"
#include "mongo/db/repl/last_vote.h"
#include "mongo/db/repl/read_concern_args.h"
#include "mongo/db/repl/repl_client_info.h"
#include "mongo/db/repl/repl_server_parameters_gen.h"
#include "mongo/db/repl/repl_set_config_checks.h"
#include "mongo/db/repl/repl_set_heartbeat_args_v1.h"
#include "mongo/db/repl/repl_set_heartbeat_response.h"
#include "mongo/db/repl/repl_set_request_votes_args.h"
#include "mongo/db/repl/repl_settings.h"
#include "mongo/db/repl/replica_set_aware_service.h"
#include "mongo/db/repl/replication_coordinator_impl_gen.h"
#include "mongo/db/repl/replication_metrics.h"
#include "mongo/db/repl/replication_process.h"
#include "mongo/db/repl/storage_interface.h"
#include "mongo/db/repl/tenant_migration_access_blocker_util.h"
#include "mongo/db/repl/tenant_migration_decoration.h"
#include "mongo/db/repl/transaction_oplog_application.h"
#include "mongo/db/repl/update_position_args.h"
#include "mongo/db/repl/vote_requester.h"
#include "mongo/db/server_options.h"
#include "mongo/db/session/kill_sessions_local.h"
#include "mongo/db/session/session_catalog.h"
#include "mongo/db/shutdown_in_progress_quiesce_info.h"
#include "mongo/db/storage/control/journal_flusher.h"
#include "mongo/db/storage/storage_options.h"
#include "mongo/db/vector_clock.h"
#include "mongo/db/vector_clock_mutable.h"
#include "mongo/db/write_concern.h"
#include "mongo/db/write_concern_options.h"
#include "mongo/executor/connection_pool_stats.h"
#include "mongo/executor/network_interface.h"
#include "mongo/logv2/log.h"
#include "mongo/platform/mutex.h"
#include "mongo/rpc/metadata/oplog_query_metadata.h"
#include "mongo/rpc/metadata/repl_set_metadata.h"
#include "mongo/transport/hello_metrics.h"
#include "mongo/util/assert_util.h"
#include "mongo/util/fail_point.h"
#include "mongo/util/scopeguard.h"
#include "mongo/util/stacktrace.h"
#include "mongo/util/synchronized_value.h"
#include "mongo/util/testing_proctor.h"
#include "mongo/util/time_support.h"
#include "mongo/util/timer.h"
#define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kReplication
namespace mongo {
namespace repl {
MONGO_FAIL_POINT_DEFINE(stepdownHangBeforePerformingPostMemberStateUpdateActions);
MONGO_FAIL_POINT_DEFINE(stepdownHangBeforeRSTLEnqueue);
// Fail setMaintenanceMode with ErrorCodes::NotSecondary to simulate a concurrent election.
MONGO_FAIL_POINT_DEFINE(setMaintenanceModeFailsWithNotSecondary);
MONGO_FAIL_POINT_DEFINE(forceSyncSourceRetryWaitForInitialSync);
// Signals that a hello request has started waiting.
MONGO_FAIL_POINT_DEFINE(waitForHelloResponse);
// Will cause a hello request to hang as it starts waiting.
MONGO_FAIL_POINT_DEFINE(hangWhileWaitingForHelloResponse);
// Will cause a hello request to hang after it times out waiting for a topology change.
MONGO_FAIL_POINT_DEFINE(hangAfterWaitingForTopologyChangeTimesOut);
MONGO_FAIL_POINT_DEFINE(skipDurableTimestampUpdates);
// Skip sending heartbeats to pre-check that a quorum is available before a reconfig.
MONGO_FAIL_POINT_DEFINE(omitConfigQuorumCheck);
// Will cause signal drain complete to hang right before acquiring the RSTL.
MONGO_FAIL_POINT_DEFINE(hangBeforeRSTLOnDrainComplete);
// Will cause signal drain complete to hang before reconfig.
MONGO_FAIL_POINT_DEFINE(hangBeforeReconfigOnDrainComplete);
// Will cause signal drain complete to hang after reconfig.
MONGO_FAIL_POINT_DEFINE(hangAfterReconfigOnDrainComplete);
MONGO_FAIL_POINT_DEFINE(doNotRemoveNewlyAddedOnHeartbeats);
// Will hang right after setting the currentOp info associated with an automatic reconfig.
MONGO_FAIL_POINT_DEFINE(hangDuringAutomaticReconfig);
// Make reconfig command hang before validating new config.
MONGO_FAIL_POINT_DEFINE(ReconfigHangBeforeConfigValidationCheck);
// Blocks after reconfig runs.
MONGO_FAIL_POINT_DEFINE(hangAfterReconfig);
// Allows skipping fetching the config from ping sender.
MONGO_FAIL_POINT_DEFINE(skipBeforeFetchingConfig);
// Hang after grabbing the RSTL but before we start rejecting writes.
MONGO_FAIL_POINT_DEFINE(stepdownHangAfterGrabbingRSTL);
// Hang before making checks on the new config relative to the current one.
MONGO_FAIL_POINT_DEFINE(hangBeforeNewConfigValidationChecks);
// Simulates returning a specified error in the hello response.
MONGO_FAIL_POINT_DEFINE(setCustomErrorInHelloResponseMongoD);
// Throws right before the call into recoverTenantMigrationAccessBlockers.
MONGO_FAIL_POINT_DEFINE(throwBeforeRecoveringTenantMigrationAccessBlockers);
// Number of times we tried to go live as a secondary.
CounterMetric attemptsToBecomeSecondary("repl.apply.attemptsToBecomeSecondary");
// Tracks the last state transition performed in this replica set.
auto& lastStateTransition =
makeSynchronizedMetric<std::string>("repl.stateTransition.lastStateTransition");
// Tracks the number of operations killed on state transition.
CounterMetric userOpsKilled("repl.stateTransition.userOperationsKilled");
// Tracks the number of operations left running on state transition.
CounterMetric userOpsRunning("repl.stateTransition.userOperationsRunning");
// Tracks the number of times we have successfully performed automatic reconfigs to remove
// 'newlyAdded' fields.
CounterMetric numAutoReconfigsForRemovalOfNewlyAddedFields(
"repl.reconfig.numAutoReconfigsForRemovalOfNewlyAddedFields");
using namespace fmt::literals;
using CallbackArgs = executor::TaskExecutor::CallbackArgs;
using CallbackFn = executor::TaskExecutor::CallbackFn;
using CallbackHandle = executor::TaskExecutor::CallbackHandle;
using EventHandle = executor::TaskExecutor::EventHandle;
using executor::NetworkInterface;
using NextAction = Fetcher::NextAction;
namespace {
const char kLocalDB[] = "local";
void lockAndCall(stdx::unique_lock<Latch>* lk, const std::function<void()>& fn) {
if (!lk->owns_lock()) {
lk->lock();
}
fn();
}
template <typename T>
StatusOrStatusWith<T> futureGetNoThrowWithDeadline(OperationContext* opCtx,
SharedSemiFuture<T>& f,
Date_t deadline,
ErrorCodes::Error error) {
try {
return opCtx->runWithDeadline(deadline, error, [&] { return f.getNoThrow(opCtx); });
} catch (const DBException& e) {
return e.toStatus();
}
}
constexpr StringData kQuiesceModeShutdownMessage =
"The server is in quiesce mode and will shut down"_sd;
} // namespace
void ReplicationCoordinatorImpl::WaiterList::add_inlock(const OpTime& opTime,
SharedWaiterHandle waiter) {
_waiters.emplace(opTime, std::move(waiter));
}
SharedSemiFuture<void> ReplicationCoordinatorImpl::WaiterList::add_inlock(
const OpTime& opTime, boost::optional<WriteConcernOptions> wc) {
auto pf = makePromiseFuture<void>();
_waiters.emplace(opTime, std::make_shared<Waiter>(std::move(pf.promise), std::move(wc)));
return std::move(pf.future);
}
bool ReplicationCoordinatorImpl::WaiterList::remove_inlock(SharedWaiterHandle waiter) {
for (auto iter = _waiters.begin(); iter != _waiters.end(); iter++) {
if (iter->second == waiter) {
_waiters.erase(iter);
return true;
}
}
return false;
}
template <typename Func>
void ReplicationCoordinatorImpl::WaiterList::setValueIf_inlock(Func&& func,
boost::optional<OpTime> opTime) {
for (auto it = _waiters.begin(); it != _waiters.end() && (!opTime || it->first <= *opTime);) {
const auto& waiter = it->second;
try {
if (func(it->first, waiter)) {
waiter->promise.emplaceValue();
it = _waiters.erase(it);
} else {
++it;
}
} catch (const DBException& e) {
waiter->promise.setError(e.toStatus());
it = _waiters.erase(it);
}
}
}
void ReplicationCoordinatorImpl::WaiterList::setValueAll_inlock() {
for (auto& [opTime, waiter] : _waiters) {
waiter->promise.emplaceValue();
}
_waiters.clear();
}
void ReplicationCoordinatorImpl::WaiterList::setErrorAll_inlock(Status status) {
invariant(!status.isOK());
for (auto& [opTime, waiter] : _waiters) {
waiter->promise.setError(status);
}
_waiters.clear();
}
namespace {
ReplicationCoordinator::Mode getReplicationModeFromSettings(const ReplSettings& settings) {
if (settings.usingReplSets()) {
return ReplicationCoordinator::modeReplSet;
}
return ReplicationCoordinator::modeNone;
}
InitialSyncerInterface::Options createInitialSyncerOptions(
ReplicationCoordinator* replCoord, ReplicationCoordinatorExternalState* externalState) {
InitialSyncerInterface::Options options;
options.getMyLastOptime = [replCoord]() { return replCoord->getMyLastAppliedOpTime(); };
options.setMyLastOptime = [replCoord,
externalState](const OpTimeAndWallTime& opTimeAndWallTime) {
// Note that setting the last applied opTime forward also advances the global timestamp.
replCoord->setMyLastAppliedOpTimeAndWallTimeForward(opTimeAndWallTime);
signalOplogWaiters();
// The oplog application phase of initial sync starts timestamping writes, causing
// WiredTiger to pin this data in memory. Advancing the oldest timestamp in step with the
// last applied optime here will permit WiredTiger to evict this data as it sees fit.
replCoord->getServiceContext()->getStorageEngine()->setOldestTimestamp(
opTimeAndWallTime.opTime.getTimestamp());
};
options.resetOptimes = [replCoord]() { replCoord->resetMyLastOpTimes(); };
options.syncSourceSelector = replCoord;
options.oplogFetcherMaxFetcherRestarts =
externalState->getOplogFetcherInitialSyncMaxFetcherRestarts();
// If this failpoint is set, override the default sync source retry interval for initial sync.
forceSyncSourceRetryWaitForInitialSync.execute([&](const BSONObj& data) {
auto retryMS = data["retryMS"].numberInt();
options.syncSourceRetryWait = Milliseconds(retryMS);
});
return options;
}
} // namespace
ReplicationCoordinatorImpl::ReplicationCoordinatorImpl(
ServiceContext* service,
const ReplSettings& settings,
std::unique_ptr<ReplicationCoordinatorExternalState> externalState,
std::unique_ptr<executor::TaskExecutor> executor,
std::unique_ptr<TopologyCoordinator> topCoord,
ReplicationProcess* replicationProcess,
StorageInterface* storage,
int64_t prngSeed)
: _service(service),
_settings(settings),
_replMode(getReplicationModeFromSettings(settings)),
_topCoord(std::move(topCoord)),
_replExecutor(std::move(executor)),
_externalState(std::move(externalState)),
_inShutdown(false),
_memberState(MemberState::RS_STARTUP),
_rsConfigState(kConfigPreStart),
_selfIndex(-1),
_sleptLastElection(false),
_readWriteAbility(std::make_unique<ReadWriteAbility>(!settings.usingReplSets())),
_replicationProcess(replicationProcess),
_storage(storage),
_handleLivenessTimeoutCallback(_replExecutor.get(),
[this](const executor::TaskExecutor::CallbackArgs& args) {
_handleLivenessTimeout(args);
}),
_handleElectionTimeoutCallback(
_replExecutor.get(),
[this](const executor::TaskExecutor::CallbackArgs&) {
_startElectSelfIfEligibleV1(StartElectionReasonEnum::kElectionTimeout);
},
[this](int64_t limit) { return _nextRandomInt64_inlock(limit); }),
_random(prngSeed) {
_termShadow.store(OpTime::kUninitializedTerm);
invariant(_service);
if (!isReplEnabled()) {
return;
}
// If this is a config server, then we set the periodic no-op interval to 1 second. This is to
// ensure that the config server will not unduly hold up change streams running on the cluster.
if (serverGlobalParams.clusterRole == ClusterRole::ConfigServer) {
periodicNoopIntervalSecs.store(1);
}
_externalState->setupNoopWriter(Seconds(periodicNoopIntervalSecs.load()));
}
ReplicationCoordinatorImpl::~ReplicationCoordinatorImpl() = default;
void ReplicationCoordinatorImpl::waitForStartUpComplete_forTest() {
_waitForStartUpComplete();
}
void ReplicationCoordinatorImpl::_waitForStartUpComplete() {
CallbackHandle handle;
{
stdx::unique_lock<Latch> lk(_mutex);
while (_rsConfigState == kConfigPreStart || _rsConfigState == kConfigStartingUp) {
_rsConfigStateChange.wait(lk);
}
handle = _finishLoadLocalConfigCbh;
}
if (handle.isValid()) {
_replExecutor->wait(handle);
}
}
ReplSetConfig ReplicationCoordinatorImpl::getReplicaSetConfig_forTest() {
stdx::lock_guard<Latch> lk(_mutex);
return _rsConfig;
}
Date_t ReplicationCoordinatorImpl::getElectionTimeout_forTest() const {
stdx::lock_guard<Latch> lk(_mutex);
return _handleElectionTimeoutCallback.getNextCall();
}
Milliseconds ReplicationCoordinatorImpl::getRandomizedElectionOffset_forTest() {
stdx::lock_guard<Latch> lk(_mutex);
return _getRandomizedElectionOffset_inlock();
}
boost::optional<Date_t> ReplicationCoordinatorImpl::getPriorityTakeover_forTest() const {
stdx::lock_guard<Latch> lk(_mutex);
if (!_priorityTakeoverCbh.isValid()) {
return boost::none;
}
return _priorityTakeoverWhen;
}
boost::optional<Date_t> ReplicationCoordinatorImpl::getCatchupTakeover_forTest() const {
stdx::lock_guard<Latch> lk(_mutex);
if (!_catchupTakeoverCbh.isValid()) {
return boost::none;
}
return _catchupTakeoverWhen;
}
executor::TaskExecutor::CallbackHandle ReplicationCoordinatorImpl::getCatchupTakeoverCbh_forTest()
const {
return _catchupTakeoverCbh;
}
OpTime ReplicationCoordinatorImpl::getCurrentCommittedSnapshotOpTime() const {
stdx::lock_guard<Latch> lk(_mutex);
return _getCurrentCommittedSnapshotOpTime_inlock();
}
OpTime ReplicationCoordinatorImpl::_getCurrentCommittedSnapshotOpTime_inlock() const {
return _currentCommittedSnapshot.value_or(OpTime());
}
void ReplicationCoordinatorImpl::appendDiagnosticBSON(mongo::BSONObjBuilder* bob) {
BSONObjBuilder eBuilder(bob->subobjStart("executor"));
_replExecutor->appendDiagnosticBSON(&eBuilder);
}
void ReplicationCoordinatorImpl::appendConnectionStats(executor::ConnectionPoolStats* stats) const {
_replExecutor->appendConnectionStats(stats);
}
bool ReplicationCoordinatorImpl::_startLoadLocalConfig(
OperationContext* opCtx, StorageEngine::LastShutdownState lastShutdownState) {
LOGV2(4280500, "Attempting to create internal replication collections");
// Create necessary replication collections to guarantee that if a checkpoint sees data after
// initial sync has completed, it also sees these collections.
fassert(50708, _replicationProcess->getConsistencyMarkers()->createInternalCollections(opCtx));
// Ensure (update if needed) the in-memory count for the oplogTruncateAfterPoint collection
// matches the collection contents.
_replicationProcess->getConsistencyMarkers()->ensureFastCountOnOplogTruncateAfterPoint(opCtx);
_replicationProcess->getConsistencyMarkers()->initializeMinValidDocument(opCtx);
fassert(51240, _externalState->createLocalLastVoteCollection(opCtx));
LOGV2(4280501, "Attempting to load local voted for document");
StatusWith<LastVote> lastVote = _externalState->loadLocalLastVoteDocument(opCtx);
if (!lastVote.isOK()) {
LOGV2_FATAL_NOTRACE(40367,
"Error loading local voted for document at startup; {error}",
"Error loading local voted for document at startup",
"error"_attr = lastVote.getStatus());
}
if (lastVote.getValue().getTerm() == OpTime::kInitialTerm) {
// This log line is checked in unit tests.
LOGV2(21311, "Did not find local initialized voted for document at startup");
}
{
stdx::lock_guard<Latch> lk(_mutex);
_topCoord->loadLastVote(lastVote.getValue());
}
LOGV2(4280502, "Searching for local Rollback ID document");
// Check that we have a local Rollback ID. If we do not have one, create one.
auto status = _replicationProcess->refreshRollbackID(opCtx);
if (!status.isOK()) {
if (status == ErrorCodes::NamespaceNotFound) {
LOGV2(21312, "Did not find local Rollback ID document at startup. Creating one");
auto initializingStatus = _replicationProcess->initializeRollbackID(opCtx);
fassert(40424, initializingStatus);
} else {
LOGV2_FATAL_NOTRACE(40428,
"Error loading local Rollback ID document at startup; {error}",
"Error loading local Rollback ID document at startup",
"error"_attr = status);
}
} else if (lastShutdownState == StorageEngine::LastShutdownState::kUnclean) {
LOGV2(501401, "Incrementing the rollback ID after unclean shutdown");
fassert(501402, _replicationProcess->incrementRollbackID(opCtx));
}
LOGV2_DEBUG(4280503, 1, "Attempting to load local replica set configuration document");
StatusWith<BSONObj> cfg = _externalState->loadLocalConfigDocument(opCtx);
if (!cfg.isOK()) {
LOGV2(21313,
"Did not find local replica set configuration document at startup; {error}",
"Did not find local replica set configuration document at startup",
"error"_attr = cfg.getStatus());
return true;
}
ReplSetConfig localConfig;
try {
localConfig = ReplSetConfig::parse(cfg.getValue());
} catch (const DBException& e) {
auto status = e.toStatus();
if (status.code() == ErrorCodes::RepairedReplicaSetNode) {
LOGV2_FATAL_NOTRACE(
50923,
"This instance has been repaired and may contain modified replicated data that "
"would not match other replica set members. To see your repaired data, start "
"mongod without the --replSet option. When you are finished recovering your "
"data and would like to perform a complete re-sync, please refer to the "
"documentation here: "
"https://docs.mongodb.com/manual/tutorial/resync-replica-set-member/");
}
LOGV2_FATAL_NOTRACE(
28545,
"Locally stored replica set configuration does not parse; See "
"http://www.mongodb.org/dochub/core/recover-replica-set-from-invalid-config "
"for information on how to recover from this. Got \"{error}\" while parsing "
"{config}",
"Locally stored replica set configuration does not parse; See "
"http://www.mongodb.org/dochub/core/recover-replica-set-from-invalid-config "
"for information on how to recover from this",
"error"_attr = status,
"config"_attr = cfg.getValue());
}
LOGV2(4280504, "Cleaning up any partially applied oplog batches & reading last op from oplog");
// Read the last op from the oplog after cleaning up any partially applied batches.
const auto stableTimestamp = boost::none;
_replicationProcess->getReplicationRecovery()->recoverFromOplog(opCtx, stableTimestamp);
LOGV2(4280505,
"Creating any necessary TenantMigrationAccessBlockers for unfinished migrations");
if (MONGO_unlikely(throwBeforeRecoveringTenantMigrationAccessBlockers.shouldFail())) {
uasserted(6111700,
"Failpoint 'throwBeforeRecoveringTenantMigrationAccessBlockers' triggered. "
"Throwing exception.");
}
tenant_migration_access_blocker::recoverTenantMigrationAccessBlockers(opCtx);
LOGV2(4280506, "Reconstructing prepared transactions");
reconstructPreparedTransactions(opCtx, OplogApplication::Mode::kRecovering);
const auto lastOpTimeAndWallTimeResult = _externalState->loadLastOpTimeAndWallTime(opCtx);
// Use a callback here, because _finishLoadLocalConfig calls isself() which requires
// that the server's networking layer be up and running and accepting connections, which
// doesn't happen until startReplication finishes.
auto handle =
_replExecutor->scheduleWork([=](const executor::TaskExecutor::CallbackArgs& args) {
_finishLoadLocalConfig(args, localConfig, lastOpTimeAndWallTimeResult, lastVote);
});
if (handle == ErrorCodes::ShutdownInProgress) {
handle = CallbackHandle{};
}
fassert(40446, handle);
stdx::lock_guard<Latch> lk(_mutex);
_finishLoadLocalConfigCbh = std::move(handle.getValue());
LOGV2(4280507, "Loaded replica set config, scheduled callback to set local config");
return false;
}
void ReplicationCoordinatorImpl::_createHorizonTopologyChangePromiseMapping(WithLock) {
auto horizonMappings = _rsConfig.getMemberAt(_selfIndex).getHorizonMappings();
// Create a new horizon to promise mapping since it is possible for the horizons
// to change after a replica set reconfig.
_horizonToTopologyChangePromiseMap.clear();
for (auto const& [horizon, hostAndPort] : horizonMappings) {
_horizonToTopologyChangePromiseMap.emplace(
horizon, std::make_shared<SharedPromise<std::shared_ptr<const HelloResponse>>>());
}
}
void ReplicationCoordinatorImpl::_finishLoadLocalConfig(
const executor::TaskExecutor::CallbackArgs& cbData,
const ReplSetConfig& localConfig,
const StatusWith<OpTimeAndWallTime>& lastOpTimeAndWallTimeStatus,
const StatusWith<LastVote>& lastVoteStatus) {
if (!cbData.status.isOK()) {
LOGV2_DEBUG(21314,
1,
"Loading local replica set configuration failed due to {error}",
"Loading local replica set configuration failed",
"error"_attr = cbData.status);
return;
}
LOGV2(4280508, "Attempting to set local replica set config; validating config for startup");
StatusWith<int> myIndex =
validateConfigForStartUp(_externalState.get(), localConfig, getServiceContext());
if (!myIndex.isOK()) {
if (myIndex.getStatus() == ErrorCodes::NodeNotFound ||
myIndex.getStatus() == ErrorCodes::InvalidReplicaSetConfig) {
LOGV2_WARNING(21405,
"Locally stored replica set configuration does not have a valid entry "
"for the current node; waiting for reconfig or remote heartbeat; Got "
"\"{error}\" while validating {localConfig}",
"Locally stored replica set configuration does not have a valid entry "
"for the current node; waiting for reconfig or remote heartbeat",
"error"_attr = myIndex.getStatus(),
"localConfig"_attr = localConfig.toBSON());
myIndex = StatusWith<int>(-1);
} else {
LOGV2_ERROR(21415,
"Locally stored replica set configuration is invalid; See "
"http://www.mongodb.org/dochub/core/recover-replica-set-from-invalid-config"
" for information on how to recover from this. Got \"{error}\" "
"while validating {localConfig}",
"Locally stored replica set configuration is invalid; See "
"http://www.mongodb.org/dochub/core/recover-replica-set-from-invalid-config"
" for information on how to recover from this",
"error"_attr = myIndex.getStatus(),
"localConfig"_attr = localConfig.toBSON());
fassertFailedNoTrace(28544);
}
}
if (!_settings.isServerless() && localConfig.getReplSetName() != _settings.ourSetName()) {
LOGV2_WARNING(21406,
"Local replica set configuration document reports set name of "
"{localConfigSetName}, but command line reports "
"{commandLineSetName}; waiting for reconfig or remote heartbeat",
"Local replica set configuration document set name differs from command line "
"set name; waiting for reconfig or remote heartbeat",
"localConfigSetName"_attr = localConfig.getReplSetName(),
"commandLineSetName"_attr = _settings.ourSetName());
myIndex = StatusWith<int>(-1);
}
LOGV2(4280509, "Local configuration validated for startup");
// Do not check optime, if this node is an arbiter.
bool isArbiter =
myIndex.getValue() != -1 && localConfig.getMemberAt(myIndex.getValue()).isArbiter();
OpTimeAndWallTime lastOpTimeAndWallTime = OpTimeAndWallTime();
if (!isArbiter) {
if (!lastOpTimeAndWallTimeStatus.isOK()) {
LOGV2_WARNING(
21407,
"Failed to load timestamp and/or wall clock time of most recently applied "
"operation: {error}",
"Failed to load timestamp and/or wall clock time of most recently applied "
"operation",
"error"_attr = lastOpTimeAndWallTimeStatus.getStatus());
} else {
lastOpTimeAndWallTime = lastOpTimeAndWallTimeStatus.getValue();
}
} else {
ReplicaSetAwareServiceRegistry::get(_service).onBecomeArbiter();
}
const auto lastOpTime = lastOpTimeAndWallTime.opTime;
// Restore the current term according to the terms of last oplog entry and last vote.
// The initial term of OpTime() is 0.
long long term = lastOpTime.getTerm();
if (lastVoteStatus.isOK()) {
long long lastVoteTerm = lastVoteStatus.getValue().getTerm();
if (term < lastVoteTerm) {
term = lastVoteTerm;
}
}
auto opCtx = cc().makeOperationContext();
if (!lastOpTime.isNull()) {
// If we have an oplog, it is still possible that our data is not in a consistent state. For
// example, if we are starting up after a crash following a post-rollback RECOVERING state.
// To detect this, we see if our last optime is >= the 'minValid' optime, which
// should be persistent across node crashes.
OpTime minValid = _replicationProcess->getConsistencyMarkers()->getMinValid(opCtx.get());
// It is not safe to take stable checkpoints until we reach minValid, so we set our
// initialDataTimestamp to prevent this. It is expected that this is only necessary when
// enableMajorityReadConcern:false.
if (lastOpTime < minValid) {
LOGV2_DEBUG(4916700,
2,
"Setting initialDataTimestamp to minValid since our last optime is less "
"than minValid",
"lastOpTime"_attr = lastOpTime,
"minValid"_attr = minValid);
_storage->setInitialDataTimestamp(getServiceContext(), minValid.getTimestamp());
}
}
// Update the global timestamp before setting the last applied opTime forward so the last
// applied optime is never greater than the latest cluster time in the logical clock.
_externalState->setGlobalTimestamp(getServiceContext(), lastOpTime.getTimestamp());
stdx::unique_lock<Latch> lock(_mutex);
invariant(_rsConfigState == kConfigStartingUp);
const PostMemberStateUpdateAction action =
_setCurrentRSConfig(lock, opCtx.get(), localConfig, myIndex.getValue());
// Set our last applied and durable optimes to the top of the oplog, if we have one.
if (!lastOpTime.isNull()) {
LOGV2_DEBUG(4280510,
1,
"Setting this node's last applied and durable opTimes to the top of the oplog");
bool isRollbackAllowed = false;
_setMyLastAppliedOpTimeAndWallTime(lock, lastOpTimeAndWallTime, isRollbackAllowed);
_setMyLastDurableOpTimeAndWallTime(lock, lastOpTimeAndWallTime, isRollbackAllowed);
_reportUpstream_inlock(std::move(lock)); // unlocks _mutex.
} else {
lock.unlock();
}
{
stdx::lock_guard<Latch> lk(_mutex);
// Step down is impossible, so we don't need to wait for the returned event.
_updateTerm_inlock(term);
}
LOGV2(21320, "Current term is now {term}", "Updated term", "term"_attr = term);
_performPostMemberStateUpdateAction(action);
if (!isArbiter && myIndex.getValue() != -1) {
_externalState->startThreads();
_startDataReplication(opCtx.get());
}
LOGV2(4280511, "Set local replica set config");
}
void ReplicationCoordinatorImpl::_startInitialSync(
OperationContext* opCtx,
InitialSyncerInterface::OnCompletionFn onCompletion,
bool fallbackToLogical) {
std::shared_ptr<InitialSyncerInterface> initialSyncerCopy;
// Initial sync may take locks during startup; make sure there is no possibility of conflict.
dassert(!opCtx->lockState()->isLocked());
try {
{
// Must take the lock to set _initialSyncer, but not call it.
stdx::lock_guard<Latch> lock(_mutex);
if (_inShutdown || _inTerminalShutdown) {
LOGV2(21326, "Initial Sync not starting because replication is shutting down");
return;
}
auto initialSyncerFactory = InitialSyncerFactory::get(opCtx->getServiceContext());
auto createInitialSyncer = [&](const std::string& method) {
return initialSyncerFactory->makeInitialSyncer(
method,
createInitialSyncerOptions(this, _externalState.get()),
std::make_unique<DataReplicatorExternalStateInitialSync>(this,
_externalState.get()),
_externalState->getDbWorkThreadPool(),
_storage,
_replicationProcess,
onCompletion);
};
if (!fallbackToLogical) {
auto swInitialSyncer = createInitialSyncer(initialSyncMethod);
if (swInitialSyncer.getStatus().code() == ErrorCodes::NotImplemented &&
initialSyncMethod != "logical") {
LOGV2_WARNING(58154,
"No such initial sync method was available. Falling back to "
"logical initial sync.",
"initialSyncMethod"_attr = initialSyncMethod,
"error"_attr = swInitialSyncer.getStatus().reason());
swInitialSyncer = createInitialSyncer(std::string("logical"));
}
initialSyncerCopy = uassertStatusOK(swInitialSyncer);
} else {
auto swInitialSyncer = createInitialSyncer(std::string("logical"));
initialSyncerCopy = uassertStatusOK(swInitialSyncer);
}
_initialSyncer = initialSyncerCopy;
}
// InitialSyncer::startup() must be called outside lock because it uses features (eg.
// setting the initial sync flag) which depend on the ReplicationCoordinatorImpl.
uassertStatusOK(initialSyncerCopy->startup(opCtx, numInitialSyncAttempts.load()));
LOGV2(4280514, "Initial sync started");
} catch (const DBException& e) {
auto status = e.toStatus();
LOGV2(21327,
"Initial Sync failed to start: {error}",
"Initial Sync failed to start",
"error"_attr = status);
if (ErrorCodes::CallbackCanceled == status || ErrorCodes::isShutdownError(status.code())) {
return;
}
fassertFailedWithStatusNoTrace(40354, status);
}
}
void ReplicationCoordinatorImpl::_initialSyncerCompletionFunction(
const StatusWith<OpTimeAndWallTime>& opTimeStatus) {
{
stdx::unique_lock<Latch> lock(_mutex);
if (opTimeStatus == ErrorCodes::CallbackCanceled) {
LOGV2(21324,
"Initial Sync has been cancelled: {error}",
"Initial Sync has been cancelled",
"error"_attr = opTimeStatus.getStatus());
return;
} else if (!opTimeStatus.isOK()) {
if (_inShutdown || _inTerminalShutdown) {
LOGV2(21325,
"Initial Sync failed during shutdown due to {error}",
"Initial Sync failed during shutdown",
"error"_attr = opTimeStatus.getStatus());
return;
} else if (opTimeStatus == ErrorCodes::InvalidSyncSource &&
_initialSyncer->getInitialSyncMethod() != "logical") {
LOGV2(5780600,
"Falling back to logical initial sync: {error}",
"Falling back to logical initial sync",
"error"_attr = opTimeStatus.getStatus());
lock.unlock();
clearSyncSourceDenylist();
_scheduleWorkAt(_replExecutor->now(),
[=](const mongo::executor::TaskExecutor::CallbackArgs& cbData) {
_startInitialSync(
cc().makeOperationContext().get(),
[this](const StatusWith<OpTimeAndWallTime>& opTimeStatus) {
_initialSyncerCompletionFunction(opTimeStatus);
},
true /* fallbackToLogical */);
});
return;
} else {
LOGV2_ERROR(21416,
"Initial sync failed, shutting down now. Restart the server "
"to attempt a new initial sync");
fassertFailedWithStatusNoTrace(40088, opTimeStatus.getStatus());
}
}
const auto lastApplied = opTimeStatus.getValue();
_setMyLastAppliedOpTimeAndWallTime(lock, lastApplied, false);
signalOplogWaiters();
_topCoord->resetMaintenanceCount();
}
ReplicaSetAwareServiceRegistry::get(_service).onInitialDataAvailable(
cc().makeOperationContext().get(), false /* isMajorityDataAvailable */);
// Transition from STARTUP2 to RECOVERING and start the producer and the applier.
// If the member state is REMOVED, this will do nothing until we receive a config with
// ourself in it.
const auto memberState = getMemberState();
invariant(memberState.startup2() || memberState.removed());
invariant(setFollowerMode(MemberState::RS_RECOVERING));
auto opCtxHolder = cc().makeOperationContext();
_externalState->startSteadyStateReplication(opCtxHolder.get(), this);
// This log is used in tests to ensure we made it to this point.
LOGV2_DEBUG(4853000, 1, "initial sync complete.");
}
void ReplicationCoordinatorImpl::_startDataReplication(OperationContext* opCtx) {
if (_startedSteadyStateReplication.swap(true)) {
// This is not the first call.
return;
}
// Make sure we're not holding any locks; existing locks might conflict with operations
// we take during initial sync or replication steady state startup.
dassert(!opCtx->lockState()->isLocked());
// Check to see if we need to do an initial sync.
const auto lastOpTime = getMyLastAppliedOpTime();
const auto needsInitialSync =
lastOpTime.isNull() || _externalState->isInitialSyncFlagSet(opCtx);
if (!needsInitialSync) {
LOGV2(4280512, "No initial sync required. Attempting to begin steady replication");
// Start steady replication, since we already have data.
// ReplSetConfig has been installed, so it's either in STARTUP2 or REMOVED.
auto memberState = getMemberState();
invariant(memberState.startup2() || memberState.removed());
invariant(setFollowerMode(MemberState::RS_RECOVERING));
// Set an initial sync ID, in case we were upgraded or restored from backup without doing
// an initial sync.
_replicationProcess->getConsistencyMarkers()->setInitialSyncIdIfNotSet(opCtx);
_externalState->startSteadyStateReplication(opCtx, this);
return;
}
LOGV2(4280513, "Initial sync required. Attempting to start initial sync...");
// Do initial sync.
if (!_externalState->getTaskExecutor()) {
LOGV2(21323, "Not running initial sync during test");
return;
}
_startInitialSync(opCtx, [this](const StatusWith<OpTimeAndWallTime>& opTimeStatus) {
_initialSyncerCompletionFunction(opTimeStatus);
});
}
void ReplicationCoordinatorImpl::startup(OperationContext* opCtx,
StorageEngine::LastShutdownState lastShutdownState) {
if (!isReplEnabled()) {
if (ReplSettings::shouldRecoverFromOplogAsStandalone()) {
uassert(ErrorCodes::InvalidOptions,
str::stream() << "Cannot set parameter 'recoverToOplogTimestamp' "
<< "when recovering from the oplog as a standalone",
recoverToOplogTimestamp.empty());
_replicationProcess->getReplicationRecovery()->recoverFromOplogAsStandalone(opCtx);
}
if (storageGlobalParams.queryableBackupMode && !recoverToOplogTimestamp.empty()) {
BSONObj recoverToTimestampObj = fromjson(recoverToOplogTimestamp);
uassert(ErrorCodes::BadValue,
str::stream() << "'recoverToOplogTimestamp' needs to have a 'timestamp' field",
recoverToTimestampObj.hasField("timestamp"));
Timestamp recoverToTimestamp = recoverToTimestampObj.getField("timestamp").timestamp();
uassert(ErrorCodes::BadValue,
str::stream() << "'recoverToOplogTimestamp' needs to be a valid timestamp",
!recoverToTimestamp.isNull());
StatusWith<BSONObj> cfg = _externalState->loadLocalConfigDocument(opCtx);
uassert(ErrorCodes::InvalidReplicaSetConfig,
str::stream()
<< "No replica set config document was found, 'recoverToOplogTimestamp' "
<< "must be used with a node that was previously part of a replica set",
cfg.isOK());
// Need to perform replication recovery up to and including the given timestamp.
_replicationProcess->getReplicationRecovery()->recoverFromOplogUpTo(opCtx,
recoverToTimestamp);
}
stdx::lock_guard<Latch> lk(_mutex);
_setConfigState_inlock(kConfigReplicationDisabled);
return;
}
invariant(_settings.usingReplSets());
invariant(!ReplSettings::shouldRecoverFromOplogAsStandalone());
_storage->initializeStorageControlsForReplication(opCtx->getServiceContext());
// We are expected to be able to transition out of the kConfigStartingUp state by the end
// of this function. Any uncaught exceptions here leave us in an invalid state and we will
// not be able to shut down by normal means, as clean shutdown assumes we can leave that state.
try {
{
stdx::lock_guard<Latch> lk(_mutex);
fassert(18822, !_inShutdown);
_setConfigState_inlock(kConfigStartingUp);
_topCoord->setStorageEngineSupportsReadCommitted(
_externalState->isReadCommittedSupportedByStorageEngine(opCtx));
}
// Initialize the cached pointer to the oplog collection.
acquireOplogCollectionForLogging(opCtx);
_replExecutor->startup();
LOGV2(6005300, "Starting up replica set aware services");
ReplicaSetAwareServiceRegistry::get(_service).onStartup(opCtx);
bool doneLoadingConfig = _startLoadLocalConfig(opCtx, lastShutdownState);
if (doneLoadingConfig) {
// If we're not done loading the config, then the config state will be set by
// _finishLoadLocalConfig.
stdx::lock_guard<Latch> lk(_mutex);
invariant(!_rsConfig.isInitialized());
_setConfigState_inlock(kConfigUninitialized);
}
} catch (DBException& e) {
auto status = e.toStatus();
LOGV2_FATAL_NOTRACE(
6111701, "Failed to load local replica set config on startup", "status"_attr = status);
}
}
void ReplicationCoordinatorImpl::_setImplicitDefaultWriteConcern(OperationContext* opCtx,
WithLock lk) {
auto& rwcDefaults = ReadWriteConcernDefaults::get(opCtx);
bool isImplicitDefaultWriteConcernMajority = _rsConfig.isImplicitDefaultWriteConcernMajority();
rwcDefaults.setImplicitDefaultWriteConcernMajority(isImplicitDefaultWriteConcernMajority);
}
void ReplicationCoordinatorImpl::enterTerminalShutdown() {
std::shared_ptr<InitialSyncerInterface> initialSyncerCopy;
{
stdx::lock_guard lk(_mutex);
_inTerminalShutdown = true;
initialSyncerCopy = _initialSyncer;
}
// Shutting down the initial syncer early works around an issue where an initial syncer may not
// be able to shut down with an opCtx active. No opCtx is active when enterTerminalShutdown is
// called due to a signal.
if (initialSyncerCopy) {
const auto status = initialSyncerCopy->shutdown();
if (!status.isOK()) {
LOGV2_WARNING(6137700,
"InitialSyncer shutdown failed: {error}",
"InitialSyncer shutdown failed",
"error"_attr = status);
}
}
}
bool ReplicationCoordinatorImpl::enterQuiesceModeIfSecondary(Milliseconds quiesceTime) {
LOGV2_INFO(4794602, "Attempting to enter quiesce mode");
stdx::lock_guard lk(_mutex);