/
replication_coordinator_impl.h
1353 lines (1078 loc) · 54.3 KB
/
replication_coordinator_impl.h
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) 2014 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.
*/
#pragma once
#include <memory>
#include <utility>
#include <vector>
#include "mongo/base/status.h"
#include "mongo/bson/timestamp.h"
#include "mongo/db/concurrency/d_concurrency.h"
#include "mongo/db/repl/initial_syncer.h"
#include "mongo/db/repl/member_state.h"
#include "mongo/db/repl/old_update_position_args.h"
#include "mongo/db/repl/optime.h"
#include "mongo/db/repl/repl_set_config.h"
#include "mongo/db/repl/replication_coordinator.h"
#include "mongo/db/repl/replication_coordinator_external_state.h"
#include "mongo/db/repl/sync_source_resolver.h"
#include "mongo/db/repl/topology_coordinator.h"
#include "mongo/db/repl/update_position_args.h"
#include "mongo/db/storage/snapshot_name.h"
#include "mongo/executor/task_executor.h"
#include "mongo/platform/atomic_word.h"
#include "mongo/platform/random.h"
#include "mongo/platform/unordered_map.h"
#include "mongo/platform/unordered_set.h"
#include "mongo/stdx/condition_variable.h"
#include "mongo/stdx/mutex.h"
#include "mongo/util/concurrency/with_lock.h"
#include "mongo/util/net/hostandport.h"
namespace mongo {
class Timer;
template <typename T>
class StatusWith;
namespace executor {
struct ConnectionPoolStats;
} // namespace executor
namespace rpc {
class OplogQueryMetadata;
class ReplSetMetadata;
} // namespace rpc
namespace repl {
class ElectCmdRunner;
class FreshnessChecker;
class HandshakeArgs;
class HeartbeatResponseAction;
class LastVote;
class OplogReader;
class ReplicationProcess;
class ReplSetRequestVotesArgs;
class ReplSetConfig;
class SyncSourceFeedback;
class StorageInterface;
class TopologyCoordinator;
class VoteRequester;
class ReplicationCoordinatorImpl : public ReplicationCoordinator {
MONGO_DISALLOW_COPYING(ReplicationCoordinatorImpl);
public:
ReplicationCoordinatorImpl(ServiceContext* serviceContext,
const ReplSettings& settings,
std::unique_ptr<ReplicationCoordinatorExternalState> externalState,
std::unique_ptr<executor::TaskExecutor> executor,
std::unique_ptr<TopologyCoordinator> topoCoord,
ReplicationProcess* replicationProcess,
StorageInterface* storage,
int64_t prngSeed);
virtual ~ReplicationCoordinatorImpl();
// ================== Members of public ReplicationCoordinator API ===================
virtual void startup(OperationContext* opCtx) override;
virtual void shutdown(OperationContext* opCtx) override;
virtual const ReplSettings& getSettings() const override;
virtual Mode getReplicationMode() const override;
virtual MemberState getMemberState() const override;
virtual Status waitForMemberState(MemberState expectedState, Milliseconds timeout) override;
virtual bool isInPrimaryOrSecondaryState() const override;
virtual Seconds getSlaveDelaySecs() const override;
virtual void clearSyncSourceBlacklist() override;
virtual ReplicationCoordinator::StatusAndDuration awaitReplication(
OperationContext* opCtx, const OpTime& opTime, const WriteConcernOptions& writeConcern);
virtual ReplicationCoordinator::StatusAndDuration awaitReplicationOfLastOpForClient(
OperationContext* opCtx, const WriteConcernOptions& writeConcern);
virtual Status stepDown(OperationContext* opCtx,
bool force,
const Milliseconds& waitTime,
const Milliseconds& stepdownTime);
virtual bool isMasterForReportingPurposes();
virtual bool canAcceptWritesForDatabase(OperationContext* opCtx, StringData dbName);
virtual bool canAcceptWritesForDatabase_UNSAFE(OperationContext* opCtx, StringData dbName);
bool canAcceptWritesFor(OperationContext* opCtx, const NamespaceString& ns) override;
bool canAcceptWritesFor_UNSAFE(OperationContext* opCtx, const NamespaceString& ns) override;
virtual Status checkIfWriteConcernCanBeSatisfied(const WriteConcernOptions& writeConcern) const;
virtual Status checkCanServeReadsFor(OperationContext* opCtx,
const NamespaceString& ns,
bool slaveOk);
virtual Status checkCanServeReadsFor_UNSAFE(OperationContext* opCtx,
const NamespaceString& ns,
bool slaveOk);
virtual bool shouldRelaxIndexConstraints(OperationContext* opCtx, const NamespaceString& ns);
virtual Status setLastOptimeForSlave(const OID& rid, const Timestamp& ts);
virtual void setMyLastAppliedOpTime(const OpTime& opTime);
virtual void setMyLastDurableOpTime(const OpTime& opTime);
virtual void setMyLastAppliedOpTimeForward(const OpTime& opTime);
virtual void setMyLastDurableOpTimeForward(const OpTime& opTime);
virtual void resetMyLastOpTimes();
virtual void setMyHeartbeatMessage(const std::string& msg);
virtual OpTime getMyLastAppliedOpTime() const override;
virtual OpTime getMyLastDurableOpTime() const override;
virtual Status waitUntilOpTimeForRead(OperationContext* opCtx,
const ReadConcernArgs& readConcern) override;
virtual OID getElectionId() override;
virtual OID getMyRID() const override;
virtual int getMyId() const override;
virtual Status setFollowerMode(const MemberState& newState) override;
virtual ApplierState getApplierState() override;
virtual void signalDrainComplete(OperationContext* opCtx,
long long termWhenBufferIsEmpty) override;
virtual Status waitForDrainFinish(Milliseconds timeout) override;
virtual void signalUpstreamUpdater() override;
virtual Status resyncData(OperationContext* opCtx, bool waitUntilCompleted) override;
virtual StatusWith<BSONObj> prepareReplSetUpdatePositionCommand(
ReplSetUpdatePositionCommandStyle commandStyle) const override;
virtual Status processReplSetGetStatus(BSONObjBuilder* result,
ReplSetGetStatusResponseStyle responseStyle) override;
virtual void fillIsMasterForReplSet(IsMasterResponse* result) override;
virtual void appendSlaveInfoData(BSONObjBuilder* result) override;
virtual ReplSetConfig getConfig() const override;
virtual void processReplSetGetConfig(BSONObjBuilder* result) override;
virtual void processReplSetMetadata(const rpc::ReplSetMetadata& replMetadata) override;
virtual void advanceCommitPoint(const OpTime& committedOpTime) override;
virtual void cancelAndRescheduleElectionTimeout() override;
virtual Status setMaintenanceMode(bool activate) override;
virtual bool getMaintenanceMode() override;
virtual Status processReplSetSyncFrom(OperationContext* opCtx,
const HostAndPort& target,
BSONObjBuilder* resultObj) override;
virtual Status processReplSetFreeze(int secs, BSONObjBuilder* resultObj) override;
virtual Status processHeartbeat(const ReplSetHeartbeatArgs& args,
ReplSetHeartbeatResponse* response) override;
virtual Status processReplSetReconfig(OperationContext* opCtx,
const ReplSetReconfigArgs& args,
BSONObjBuilder* resultObj) override;
virtual Status processReplSetInitiate(OperationContext* opCtx,
const BSONObj& configObj,
BSONObjBuilder* resultObj) override;
virtual Status processReplSetFresh(const ReplSetFreshArgs& args,
BSONObjBuilder* resultObj) override;
virtual Status processReplSetElect(const ReplSetElectArgs& args,
BSONObjBuilder* response) override;
virtual Status processReplSetUpdatePosition(const OldUpdatePositionArgs& updates,
long long* configVersion) override;
virtual Status processReplSetUpdatePosition(const UpdatePositionArgs& updates,
long long* configVersion) override;
virtual Status processHandshake(OperationContext* opCtx,
const HandshakeArgs& handshake) override;
virtual bool buildsIndexes() override;
virtual std::vector<HostAndPort> getHostsWrittenTo(const OpTime& op,
bool durablyWritten) override;
virtual std::vector<HostAndPort> getOtherNodesInReplSet() const override;
virtual WriteConcernOptions getGetLastErrorDefault() override;
virtual Status checkReplEnabledForCommand(BSONObjBuilder* result) override;
virtual bool isReplEnabled() const override;
virtual HostAndPort chooseNewSyncSource(const OpTime& lastOpTimeFetched) override;
virtual void blacklistSyncSource(const HostAndPort& host, Date_t until) override;
virtual void resetLastOpTimesFromOplog(OperationContext* opCtx) override;
virtual bool shouldChangeSyncSource(
const HostAndPort& currentSource,
const rpc::ReplSetMetadata& replMetadata,
boost::optional<rpc::OplogQueryMetadata> oqMetadata) override;
virtual OpTime getLastCommittedOpTime() const override;
virtual Status processReplSetRequestVotes(OperationContext* opCtx,
const ReplSetRequestVotesArgs& args,
ReplSetRequestVotesResponse* response) override;
virtual void prepareReplMetadata(OperationContext* opCtx,
const BSONObj& metadataRequestObj,
const OpTime& lastOpTimeFromClient,
BSONObjBuilder* builder) const override;
virtual Status processHeartbeatV1(const ReplSetHeartbeatArgsV1& args,
ReplSetHeartbeatResponse* response) override;
virtual bool isV1ElectionProtocol() const override;
virtual bool getWriteConcernMajorityShouldJournal() override;
virtual void summarizeAsHtml(ReplSetHtmlSummary* s) override;
virtual void dropAllSnapshots() override;
/**
* Get current term from topology coordinator
*/
virtual long long getTerm() override;
// Returns the ServiceContext where this instance runs.
virtual ServiceContext* getServiceContext() override {
return _service;
}
virtual Status updateTerm(OperationContext* opCtx, long long term) override;
virtual SnapshotName reserveSnapshotName(OperationContext* opCtx) override;
virtual void createSnapshot(OperationContext* opCtx,
OpTime timeOfSnapshot,
SnapshotName name) override;
virtual OpTime getCurrentCommittedSnapshotOpTime() const override;
virtual void waitUntilSnapshotCommitted(OperationContext* opCtx,
const SnapshotName& untilSnapshot) override;
virtual void appendDiagnosticBSON(BSONObjBuilder*) override;
virtual void appendConnectionStats(executor::ConnectionPoolStats* stats) const override;
virtual size_t getNumUncommittedSnapshots() override;
virtual WriteConcernOptions populateUnsetWriteConcernOptionsSyncMode(
WriteConcernOptions wc) override;
virtual ReplSettings::IndexPrefetchConfig getIndexPrefetchConfig() const override;
virtual void setIndexPrefetchConfig(const ReplSettings::IndexPrefetchConfig cfg) override;
virtual Status stepUpIfEligible() override;
virtual Status abortCatchupIfNeeded() override;
// ================== Test support API ===================
/**
* If called after startReplication(), blocks until all asynchronous
* activities associated with replication start-up complete.
*/
void waitForStartUpComplete_forTest();
/**
* Gets the replica set configuration in use by the node.
*/
ReplSetConfig getReplicaSetConfig_forTest();
/**
* Returns scheduled time of election timeout callback.
* Returns Date_t() if callback is not scheduled.
*/
Date_t getElectionTimeout_forTest() const;
/*
* Return a randomized offset amount that is scaled in proportion to the size of the
* _electionTimeoutPeriod.
*/
Milliseconds getRandomizedElectionOffset_forTest();
/**
* Returns the scheduled time of the priority takeover callback. If a priority
* takeover has not been scheduled, returns boost::none.
*/
boost::optional<Date_t> getPriorityTakeover_forTest() const;
/**
* Returns the scheduled time of the catchup takeover callback. If a catchup
* takeover has not been scheduled, returns boost::none.
*/
boost::optional<Date_t> getCatchupTakeover_forTest() const;
/**
* Returns the catchup takeover CallbackHandle.
*/
executor::TaskExecutor::CallbackHandle getCatchupTakeoverCbh_forTest() const;
/**
* Simple wrappers around _setLastOptime_inlock to make it easier to test.
*/
Status setLastAppliedOptime_forTest(long long cfgVer, long long memberId, const OpTime& opTime);
Status setLastDurableOptime_forTest(long long cfgVer, long long memberId, const OpTime& opTime);
/**
* Simple test wrappers that expose private methods.
*/
boost::optional<OpTime> calculateStableOpTime_forTest(const std::set<OpTime>& candidates,
const OpTime& commitPoint);
void cleanupStableOpTimeCandidates_forTest(std::set<OpTime>* candidates, OpTime stableOpTime);
std::set<OpTime> getStableOpTimeCandidates_forTest();
/**
* Non-blocking version of updateTerm.
* Returns event handle that we can use to wait for the operation to complete.
* When the operation is complete (waitForEvent() returns), 'updateResult' will be set
* to a status telling if the term increased or a stepdown was triggered.
*/
executor::TaskExecutor::EventHandle updateTerm_forTest(
long long term, TopologyCoordinator::UpdateTermResult* updateResult);
/**
* If called after _startElectSelfV1(), blocks until all asynchronous
* activities associated with election complete.
*/
void waitForElectionFinish_forTest();
/**
* If called after _startElectSelfV1(), blocks until all asynchronous
* activities associated with election dry run complete, including writing
* last vote and scheduling the real election.
*/
void waitForElectionDryRunFinish_forTest();
/**
* Waits until a stepdown command has begun. Callers should ensure that the stepdown attempt
* won't fully complete before this method is called, or this method may never return.
*/
void waitForStepDownAttempt_forTest();
private:
using CallbackFn = executor::TaskExecutor::CallbackFn;
using CallbackHandle = executor::TaskExecutor::CallbackHandle;
using EventHandle = executor::TaskExecutor::EventHandle;
using ScheduleFn = stdx::function<StatusWith<executor::TaskExecutor::CallbackHandle>(
const executor::TaskExecutor::CallbackFn& work)>;
class LoseElectionGuardV1;
class LoseElectionDryRunGuardV1;
/**
* Configuration states for a replica set node.
*
* Transition diagram:
*
* PreStart ------------------> ReplicationDisabled
* |
* |
* v
* StartingUp -------> Uninitialized <------> Initiating
* \ ^ |
* ------- | |
* | | |
* v v |
* Reconfig <---> Steady <----> HBReconfig |
* ^ /
* | /
* \ /
* -----------------------
*/
enum ConfigState {
kConfigPreStart,
kConfigStartingUp,
kConfigReplicationDisabled,
kConfigUninitialized,
kConfigSteady,
kConfigInitiating,
kConfigReconfiguring,
kConfigHBReconfiguring
};
/**
* Type describing actions to take after a change to the MemberState _memberState.
*/
enum PostMemberStateUpdateAction {
kActionNone,
kActionCloseAllConnections, // Also indicates that we should clear sharding state.
kActionFollowerModeStateChange,
kActionWinElection,
kActionStartSingleNodeElection
};
// Abstract struct that holds information about clients waiting for replication.
// Subclasses need to define how to notify them.
struct Waiter {
Waiter(OpTime _opTime, const WriteConcernOptions* _writeConcern);
virtual ~Waiter() = default;
BSONObj toBSON() const;
std::string toString() const;
// It is invalid to call notify_inlock() unless holding ReplicationCoordinatorImpl::_mutex.
virtual void notify_inlock() = 0;
const OpTime opTime;
const WriteConcernOptions* writeConcern = nullptr;
};
// When ThreadWaiter gets notified, it will signal the conditional variable.
//
// This is used when a thread wants to block inline until the opTime is reached with the given
// writeConcern.
struct ThreadWaiter : public Waiter {
ThreadWaiter(OpTime _opTime,
const WriteConcernOptions* _writeConcern,
stdx::condition_variable* _condVar);
void notify_inlock() override;
stdx::condition_variable* condVar = nullptr;
};
// When the waiter is notified, finishCallback will be called while holding replCoord _mutex
// since WaiterLists are protected by _mutex.
//
// This is used when we want to run a callback when the opTime is reached.
struct CallbackWaiter : public Waiter {
using FinishFunc = stdx::function<void()>;
CallbackWaiter(OpTime _opTime, FinishFunc _finishCallback);
void notify_inlock() override;
// The callback that will be called when this waiter is notified.
FinishFunc finishCallback = nullptr;
};
class WaiterGuard;
class WaiterList {
public:
using WaiterType = Waiter*;
// Adds waiter into the list.
void add_inlock(WaiterType waiter);
// Returns whether waiter is found and removed.
bool remove_inlock(WaiterType waiter);
// Signals and removes all waiters that satisfy the condition.
void signalAndRemoveIf_inlock(stdx::function<bool(WaiterType)> fun);
// Signals and removes all waiters from the list.
void signalAndRemoveAll_inlock();
private:
std::vector<WaiterType> _list;
};
typedef std::vector<executor::TaskExecutor::CallbackHandle> HeartbeatHandles;
// The state and logic of primary catchup.
//
// When start() is called, CatchupState will schedule the timeout callback. When we get
// responses of the latest heartbeats from all nodes, the target time (opTime of _waiter) is
// set.
// The primary exits catchup mode when any of the following happens.
// 1) My last applied optime reaches the target optime, if we've received a heartbeat from all
// nodes.
// 2) Catchup timeout expires.
// 3) Primary steps down.
// 4) The primary has to roll back to catch up.
// 5) The primary is too stale to catch up.
//
// On abort, the state resets the pointer to itself in ReplCoordImpl. In other words, the
// life cycle of the state object aligns with the conceptual state.
// In shutdown, the timeout callback will be canceled by the executor and the state is safe to
// destroy.
//
// Any function of the state must be called while holding _mutex.
class CatchupState {
public:
CatchupState(ReplicationCoordinatorImpl* repl) : _repl(repl) {}
// start() can only be called once.
void start_inlock();
// Reset the state itself to destruct the state.
void abort_inlock();
// Heartbeat calls this function to update the target optime.
void signalHeartbeatUpdate_inlock();
private:
ReplicationCoordinatorImpl* _repl; // Not owned.
// Callback handle used to cancel a scheduled catchup timeout callback.
executor::TaskExecutor::CallbackHandle _timeoutCbh;
// Handle to a Waiter that contains the current target optime to reach after which
// we can exit catchup mode.
std::unique_ptr<CallbackWaiter> _waiter;
};
void _resetMyLastOpTimes_inlock();
/**
* Returns the _writeConcernMajorityJournalDefault of our current _rsConfig.
*/
bool getWriteConcernMajorityShouldJournal_inlock() const;
/**
* Returns the OpTime of the current committed snapshot, if one exists.
*/
OpTime _getCurrentCommittedSnapshotOpTime_inlock() const;
/**
* Returns the OpTime of the current committed snapshot converted to LogicalTime.
*/
LogicalTime _getCurrentCommittedLogicalTime_inlock() const;
/**
* Verifies that ReadConcernArgs match node's readConcern.
*/
Status _validateReadConcern(OperationContext* opCtx, const ReadConcernArgs& readConcern);
/**
* Helper to update our saved config, cancel any pending heartbeats, and kick off sending
* new heartbeats based on the new config.
*
* Returns an action to be performed after unlocking _mutex, via
* _performPostMemberStateUpdateAction.
*/
PostMemberStateUpdateAction _setCurrentRSConfig_inlock(OperationContext* opCtx,
const ReplSetConfig& newConfig,
int myIndex);
/**
* Helper to wake waiters in _replicationWaiterList that are doneWaitingForReplication.
*/
void _wakeReadyWaiters_inlock();
/**
* Scheduled to cause the ReplicationCoordinator to reconsider any state that might
* need to change as a result of time passing - for instance becoming PRIMARY when a single
* node replica set member's stepDown period ends.
*/
void _handleTimePassing(const executor::TaskExecutor::CallbackArgs& cbData);
/**
* Helper method for _awaitReplication that takes an already locked unique_lock, but leaves
* operation timing to the caller.
*/
Status _awaitReplication_inlock(stdx::unique_lock<stdx::mutex>* lock,
OperationContext* opCtx,
const OpTime& opTime,
SnapshotName minSnapshot,
const WriteConcernOptions& writeConcern);
/**
* Returns true if the given writeConcern is satisfied up to "optime" or is unsatisfiable.
*
* If the writeConcern is 'majority', also waits for _currentCommittedSnapshot to be newer than
* minSnapshot.
*/
bool _doneWaitingForReplication_inlock(const OpTime& opTime,
SnapshotName minSnapshot,
const WriteConcernOptions& writeConcern);
Status _checkIfWriteConcernCanBeSatisfied_inlock(const WriteConcernOptions& writeConcern) const;
/**
* Wakes up threads in the process of handling a stepdown request based on whether the
* TopologyCoordinator now believes enough secondaries are caught up for the stepdown request to
* complete.
*/
void _signalStepDownWaiterIfReady_inlock();
bool _canAcceptWritesFor_inlock(const NamespaceString& ns);
OID _getMyRID_inlock() const;
int _getMyId_inlock() const;
OpTime _getMyLastAppliedOpTime_inlock() const;
OpTime _getMyLastDurableOpTime_inlock() const;
/**
* Helper method for updating our tracking of the last optime applied by a given node.
* This is only valid to call on replica sets.
* "configVersion" will be populated with our config version if it and the configVersion
* of "args" differ.
*
* The OldUpdatePositionArgs version provides support for the pre-3.2.4 format of
* UpdatePositionArgs.
*/
Status _setLastOptime_inlock(const OldUpdatePositionArgs::UpdateInfo& args,
long long* configVersion);
Status _setLastOptime_inlock(const UpdatePositionArgs::UpdateInfo& args,
long long* configVersion);
/**
* This function will report our position externally (like upstream) if necessary.
*
* Takes in a unique lock, that must already be locked, on _mutex.
*
* Lock will be released after this method finishes.
*/
void _reportUpstream_inlock(stdx::unique_lock<stdx::mutex> lock);
/**
* Helpers to set the last applied and durable OpTime.
*/
void _setMyLastAppliedOpTime_inlock(const OpTime& opTime, bool isRollbackAllowed);
void _setMyLastDurableOpTime_inlock(const OpTime& opTime, bool isRollbackAllowed);
/**
* Schedules a heartbeat to be sent to "target" at "when". "targetIndex" is the index
* into the replica set config members array that corresponds to the "target", or -1 if
* "target" is not in _rsConfig.
*/
void _scheduleHeartbeatToTarget_inlock(const HostAndPort& target, int targetIndex, Date_t when);
/**
* Processes each heartbeat response.
*
* Schedules additional heartbeats, triggers elections and step downs, etc.
*/
void _handleHeartbeatResponse(const executor::TaskExecutor::RemoteCommandCallbackArgs& cbData,
int targetIndex);
void _trackHeartbeatHandle_inlock(
const StatusWith<executor::TaskExecutor::CallbackHandle>& handle);
void _untrackHeartbeatHandle_inlock(const executor::TaskExecutor::CallbackHandle& handle);
/*
* Return a randomized offset amount that is scaled in proportion to the size of the
* _electionTimeoutPeriod. Used to add randomization to an election timeout.
*/
Milliseconds _getRandomizedElectionOffset_inlock();
/**
* Helper for _handleHeartbeatResponse.
*
* Updates the lastDurableOpTime and lastAppliedOpTime associated with the member at
* "memberIndex" in our config.
*/
void _updateOpTimesFromHeartbeat_inlock(int targetIndex,
const OpTime& durableOpTime,
const OpTime& appliedOpTime);
/**
* Starts a heartbeat for each member in the current config. Called while holding _mutex.
*/
void _startHeartbeats_inlock();
/**
* Cancels all heartbeats. Called while holding replCoord _mutex.
*/
void _cancelHeartbeats_inlock();
/**
* Cancels all heartbeats, then starts a heartbeat for each member in the current config.
* Called while holding replCoord _mutex.
*/
void _restartHeartbeats_inlock();
/**
* Asynchronously sends a heartbeat to "target". "targetIndex" is the index
* into the replica set config members array that corresponds to the "target", or -1 if
* we don't have a valid replica set config.
*
* Scheduled by _scheduleHeartbeatToTarget_inlock.
*/
void _doMemberHeartbeat(executor::TaskExecutor::CallbackArgs cbData,
const HostAndPort& target,
int targetIndex);
MemberState _getMemberState_inlock() const;
/**
* Starts loading the replication configuration from local storage, and if it is valid,
* schedules a callback (of _finishLoadLocalConfig) to set it as the current replica set
* config (sets _rsConfig and _thisMembersConfigIndex).
* Returns true if it finishes loading the local config, which most likely means there
* was no local config at all or it was invalid in some way, and false if there was a valid
* config detected but more work is needed to set it as the local config (which will be
* handled by the callback to _finishLoadLocalConfig).
*/
bool _startLoadLocalConfig(OperationContext* opCtx);
/**
* Callback that finishes the work started in _startLoadLocalConfig and sets _rsConfigState
* to kConfigSteady, so that we can begin processing heartbeats and reconfigs.
*/
void _finishLoadLocalConfig(const executor::TaskExecutor::CallbackArgs& cbData,
const ReplSetConfig& localConfig,
const StatusWith<OpTime>& lastOpTimeStatus,
const StatusWith<LastVote>& lastVoteStatus);
/**
* Start replicating data, and does an initial sync if needed first.
*/
void _startDataReplication(OperationContext* opCtx,
stdx::function<void()> startCompleted = nullptr);
/**
* Stops replicating data by stopping the applier, fetcher and such.
*/
void _stopDataReplication(OperationContext* opCtx);
/**
* Finishes the work of processReplSetInitiate() in the event of a successful quorum check.
*/
void _finishReplSetInitiate(OperationContext* opCtx,
const ReplSetConfig& newConfig,
int myIndex);
/**
* Finishes the work of processReplSetReconfig, in the event of
* a successful quorum check.
*/
void _finishReplSetReconfig(const executor::TaskExecutor::CallbackArgs& cbData,
const ReplSetConfig& newConfig,
bool isForceReconfig,
int myIndex,
const executor::TaskExecutor::EventHandle& finishedEvent);
/**
* Changes _rsConfigState to newState, and notify any waiters.
*/
void _setConfigState_inlock(ConfigState newState);
/**
* Updates the cached value, _memberState, to match _topCoord's reported
* member state, from getMemberState().
*
* Returns an enum indicating what action to take after releasing _mutex, if any.
* Call performPostMemberStateUpdateAction on the return value after releasing
* _mutex.
*
* Note: opCtx may be null as currently not all paths thread an OperationContext all the way
* down, but it must be non-null for any calls that change _canAcceptNonLocalWrites.
*/
PostMemberStateUpdateAction _updateMemberStateFromTopologyCoordinator_inlock(
OperationContext* opCtx);
/**
* Performs a post member-state update action. Do not call while holding _mutex.
*/
void _performPostMemberStateUpdateAction(PostMemberStateUpdateAction action);
/**
* Begins an attempt to elect this node.
* Called after an incoming heartbeat changes this node's view of the set such that it
* believes it can be elected PRIMARY.
* For proper concurrency, start methods must be called while holding _mutex.
*
* For old style elections the election path is:
* _startElectSelf_inlock()
* _onFreshnessCheckComplete()
* _onElectCmdRunnerComplete()
* For V1 (raft) style elections the election path is:
* _startElectSelfV1() or _startElectSelfV1_inlock()
* _onDryRunComplete()
* _writeLastVoteForMyElection()
* _startVoteRequester_inlock()
* _onVoteRequestComplete()
*/
void _startElectSelf_inlock();
void _startElectSelfV1_inlock(TopologyCoordinator::StartElectionReason reason);
void _startElectSelfV1(TopologyCoordinator::StartElectionReason reason);
/**
* Callback called when the FreshnessChecker has completed; checks the results and
* decides whether to continue election proceedings.
**/
void _onFreshnessCheckComplete();
/**
* Callback called when the ElectCmdRunner has completed; checks the results and
* decides whether to complete the election and change state to primary.
**/
void _onElectCmdRunnerComplete();
/**
* Callback called when the dryRun VoteRequester has completed; checks the results and
* decides whether to conduct a proper election.
* "originalTerm" was the term during which the dry run began, if the term has since
* changed, do not run for election.
*/
void _onDryRunComplete(long long originalTerm);
/**
* Writes the last vote in persistent storage after completing dry run successfully.
* This job will be scheduled to run in DB worker threads.
*/
void _writeLastVoteForMyElection(LastVote lastVote,
const executor::TaskExecutor::CallbackArgs& cbData);
/**
* Starts VoteRequester to run the real election when last vote write has completed.
*/
void _startVoteRequester_inlock(long long newTerm);
/**
* Callback called when the VoteRequester has completed; checks the results and
* decides whether to change state to primary and alert other nodes of our primary-ness.
* "originalTerm" was the term during which the election began, if the term has since
* changed, do not step up as primary.
*/
void _onVoteRequestComplete(long long originalTerm);
/**
* Callback called after a random delay, to prevent repeated election ties.
*/
void _recoverFromElectionTie(const executor::TaskExecutor::CallbackArgs& cbData);
/**
* Removes 'host' from the sync source blacklist. If 'host' isn't found, it's simply
* ignored and no error is thrown.
*
* Must be scheduled as a callback.
*/
void _unblacklistSyncSource(const executor::TaskExecutor::CallbackArgs& cbData,
const HostAndPort& host);
/**
* Schedules a request that the given host step down; logs any errors.
*/
void _requestRemotePrimaryStepdown(const HostAndPort& target);
/**
* Schedules stepdown to run with the global exclusive lock.
*/
executor::TaskExecutor::EventHandle _stepDownStart();
/**
* Completes a step-down of the current node. Must be run with a global
* shared or global exclusive lock.
* Signals 'finishedEvent' on successful completion.
*/
void _stepDownFinish(const executor::TaskExecutor::CallbackArgs& cbData,
const executor::TaskExecutor::EventHandle& finishedEvent);
/**
* Schedules a replica set config change.
*/
void _scheduleHeartbeatReconfig_inlock(const ReplSetConfig& newConfig);
/**
* Method to write a configuration transmitted via heartbeat message to stable storage.
*/
void _heartbeatReconfigStore(const executor::TaskExecutor::CallbackArgs& cbd,
const ReplSetConfig& newConfig);
/**
* Conclusion actions of a heartbeat-triggered reconfiguration.
*/
void _heartbeatReconfigFinish(const executor::TaskExecutor::CallbackArgs& cbData,
const ReplSetConfig& newConfig,
StatusWith<int> myIndex);
/**
* Utility method that schedules or performs actions specified by a HeartbeatResponseAction
* returned by a TopologyCoordinator::processHeartbeatResponse(V1) call with the given
* value of "responseStatus".
*
* Requires "lock" to own _mutex, and returns the same unique_lock.
*/
stdx::unique_lock<stdx::mutex> _handleHeartbeatResponseAction_inlock(
const HeartbeatResponseAction& action,
const StatusWith<ReplSetHeartbeatResponse>& responseStatus,
stdx::unique_lock<stdx::mutex> lock);
/**
* Updates the last committed OpTime to be "committedOpTime" if it is more recent than the
* current last committed OpTime.
*/
void _advanceCommitPoint_inlock(const OpTime& committedOpTime);
/**
* Scan the memberData and determine the highest last applied or last
* durable optime present on a majority of servers; set _lastCommittedOpTime to this
* new entry. Wake any threads waiting for replication that now have their
* write concern satisfied.
*
* Whether the last applied or last durable op time is used depends on whether
* the config getWriteConcernMajorityShouldJournal is set.
*/
void _updateLastCommittedOpTime_inlock();
/**
* Callback that attempts to set the current term in topology coordinator and
* relinquishes primary if the term actually changes and we are primary.
* *updateTermResult will be the result of the update term attempt.
* Returns the finish event if it does not finish in this function, for example,
* due to stepdown, otherwise the returned EventHandle is invalid.
*/
EventHandle _updateTerm_inlock(
long long term, TopologyCoordinator::UpdateTermResult* updateTermResult = nullptr);
/**
* Callback that processes the ReplSetMetadata returned from a command run against another
* replica set member and so long as the config version in the metadata matches the replica set
* config version this node currently has, updates the current term.
*
* This does NOT update this node's notion of the commit point.
*
* Returns the finish event which is invalid if the process has already finished.
*/
EventHandle _processReplSetMetadata_inlock(const rpc::ReplSetMetadata& replMetadata);
/**
* Prepares a metadata object for ReplSetMetadata.
*/
void _prepareReplSetMetadata_inlock(const OpTime& lastOpTimeFromClient,
BSONObjBuilder* builder) const;
/**
* Prepares a metadata object for OplogQueryMetadata.
*/
void _prepareOplogQueryMetadata_inlock(int rbid, BSONObjBuilder* builder) const;
/**
* Blesses a snapshot to be used for new committed reads.
*/
void _updateCommittedSnapshot_inlock(SnapshotInfo newCommittedSnapshot);
/**
* Calculates the 'stable' replication optime given a set of optime candidates and the