/
topology_coordinator.cpp
3405 lines (2993 loc) · 138 KB
/
topology_coordinator.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 MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kReplication
#define LOGV2_FOR_ELECTION(ID, DLEVEL, MESSAGE, ...) \
LOGV2_DEBUG_OPTIONS( \
ID, DLEVEL, {logv2::LogComponent::kReplicationElection}, MESSAGE, ##__VA_ARGS__)
#define LOGV2_FOR_HEARTBEATS(ID, DLEVEL, MESSAGE, ...) \
LOGV2_DEBUG_OPTIONS( \
ID, DLEVEL, {logv2::LogComponent::kReplicationHeartbeats}, MESSAGE, ##__VA_ARGS__)
#include "mongo/platform/basic.h"
#include "mongo/db/repl/topology_coordinator.h"
#include "mongo/db/repl/topology_coordinator_gen.h"
#include <fmt/format.h>
#include <fmt/ostream.h>
#include <limits>
#include <string>
#include "mongo/bson/simple_bsonobj_comparator.h"
#include "mongo/db/audit.h"
#include "mongo/db/catalog/commit_quorum_options.h"
#include "mongo/db/client.h"
#include "mongo/db/mongod_options.h"
#include "mongo/db/operation_context.h"
#include "mongo/db/repl/heartbeat_response_action.h"
#include "mongo/db/repl/isself.h"
#include "mongo/db/repl/member_data.h"
#include "mongo/db/repl/repl_server_parameters_gen.h"
#include "mongo/logv2/log.h"
#include "mongo/rpc/metadata/oplog_query_metadata.h"
#include "mongo/rpc/metadata/repl_set_metadata.h"
#include "mongo/util/assert_util.h"
#include "mongo/util/fail_point.h"
#include "mongo/util/hex.h"
#include "mongo/util/scopeguard.h"
#include "mongo/util/str.h"
namespace mongo {
namespace repl {
MONGO_FAIL_POINT_DEFINE(forceSyncSourceCandidate);
MONGO_FAIL_POINT_DEFINE(voteNoInElection);
MONGO_FAIL_POINT_DEFINE(voteYesInDryRunButNoInRealElection);
// If this fail point is enabled, TopologyCoordinator::shouldChangeSyncSource() will ignore
// the option TopologyCoordinator::Options::maxSyncSourceLagSecs. The sync source will not be
// re-evaluated if it lags behind another node by more than 'maxSyncSourceLagSecs' seconds.
MONGO_FAIL_POINT_DEFINE(disableMaxSyncSourceLagSecs);
constexpr Milliseconds TopologyCoordinator::PingStats::UninitializedPingTime;
using namespace fmt::literals;
std::string TopologyCoordinator::roleToString(TopologyCoordinator::Role role) {
switch (role) {
case TopologyCoordinator::Role::kLeader:
return "leader";
case TopologyCoordinator::Role::kFollower:
return "follower";
case TopologyCoordinator::Role::kCandidate:
return "candidate";
}
MONGO_UNREACHABLE;
}
TopologyCoordinator::~TopologyCoordinator() {}
std::ostream& operator<<(std::ostream& os, TopologyCoordinator::Role role) {
return os << TopologyCoordinator::roleToString(role);
}
std::ostream& operator<<(std::ostream& os,
TopologyCoordinator::PrepareFreezeResponseResult result) {
switch (result) {
case TopologyCoordinator::PrepareFreezeResponseResult::kNoAction:
return os << "no action";
case TopologyCoordinator::PrepareFreezeResponseResult::kSingleNodeSelfElect:
return os << "single node self elect";
}
MONGO_UNREACHABLE;
}
namespace {
template <typename T>
int indexOfIterator(const std::vector<T>& vec, typename std::vector<T>::const_iterator& it) {
return static_cast<int>(it - vec.begin());
}
/**
* Returns true if the only up heartbeats are auth errors.
*/
bool _hasOnlyAuthErrorUpHeartbeats(const std::vector<MemberData>& hbdata, const int selfIndex) {
bool foundAuthError = false;
for (std::vector<MemberData>::const_iterator it = hbdata.begin(); it != hbdata.end(); ++it) {
if (indexOfIterator(hbdata, it) == selfIndex) {
continue;
}
if (it->up()) {
return false;
}
if (it->hasAuthIssue()) {
foundAuthError = true;
}
}
return foundAuthError;
}
void appendOpTime(BSONObjBuilder* bob, const char* elemName, const OpTime& opTime) {
opTime.append(bob, elemName);
}
} // namespace
void TopologyCoordinator::PingStats::start(Date_t now) {
_lastHeartbeatStartDate = now;
_numFailuresSinceLastStart = 0;
_state = HeartbeatState::TRYING;
}
void TopologyCoordinator::PingStats::hit(Milliseconds millis) {
_state = HeartbeatState::SUCCEEDED;
++hitCount;
averagePingTimeMs = averagePingTimeMs == UninitializedPingTime
? millis
: Milliseconds((averagePingTimeMs * 4 + millis) / 5);
}
void TopologyCoordinator::PingStats::set_forTest(Milliseconds millis) {
_state = HeartbeatState::SUCCEEDED;
averagePingTimeMs = millis;
}
void TopologyCoordinator::PingStats::miss() {
++_numFailuresSinceLastStart;
// Transition to 'FAILED' state if this was our last retry.
if (_numFailuresSinceLastStart > kMaxHeartbeatRetries) {
_state = PingStats::HeartbeatState::FAILED;
}
}
bool TopologyCoordinator::RecentSyncSourceChanges::changedTooOftenRecently(Date_t now) {
size_t maxSize = maxNumSyncSourceChangesPerHour.load();
// Return false if we have fewer than maxNumSyncSourceChangesPerHour entries.
if (_recentChanges.empty() || _recentChanges.size() < maxSize) {
return false;
}
// Remove additional entries in case maxNumSyncSourceChangesPerHour was changed.
while (_recentChanges.size() > maxSize) {
_recentChanges.pop();
}
// Return whether all entries in the queue happened within the last hour by checking the oldest
// entry.
auto hourBefore = now - Hours(1);
return _recentChanges.front() > hourBefore;
}
void TopologyCoordinator::RecentSyncSourceChanges::addNewEntry(Date_t now) {
// Remove additional entries if the queue already has maxNumSyncSourceChangerPerHour entries.
while (_recentChanges.size() >= static_cast<size_t>(maxNumSyncSourceChangesPerHour.load())) {
_recentChanges.pop();
}
_recentChanges.push(now);
return;
}
std::queue<Date_t> TopologyCoordinator::RecentSyncSourceChanges::getChanges_forTest() {
return _recentChanges;
}
TopologyCoordinator::TopologyCoordinator(Options options)
: _role(Role::kFollower),
_topologyVersion(instanceId, 0),
_term(OpTime::kUninitializedTerm),
_currentPrimaryIndex(-1),
_forceSyncSourceIndex(-1),
_syncSourceCurrentlyForced(false),
_options(std::move(options)),
_selfIndex(-1),
_maintenanceModeCalls(0),
_followerMode(MemberState::RS_STARTUP2) {
invariant(getMemberState() == MemberState::RS_STARTUP);
// Need an entry for self in the memberHearbeatData.
_memberData.emplace_back();
_memberData.back().setIsSelf(true);
}
TopologyCoordinator::Role TopologyCoordinator::getRole() const {
return _role;
}
TopologyVersion TopologyCoordinator::getTopologyVersion() const {
return _topologyVersion;
}
void TopologyCoordinator::setForceSyncSourceIndex(int index) {
invariant(_forceSyncSourceIndex < _rsConfig.getNumMembers());
_forceSyncSourceIndex = index;
}
HostAndPort TopologyCoordinator::getSyncSourceAddress() const {
return _syncSource;
}
void TopologyCoordinator::_clearSyncSource() {
_syncSource = HostAndPort();
_syncSourceCurrentlyForced = false;
}
void TopologyCoordinator::_setSyncSource(HostAndPort newSyncSource, Date_t now, bool forced) {
_syncSource = newSyncSource;
_syncSourceCurrentlyForced = forced;
// If we chose another node rather than clearing the sync source, update the recent sync source
// changes.
if (!_syncSource.empty()) {
_recentSyncSourceChanges.addNewEntry(now);
}
}
HostAndPort TopologyCoordinator::chooseNewSyncSource(Date_t now,
const OpTime& lastOpTimeFetched,
ReadPreference readPreference) {
// Check to make sure we can choose a sync source, and choose a forced one if set.
auto maybeSyncSource = _chooseSyncSourceInitialStep(now);
if (maybeSyncSource) {
bool forced = !maybeSyncSource->empty();
_setSyncSource(*maybeSyncSource, now, forced);
return _syncSource;
}
// If we are only allowed to sync from the primary, use it as the sync source if possible.
if (readPreference == ReadPreference::PrimaryOnly) {
_setSyncSource(_choosePrimaryAsSyncSource(now, lastOpTimeFetched), now);
if (_syncSource.empty()) {
if (readPreference == ReadPreference::PrimaryOnly) {
LOGV2_DEBUG(3873104,
1,
"Cannot select a sync source because the primary is not a valid sync "
"source and the sync source read preference is 'primary'.");
} else {
LOGV2_DEBUG(3873105,
1,
"Cannot select a sync source because the primary is not a valid sync "
"source and chaining is disabled.");
}
}
return _syncSource;
} else if (readPreference == ReadPreference::PrimaryPreferred) {
// If we prefer the primary, try it first.
_setSyncSource(_choosePrimaryAsSyncSource(now, lastOpTimeFetched), now);
if (!_syncSource.empty()) {
return _syncSource;
}
}
_setSyncSource(_chooseNearbySyncSource(now, lastOpTimeFetched, readPreference), now);
return _syncSource;
}
HostAndPort TopologyCoordinator::_chooseNearbySyncSource(Date_t now,
const OpTime& lastOpTimeFetched,
ReadPreference readPreference) {
// We should have handled PrimaryOnly before calling this.
invariant(readPreference != ReadPreference::PrimaryOnly);
// find the member with the lowest ping time that is ahead of me
int closestIndex = -1;
// Make two attempts, with less restrictive rules the second time.
//
// During the first attempt, we ignore those nodes that have a larger slave
// delay, hidden nodes or non-voting, and nodes that are excessively behind.
//
// For the second attempt include those nodes, in case those are the only ones we can reach.
//
// This loop attempts to set 'closestIndex', to select a viable candidate.
for (int attempts = 0; attempts < 2; ++attempts) {
for (size_t candidateIndex = 0; candidateIndex < _memberData.size(); candidateIndex++) {
if (!_isEligibleSyncSource(candidateIndex,
now,
lastOpTimeFetched,
readPreference,
attempts == 0 /* firstAttempt */)) {
// Node is not a viable sync source candidate.
continue;
}
// Set 'closestIndex' if this node is the first viable candidate we have encountered.
if (closestIndex == -1) {
closestIndex = candidateIndex;
continue;
}
const auto syncSourceCandidate = _rsConfig.getMemberAt(candidateIndex).getHostAndPort();
const auto closestNode = _rsConfig.getMemberAt(closestIndex).getHostAndPort();
// Do not update 'closestIndex' if the candidate is not the closest node we've seen.
if (_getPing(syncSourceCandidate) > _getPing(closestNode)) {
LOGV2_DEBUG(3873114,
2,
"Cannot select sync source with higher latency than the best "
"candidate",
"syncSourceCandidate"_attr = syncSourceCandidate);
continue;
}
closestIndex = candidateIndex;
}
if (closestIndex != -1)
break; // no need for second attempt
}
if (closestIndex == -1) {
// Did not find any members to sync from
// Only log when we had a valid sync source before
static constexpr char message[] = "Could not find member to sync from";
if (!_syncSource.empty()) {
LOGV2(21798, message);
}
setMyHeartbeatMessage(now, message);
return HostAndPort();
}
auto syncSource = _rsConfig.getMemberAt(closestIndex).getHostAndPort();
LOGV2(21799, "Sync source candidate chosen", "syncSource"_attr = syncSource);
std::string msg(str::stream() << "syncing from: " << syncSource.toString(), 0);
setMyHeartbeatMessage(now, msg);
return syncSource;
}
const OpTime TopologyCoordinator::_getOldestSyncOpTime() const {
OpTime oldestSyncOpTime = OpTime();
// Find primary's oplog time. We will reject sync candidates that are more than
// _options.maxSyncSourceLagSecs seconds behind this optime.
if (_currentPrimaryIndex != -1) {
OpTime primaryOpTime = _memberData.at(_currentPrimaryIndex).getHeartbeatAppliedOpTime();
// Check if primaryOpTime is still close to 0 because we haven't received
// our first heartbeat from a new primary yet.
auto maxLag =
static_cast<unsigned int>(durationCount<Seconds>(_options.maxSyncSourceLagSecs));
if (primaryOpTime.getSecs() >= maxLag) {
oldestSyncOpTime =
OpTime(Timestamp(primaryOpTime.getSecs() - maxLag, 0), primaryOpTime.getTerm());
}
}
return oldestSyncOpTime;
}
bool TopologyCoordinator::_isEligibleSyncSource(int candidateIndex,
Date_t now,
const OpTime& lastOpTimeFetched,
ReadPreference readPreference,
const bool firstAttempt) const {
// Don't consider ourselves.
if (candidateIndex == _selfIndex) {
return false;
}
const MemberConfig& memberConfig(_rsConfig.getMemberAt(candidateIndex));
const auto syncSourceCandidate = memberConfig.getHostAndPort();
const auto memberData = _memberData[candidateIndex];
// Candidate must be up to be considered.
if (!memberData.up()) {
LOGV2_DEBUG(3873106,
2,
"Cannot select sync source because it is not up",
"syncSourceCandidate"_attr = syncSourceCandidate);
return false;
}
// Candidate must be PRIMARY or SECONDARY state to be considered.
if (!memberData.getState().readable()) {
LOGV2_DEBUG(3873107,
2,
"Cannot select sync source because it is not readable",
"syncSourceCandidate"_attr = syncSourceCandidate);
return false;
}
// Disallow the primary for first or all attempts depending on the readPreference.
if (readPreference == ReadPreference::SecondaryOnly ||
(readPreference == ReadPreference::SecondaryPreferred && firstAttempt)) {
if (memberData.getState().primary()) {
LOGV2_DEBUG(3873101,
2,
"Cannot select sync source because it is a primary and we are "
"looking for a secondary",
"syncSourceCandidate"_attr = syncSourceCandidate);
return false;
}
}
// On the first attempt, we skip candidates that do not match these criteria.
if (firstAttempt) {
// Candidate must be a voter if we are a voter.
if (_selfConfig().isVoter() && !memberConfig.isVoter()) {
LOGV2_DEBUG(3873108,
2,
"Cannot select sync source because we are a voter and it is not",
"syncSourceCandidate"_attr = syncSourceCandidate);
return false;
}
// Candidates must not be hidden.
if (memberConfig.isHidden()) {
LOGV2_DEBUG(3873109,
2,
"Cannot select sync source because it is hidden",
"syncSourceCandidate"_attr = syncSourceCandidate);
return false;
}
// Candidates cannot be excessively behind.
const auto oldestSyncOpTime = _getOldestSyncOpTime();
if (memberData.getHeartbeatAppliedOpTime() < oldestSyncOpTime) {
LOGV2_DEBUG(3873110,
2,
"Cannot select sync source because it is too far behind",
"syncSourceCandidate"_attr = syncSourceCandidate,
"syncSourceCandidateOpTime"_attr = memberData.getHeartbeatAppliedOpTime(),
"oldestAcceptableOpTime"_attr = oldestSyncOpTime);
return false;
}
// Candidate must not have a configured delay larger than ours.
if (_selfConfig().getSlaveDelay() < memberConfig.getSlaveDelay()) {
LOGV2_DEBUG(3873111,
2,
"Cannot select sync source with larger slaveDelay than ours",
"syncSourceCandidate"_attr = syncSourceCandidate,
"syncSourceCandidateSlaveDelay"_attr = memberConfig.getSlaveDelay(),
"slaveDelay"_attr = _selfConfig().getSlaveDelay());
return false;
}
}
// Candidate must build indexes if we build indexes, to be considered.
if (_selfConfig().shouldBuildIndexes()) {
if (!memberConfig.shouldBuildIndexes()) {
LOGV2_DEBUG(3873112,
2,
"Cannot select sync source which does not build indexes when we do",
"syncSourceCandidate"_attr = syncSourceCandidate);
return false;
}
}
// Only select a candidate that is ahead of me.
if (memberData.getHeartbeatAppliedOpTime() <= lastOpTimeFetched) {
LOGV2_DEBUG(3873113,
1,
"Cannot select sync source which is not ahead of me",
"syncSourceCandidate"_attr = syncSourceCandidate,
"syncSourceCandidateLastAppliedOpTime"_attr =
memberData.getHeartbeatAppliedOpTime().toBSON(),
"lastOpTimeFetched"_attr = lastOpTimeFetched.toBSON());
return false;
}
// Candidate cannot be blacklisted.
if (_memberIsBlacklisted(memberConfig, now)) {
LOGV2_DEBUG(3873115,
1,
"Cannot select sync source which is blacklisted",
"syncSourceCandidate"_attr = syncSourceCandidate);
return false;
}
// This candidate has passed all tests.
return true;
}
boost::optional<HostAndPort> TopologyCoordinator::_chooseSyncSourceInitialStep(Date_t now) {
// If we are not a member of the current replica set configuration, no sync source is valid.
if (_selfIndex == -1) {
LOGV2_DEBUG(
21778, 1, "Cannot sync from any members because we are not in the replica set config");
return HostAndPort();
}
if (auto sfp = forceSyncSourceCandidate.scoped(); MONGO_unlikely(sfp.isActive())) {
const auto& data = sfp.getData();
const auto hostAndPortElem = data["hostAndPort"];
if (!hostAndPortElem) {
LOGV2_FATAL(50835,
"'forceSyncSoureCandidate' parameter set with invalid host and port: "
"{failpointData}",
"'forceSyncSoureCandidate' parameter set with invalid host and port",
"failpointData"_attr = data);
}
const auto hostAndPort = HostAndPort(hostAndPortElem.checkAndGetStringData());
const int syncSourceIndex = _rsConfig.findMemberIndexByHostAndPort(hostAndPort);
if (syncSourceIndex < 0) {
LOGV2(3873118,
"'forceSyncSourceCandidate' failed due to host and port not in "
"replica set config.",
"syncSourceCandidate"_attr = hostAndPort.toString());
fassertFailed(50836);
}
if (_memberIsBlacklisted(_rsConfig.getMemberAt(syncSourceIndex), now)) {
LOGV2(3873119,
"Cannot select a sync source because forced candidate is blacklisted.",
"syncSourceCandidate"_attr = hostAndPort.toString());
return HostAndPort();
}
auto syncSource = _rsConfig.getMemberAt(syncSourceIndex).getHostAndPort();
LOGV2(21781,
"Choosing sync source candidate due to 'forceSyncSourceCandidate' parameter",
"syncSource"_attr = syncSource);
std::string msg(str::stream() << "syncing from: " << syncSource.toString()
<< " by 'forceSyncSourceCandidate' parameter");
setMyHeartbeatMessage(now, msg);
return syncSource;
}
// if we have a target we've requested to sync from, use it
if (_forceSyncSourceIndex != -1) {
invariant(_forceSyncSourceIndex < _rsConfig.getNumMembers());
auto syncSource = _rsConfig.getMemberAt(_forceSyncSourceIndex).getHostAndPort();
_forceSyncSourceIndex = -1;
LOGV2(21782, "Choosing sync source candidate by request", "syncSource"_attr = syncSource);
std::string msg(str::stream()
<< "syncing from: " << syncSource.toString() << " by request");
setMyHeartbeatMessage(now, msg);
return syncSource;
}
// wait for 2N pings (not counting ourselves) before choosing a sync target
int numPingsNeeded = (_memberData.size() - 1) * 2 - pingsInConfig;
if (numPingsNeeded > 0) {
static Occasionally sampler;
if (sampler.tick()) {
LOGV2(21783,
"waiting for {pingsNeeded} pings from other members before syncing",
"Waiting for pings from other members before syncing",
"pingsNeeded"_attr = numPingsNeeded);
}
return HostAndPort();
}
return boost::none;
}
HostAndPort TopologyCoordinator::_choosePrimaryAsSyncSource(Date_t now,
const OpTime& lastOpTimeFetched) {
if (_currentPrimaryIndex == -1) {
LOGV2_DEBUG(21784,
1,
"Cannot select the primary as sync source because"
" the primary is unknown/down.");
return HostAndPort();
} else if (_memberIsBlacklisted(*getCurrentPrimaryMember(), now)) {
LOGV2_DEBUG(
3873116,
1,
"Cannot select the primary as sync source because the primary member is blacklisted",
"primary"_attr = getCurrentPrimaryMember()->getHostAndPort());
return HostAndPort();
} else if (_currentPrimaryIndex == _selfIndex) {
LOGV2_DEBUG(
21786, 1, "Cannot select the primary as sync source because this node is primary.");
return HostAndPort();
} else if (_memberData.at(_currentPrimaryIndex).getLastAppliedOpTime() < lastOpTimeFetched) {
LOGV2_DEBUG(4615639,
1,
"Cannot select the primary as sync source because the primary "
"is behind this node.",
"primary"_attr = getCurrentPrimaryMember()->getHostAndPort(),
"primaryOpTime"_attr =
_memberData.at(_currentPrimaryIndex).getLastAppliedOpTime(),
"lastFetchedOpTime"_attr = lastOpTimeFetched);
return HostAndPort();
} else {
auto syncSource = getCurrentPrimaryMember()->getHostAndPort();
LOGV2(3873117, "Choosing primary as sync source", "primary"_attr = syncSource);
std::string msg(str::stream() << "syncing from primary: " << syncSource.toString());
setMyHeartbeatMessage(now, msg);
return syncSource;
}
}
bool TopologyCoordinator::_memberIsBlacklisted(const MemberConfig& memberConfig, Date_t now) const {
std::map<HostAndPort, Date_t>::const_iterator blacklisted =
_syncSourceBlacklist.find(memberConfig.getHostAndPort());
if (blacklisted != _syncSourceBlacklist.end()) {
if (blacklisted->second > now) {
return true;
}
}
return false;
}
void TopologyCoordinator::blacklistSyncSource(const HostAndPort& host, Date_t until) {
LOGV2_DEBUG(21800,
2,
"blacklisting {syncSource} until {until}",
"Blacklisting sync source",
"syncSource"_attr = host,
"until"_attr = until.toString());
_syncSourceBlacklist[host] = until;
}
void TopologyCoordinator::unblacklistSyncSource(const HostAndPort& host, Date_t now) {
std::map<HostAndPort, Date_t>::iterator hostItr = _syncSourceBlacklist.find(host);
if (hostItr != _syncSourceBlacklist.end() && now >= hostItr->second) {
LOGV2_DEBUG(21801,
2,
"unblacklisting {syncSource}",
"Unblacklisting sync source",
"syncSource"_attr = host);
_syncSourceBlacklist.erase(hostItr);
}
}
void TopologyCoordinator::clearSyncSourceBlacklist() {
_syncSourceBlacklist.clear();
}
void TopologyCoordinator::prepareSyncFromResponse(const HostAndPort& target,
BSONObjBuilder* response,
Status* result) {
response->append("syncFromRequested", target.toString());
if (_selfIndex == -1) {
*result = Status(ErrorCodes::NotSecondary, "Removed and uninitialized nodes do not sync");
return;
}
const MemberConfig& selfConfig = _selfConfig();
if (selfConfig.isArbiter()) {
*result = Status(ErrorCodes::NotSecondary, "arbiters don't sync");
return;
}
if (_selfIndex == _currentPrimaryIndex) {
*result = Status(ErrorCodes::NotSecondary, "primaries don't sync");
return;
}
ReplSetConfig::MemberIterator targetConfig = _rsConfig.membersEnd();
int targetIndex = 0;
for (ReplSetConfig::MemberIterator it = _rsConfig.membersBegin(); it != _rsConfig.membersEnd();
++it) {
if (it->getHostAndPort() == target) {
targetConfig = it;
break;
}
++targetIndex;
}
if (targetConfig == _rsConfig.membersEnd()) {
*result = Status(ErrorCodes::NodeNotFound,
str::stream() << "Could not find member \"" << target.toString()
<< "\" in replica set");
return;
}
if (targetIndex == _selfIndex) {
*result = Status(ErrorCodes::InvalidOptions, "I cannot sync from myself");
return;
}
if (targetConfig->isArbiter()) {
*result = Status(ErrorCodes::InvalidOptions,
str::stream() << "Cannot sync from \"" << target.toString()
<< "\" because it is an arbiter");
return;
}
if (!targetConfig->shouldBuildIndexes() && selfConfig.shouldBuildIndexes()) {
*result = Status(ErrorCodes::InvalidOptions,
str::stream() << "Cannot sync from \"" << target.toString()
<< "\" because it does not build indexes");
return;
}
if (selfConfig.isVoter() && !targetConfig->isVoter()) {
*result = Status(ErrorCodes::InvalidOptions,
str::stream() << "Cannot sync from \"" << target.toString()
<< "\" because it is not a voter");
return;
}
const MemberData& hbdata = _memberData.at(targetIndex);
if (hbdata.hasAuthIssue()) {
*result =
Status(ErrorCodes::Unauthorized,
str::stream() << "not authorized to communicate with " << target.toString());
return;
}
if (hbdata.getHealth() == 0) {
*result =
Status(ErrorCodes::HostUnreachable,
str::stream() << "I cannot reach the requested member: " << target.toString());
return;
}
const OpTime lastOpApplied = getMyLastAppliedOpTime();
if (hbdata.getHeartbeatAppliedOpTime().getSecs() + 10 < lastOpApplied.getSecs()) {
LOGV2_WARNING(
21837,
"attempting to sync from {syncSource}, but its latest opTime is "
"{syncSourceHeartbeatAppliedOpTime} and ours is "
"{lastOpApplied} so this may not work",
"Attempting to sync from sync source, but it is more than 10 seconds behind us",
"syncSource"_attr = target,
"syncSourceHeartbeatAppliedOpTime"_attr = hbdata.getHeartbeatAppliedOpTime().getSecs(),
"lastOpApplied"_attr = lastOpApplied.getSecs());
response->append("warning",
str::stream() << "requested member \"" << target.toString()
<< "\" is more than 10 seconds behind us");
// not returning bad Status, just warning
}
HostAndPort prevSyncSource = getSyncSourceAddress();
if (!prevSyncSource.empty()) {
response->append("prevSyncTarget", prevSyncSource.toString());
}
setForceSyncSourceIndex(targetIndex);
*result = Status::OK();
}
// produce a reply to a heartbeat
Status TopologyCoordinator::prepareHeartbeatResponseV1(Date_t now,
const ReplSetHeartbeatArgsV1& args,
StringData ourSetName,
ReplSetHeartbeatResponse* response) {
// Verify that replica set names match
const std::string rshb = args.getSetName();
if (ourSetName != rshb) {
LOGV2(21802,
"replSet set names do not match, ours: {ourSetName}; remote node's: "
"{remoteNodeSetName}",
"replSet set names do not match",
"ourSetName"_attr = ourSetName,
"remoteNodeSetName"_attr = rshb);
return Status(ErrorCodes::InconsistentReplicaSetNames,
str::stream() << "Our set name of " << ourSetName << " does not match name "
<< rshb << " reported by remote node");
}
const MemberState myState = getMemberState();
if (_selfIndex == -1) {
if (myState.removed()) {
return Status(ErrorCodes::InvalidReplicaSetConfig,
"Our replica set configuration is invalid or does not include us");
}
} else {
if (args.getSenderId() == _selfConfig().getId().getData()) {
return Status(ErrorCodes::BadValue,
str::stream() << "Received heartbeat from member with the same "
"member ID as ourself: "
<< args.getSenderId());
}
}
response->setSetName(ourSetName);
response->setState(myState.s);
if (myState.primary()) {
response->setElectionTime(_electionTime);
}
OpTimeAndWallTime lastOpApplied;
OpTimeAndWallTime lastOpDurable;
// We include null times for lastApplied and lastDurable if we are in STARTUP_2, as we do not
// want to report replication progress and be part of write majorities while in initial sync.
if (!myState.startup2()) {
lastOpApplied = getMyLastAppliedOpTimeAndWallTime();
lastOpDurable = getMyLastDurableOpTimeAndWallTime();
}
response->setAppliedOpTimeAndWallTime(lastOpApplied);
response->setDurableOpTimeAndWallTime(lastOpDurable);
if (_currentPrimaryIndex != -1) {
response->setPrimaryId(_rsConfig.getMemberAt(_currentPrimaryIndex).getId().getData());
}
response->setTerm(_term);
if (!_syncSource.empty()) {
response->setSyncingTo(_syncSource);
}
if (!_rsConfig.isInitialized()) {
response->setConfigVersion(-2);
return Status::OK();
}
const long long v = _rsConfig.getConfigVersion();
const long long t = _rsConfig.getConfigTerm();
response->setConfigVersion(v);
response->setConfigTerm(t);
// Deliver new config if caller's config is older than ours
if (_rsConfig.getConfigVersionAndTerm() > args.getConfigVersionAndTerm()) {
response->setConfig(_rsConfig);
}
// Resolve the caller's id in our Member list
int from = -1;
if (v == args.getConfigVersion() && args.getSenderId() != -1) {
from = _getMemberIndex(args.getSenderId());
}
if (from == -1) {
return Status::OK();
}
invariant(from != _selfIndex);
auto& fromNodeData = _memberData.at(from);
// note that we got a heartbeat from this node
fromNodeData.setLastHeartbeatRecv(now);
// Update liveness for sending node.
fromNodeData.updateLiveness(now);
return Status::OK();
}
int TopologyCoordinator::_getMemberIndex(int id) const {
int index = 0;
for (ReplSetConfig::MemberIterator it = _rsConfig.membersBegin(); it != _rsConfig.membersEnd();
++it, ++index) {
if (it->getId() == MemberId(id)) {
return index;
}
}
return -1;
}
std::pair<ReplSetHeartbeatArgsV1, Milliseconds> TopologyCoordinator::prepareHeartbeatRequestV1(
Date_t now, StringData ourSetName, const HostAndPort& target) {
PingStats& hbStats = _pings[target];
Milliseconds alreadyElapsed(now.asInt64() - hbStats.getLastHeartbeatStartDate().asInt64());
if ((!_rsConfig.isInitialized()) || !hbStats.trying() ||
(alreadyElapsed >= _rsConfig.getHeartbeatTimeoutPeriodMillis())) {
// This is either the first request ever for "target", or the heartbeat timeout has
// passed, so we're starting a "new" heartbeat.
hbStats.start(now);
alreadyElapsed = Milliseconds(0);
}
ReplSetHeartbeatArgsV1 hbArgs;
if (_rsConfig.isInitialized()) {
hbArgs.setSetName(_rsConfig.getReplSetName());
hbArgs.setConfigVersion(_rsConfig.getConfigVersion());
if (_rsConfig.getConfigTerm() != OpTime::kUninitializedTerm) {
hbArgs.setConfigTerm(_rsConfig.getConfigTerm());
}
if (_currentPrimaryIndex >= 0) {
// Send primary member id if one exists.
hbArgs.setPrimaryId(_memberData.at(_currentPrimaryIndex).getMemberId().getData());
}
if (_selfIndex >= 0) {
const MemberConfig& me = _selfConfig();
hbArgs.setSenderId(me.getId().getData());
hbArgs.setSenderHost(me.getHostAndPort());
}
hbArgs.setTerm(_term);
} else {
hbArgs.setSetName(ourSetName);
// Config version -2 is for uninitialized config.
hbArgs.setConfigVersion(-2);
hbArgs.setTerm(OpTime::kInitialTerm);
}
hbArgs.setHeartbeatVersion(1);
const Milliseconds timeoutPeriod(
_rsConfig.isInitialized() ? _rsConfig.getHeartbeatTimeoutPeriodMillis()
: Milliseconds{ReplSetConfig::kDefaultHeartbeatTimeoutPeriod});
const Milliseconds timeout(timeoutPeriod - alreadyElapsed);
return std::make_pair(hbArgs, timeout);
}
HeartbeatResponseAction TopologyCoordinator::processHeartbeatResponse(
Date_t now,
Milliseconds networkRoundTripTime,
const HostAndPort& target,
const StatusWith<ReplSetHeartbeatResponse>& hbResponse) {
PingStats& hbStats = _pings[target];
invariant(hbStats.getLastHeartbeatStartDate() != Date_t());
const bool isUnauthorized = (hbResponse.getStatus().code() == ErrorCodes::Unauthorized) ||
(hbResponse.getStatus().code() == ErrorCodes::AuthenticationFailed);
if (hbResponse.isOK() || isUnauthorized) {
hbStats.hit(networkRoundTripTime);
} else {
hbStats.miss();
}
// If a node is not PRIMARY and has no sync source, we increase the heartbeat rate in order
// to help it find a sync source more quickly, which helps ensure the PRIMARY will continue to
// see the majority of the cluster.
//
// Arbiters also decrease their heartbeat interval to at most half the election timeout period.
Milliseconds heartbeatInterval = _rsConfig.getHeartbeatInterval();
if (getMemberState().arbiter()) {
heartbeatInterval =
std::min(_rsConfig.getElectionTimeoutPeriod() / 2, _rsConfig.getHeartbeatInterval());
} else if (getSyncSourceAddress().empty() && !_iAmPrimary()) {
heartbeatInterval = std::min(_rsConfig.getElectionTimeoutPeriod() / 2,
_rsConfig.getHeartbeatInterval() / 4);
}
const Milliseconds alreadyElapsed = now - hbStats.getLastHeartbeatStartDate();
Date_t nextHeartbeatStartDate;
// Determine the next heartbeat start time. If a heartbeat has not succeeded or failed, and we
// have not used up the timeout period, we should retry.
if (hbStats.trying() && (alreadyElapsed < _rsConfig.getHeartbeatTimeoutPeriod())) {
// There are still retries left, let's use one.
nextHeartbeatStartDate = now;
} else {
nextHeartbeatStartDate = now + heartbeatInterval;
}
if (hbStats.failed()) {
LOGV2_FOR_HEARTBEATS(
23974,
0,
"Heartbeat to {target} failed after {maxHeartbeatRetries} retries, response "
"status: {error}",
"Heartbeat failed after max retries",
"target"_attr = target,
"maxHeartbeatRetries"_attr = kMaxHeartbeatRetries,
"error"_attr = hbResponse.getStatus());
}
HeartbeatResponseAction nextAction = HeartbeatResponseAction::makeNoAction();
nextAction.setNextHeartbeatStartDate(nextHeartbeatStartDate);
if (hbResponse.isOK() && hbResponse.getValue().hasConfig()) {
// -2 is for uninitialized config.
const ConfigVersionAndTerm currentConfigVersionAndTerm = _rsConfig.isInitialized()
? _rsConfig.getConfigVersionAndTerm()
: ConfigVersionAndTerm(-2, OpTime::kUninitializedTerm);
const ReplSetConfig& newConfig = hbResponse.getValue().getConfig();
if (newConfig.getConfigVersionAndTerm() > currentConfigVersionAndTerm) {
nextAction = HeartbeatResponseAction::makeReconfigAction();
nextAction.setNextHeartbeatStartDate(nextHeartbeatStartDate);
// TODO(SERVER-48178) Only continue processing heartbeat in primary state to avoid
// concurrent reconfig and rollback.
if (_role != Role::kLeader) {
return nextAction;
}
// Continue processing heartbeat responses even if we decide to install a new config.
} else {
// Could be we got the newer version before we got the response, or the
// target erroneously sent us one, even though it isn't newer.
if (newConfig.getConfigVersionAndTerm() < currentConfigVersionAndTerm) {
LOGV2_DEBUG(21803, 1, "Config version from heartbeat was older than ours");
} else {
LOGV2_DEBUG(21804, 2, "Config from heartbeat response was same as ours");
}
if (_rsConfig.isInitialized()) {
LOGV2_DEBUG(
4615641,
2,
"Current config: {currentConfig}; Config in heartbeat: {heartbeatConfig}",
"Heartbeat config",
"currentConfig"_attr = _rsConfig.toBSON(),
"heartbeatConfig"_attr = newConfig.toBSON());
} else {
LOGV2_DEBUG(4615647,
2,
"Config in heartbeat: {heartbeatConfig}",
"Heartbeat config",
"heartbeatConfig"_attr = newConfig.toBSON());
}