-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathDDTeamCollection.actor.cpp
More file actions
7176 lines (6342 loc) · 294 KB
/
DDTeamCollection.actor.cpp
File metadata and controls
7176 lines (6342 loc) · 294 KB
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
/*
* DDTeamCollection.actor.cpp
*
* This source file is part of the FoundationDB open source project
*
* Copyright 2013-2026 Apple Inc. and the FoundationDB project authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <climits>
#include "fdbclient/SystemData.h"
#include "fdbrpc/simulator.h"
#include "fdbserver/DDTeamCollection.h"
#include "fdbserver/ExclusionTracker.actor.h"
#include "fdbserver/DataDistributionTeam.h"
#include "fdbserver/Knobs.h"
#include "flow/IRandom.h"
#include "flow/Trace.h"
#include "flow/network.h"
#include "fmt/format.h"
#include "flow/actorcompiler.h" // This must be the last #include.
namespace {
// Helper function for STL containers, with flow-friendly error handling
template <class MapContainer, class K>
auto get(MapContainer& m, K const& k) -> decltype(m.at(k)) {
auto it = m.find(k);
ASSERT(it != m.end());
return it->second;
}
} // namespace
namespace data_distribution {
int EligibilityCounter::fromGetTeamRequest(GetTeamRequest const& req) {
// equivalent to bit set operation
return req.preferLowerDiskUtil * EligibilityCounter::LOW_DISK_UTIL +
// When preferLowerReadUtil, CPU stat is for admittance to eligible pool, and ReadLoad is for sorting inside
// the pool.
req.preferLowerReadUtil * EligibilityCounter::LOW_CPU;
}
void EligibilityCounter::increase(Type type) {
type_count[type]++;
}
void EligibilityCounter::reset(Type type) {
type_count[type] = 0;
}
int EligibilityCounter::getCount(int combinedType) const {
unsigned minCount = std::numeric_limits<unsigned>::max();
for (auto& [t, c] : type_count) {
if ((combinedType & t) > 0 && minCount > c) {
minCount = c;
}
}
return minCount;
}
} // namespace data_distribution
class DDTeamCollectionImpl {
ACTOR static Future<Void> checkAndRemoveInvalidLocalityAddr(DDTeamCollection* self) {
state double start = now();
state bool hasCorrectedLocality = false;
loop {
try {
wait(delay(SERVER_KNOBS->DD_CHECK_INVALID_LOCALITY_DELAY, TaskPriority::DataDistribution));
// Because worker's processId can be changed when its locality is changed, we cannot watch on the old
// processId; This actor is inactive most time, so iterating all workers incurs little performance
// overhead.
state std::vector<ProcessData> workers = wait(self->db->getWorkers());
state std::set<AddressExclusion> existingAddrs;
for (int i = 0; i < workers.size(); i++) {
const ProcessData& workerData = workers[i];
AddressExclusion addr(workerData.address.ip, workerData.address.port);
existingAddrs.insert(addr);
if (self->invalidLocalityAddr.contains(addr) &&
self->isValidLocality(self->configuration.storagePolicy, workerData.locality)) {
// The locality info on the addr has been corrected
self->invalidLocalityAddr.erase(addr);
hasCorrectedLocality = true;
TraceEvent("InvalidLocalityCorrected").detail("Addr", addr.toString());
}
}
wait(yield(TaskPriority::DataDistribution));
// In case system operator permanently excludes workers on the address with invalid locality
for (auto addr = self->invalidLocalityAddr.begin(); addr != self->invalidLocalityAddr.end();) {
if (!existingAddrs.contains(*addr)) {
// The address no longer has a worker
addr = self->invalidLocalityAddr.erase(addr);
hasCorrectedLocality = true;
TraceEvent("InvalidLocalityNoLongerExists").detail("Addr", addr->toString());
} else {
++addr;
}
}
if (hasCorrectedLocality) {
// Recruit on address who locality has been corrected
self->restartRecruiting.trigger();
hasCorrectedLocality = false;
}
if (self->invalidLocalityAddr.empty()) {
break;
}
if (now() - start > 300) { // Report warning if invalid locality is not corrected within 300 seconds
// The incorrect locality info has not been properly corrected in a reasonable time
TraceEvent(SevWarn, "PersistentInvalidLocality")
.detail("Addresses", self->invalidLocalityAddr.size());
start = now();
}
} catch (Error& e) {
TraceEvent("CheckAndRemoveInvalidLocalityAddrRetry", self->distributorId).detail("Error", e.what());
}
}
return Void();
}
public:
ACTOR static Future<Void> logOnCompletion(DDTeamCollection* self, Future<Void> signal) {
wait(signal);
wait(delay(SERVER_KNOBS->LOG_ON_COMPLETION_DELAY, TaskPriority::DataDistribution));
if (!self->primary || self->configuration.usableRegions == 1) {
TraceEvent("DDTrackerStarting", self->distributorId)
.detail("State", "Active")
.trackLatest(self->ddTrackerStartingEventHolder->trackingKey);
}
return Void();
}
ACTOR static Future<Void> interruptableBuildTeams(DDTeamCollection* self) {
if (!self->addSubsetComplete.isSet()) {
wait(addSubsetOfEmergencyTeams(self));
self->addSubsetComplete.send(Void());
}
loop {
choose {
when(wait(self->buildTeams())) {
return Void();
}
when(wait(self->restartTeamBuilder.onTrigger())) {}
}
}
}
ACTOR static Future<Void> checkBuildTeams(DDTeamCollection* self) {
wait(self->checkTeamDelay);
while (!self->teamBuilder.isReady())
wait(self->teamBuilder);
if (self->doBuildTeams && self->readyToStart.isReady()) {
self->doBuildTeams = false;
self->teamBuilder = self->interruptableBuildTeams();
wait(self->teamBuilder);
}
return Void();
}
// Find the team with the exact storage servers as req.src.
static void getTeamByServers(DDTeamCollection* self, GetTeamRequest req) {
const std::string servers = TCTeamInfo::serversToString(req.src);
Optional<Reference<IDataDistributionTeam>> res;
for (const auto& team : self->teams) {
if (team->getServerIDsStr() == servers) {
res = team;
break;
}
}
req.reply.send(std::make_pair(res, false));
}
// Random selection for load balance
ACTOR static Future<Void> getTeamForBulkLoad(DDTeamCollection* self, GetTeamRequest req) {
try {
TraceEvent(bulkLoadVerboseEventSev(), "DDBulkLoadEngineTaskGetTeamReqReceived", self->distributorId)
.detail("TCReady", self->readyToStart.isReady())
.detail("TeamBuilderValid", self->teamBuilder.isValid())
.detail("TeamBuilderReady", self->teamBuilder.isValid() ? self->teamBuilder.isReady() : false)
.detail("SrcIds", describe(req.src))
.detail("Primary", self->isPrimary())
.detail("TeamSize", self->teams.size());
wait(self->checkBuildTeams());
TraceEvent(bulkLoadVerboseEventSev(), "DDBulkLoadEngineTaskGetTeamCheckBuildTeamDone", self->distributorId)
.detail("TCReady", self->readyToStart.isReady())
.detail("TeamBuilderValid", self->teamBuilder.isValid())
.detail("TeamBuilderReady", self->teamBuilder.isValid() ? self->teamBuilder.isReady() : false)
.detail("SrcIds", describe(req.src))
.detail("Primary", self->isPrimary())
.detail("TeamSize", self->teams.size());
if (!self->primary && !self->readyToStart.isReady()) {
// When remote DC is not ready, DD shouldn't reply with a new team because
// a data movement to that team can't be completed and such a move
// may block the primary DC from reaching "storage_recovered".
auto team = self->findTeamFromServers(req.completeSources, /*wantHealthy=*/false);
TraceEvent(SevWarn, "DDBulkLoadEngineTaskGetTeamRemoteDCNotReady", self->distributorId)
.suppressFor(1.0)
.detail("Primary", self->primary)
.detail("Team", team.present() ? describe(team.get()->getServerIDs()) : "");
req.reply.send(std::make_pair(team, true));
return Void();
}
self->updateTeamPivotValues();
// Step 1: find all valid teams from team collection
std::vector<Reference<TCTeamInfo>> validTeams;
int unhealthyTeamCount = 0;
int notEligibileTeamCount = 0;
int duplicatedCount = 0;
for (const auto& dest : self->teams) {
if (!dest->isHealthy()) {
unhealthyTeamCount++;
continue;
}
// In the simulation, the available disk space is simulated randomly.
// So, it is possible that a random low disk space can cause the bulkload test
// stuck at failing to get an eligible team.
// We still want to have this low disk space check in the simulation, but we
// do not want this check blocking the simulation. So, we randomly do the check.
if (!g_network->isSimulated() || deterministicRandom()->random01() < 0.5) {
bool anyDestServerHaveLowDiskUtil =
dest->getEligibilityCount(data_distribution::EligibilityCounter::LOW_DISK_UTIL) > 0;
if (!anyDestServerHaveLowDiskUtil) {
notEligibileTeamCount++;
continue;
}
}
bool ok = true;
for (const auto& srcId : req.src) {
std::vector<UID> serverIds = dest->getServerIDs();
for (const auto& serverId : serverIds) {
if (serverId == srcId) {
ok = false; // Do not select a team that has a server owning the bulk loading range.
break;
}
}
if (!ok) {
break;
}
}
if (!ok) {
duplicatedCount++;
continue;
}
validTeams.push_back(dest);
}
// Step 2: Conduct Power-of-D-Choice to select a team
std::vector<Reference<TCTeamInfo>> candidateTeams;
if (validTeams.size() <= SERVER_KNOBS->DD_BULKLOAD_POWER_OF_D_RATIO) {
candidateTeams = validTeams;
} else {
deterministicRandom()->randomShuffle(validTeams);
candidateTeams = std::vector<Reference<TCTeamInfo>>(
validTeams.begin(),
validTeams.begin() + std::floor(validTeams.size() / SERVER_KNOBS->DD_BULKLOAD_POWER_OF_D_RATIO));
}
Optional<Reference<IDataDistributionTeam>> res;
int minOngoingBulkLoadTaskCount = std::numeric_limits<int>::max();
for (int i = 0; i < candidateTeams.size(); i++) {
int ongoingBulkLoadTaskCount = -1;
for (const auto& ssid : candidateTeams[i]->getServerIDs()) {
ongoingBulkLoadTaskCount =
std::max(ongoingBulkLoadTaskCount, self->bulkLoadTaskCollection->busyMap.getTaskCount(ssid));
}
if (!res.present() || ongoingBulkLoadTaskCount < minOngoingBulkLoadTaskCount) {
minOngoingBulkLoadTaskCount = ongoingBulkLoadTaskCount;
res = candidateTeams[i];
}
}
if (res.present()) {
TraceEvent(bulkLoadVerboseEventSev(), "DDBulkLoadEngineTaskGetTeamReply", self->distributorId)
.detail("TCReady", self->readyToStart.isReady())
.detail("SrcIds", describe(req.src))
.detail("Primary", self->isPrimary())
.detail("TeamSize", self->teams.size())
.detail("ValidTeamSize", validTeams.size())
.detail("UnhealthyTeamCount", unhealthyTeamCount)
.detail("DuplicatedCount", duplicatedCount)
.detail("NotEligibileTeamCount", notEligibileTeamCount)
.detail("DestIds", describe(res.get()->getServerIDs()))
.detail("DestTeam", res.get()->getTeamID());
} else {
TraceEvent(SevWarnAlways, "DDBulkLoadEngineTaskGetTeamFailedToFindValidTeam", self->distributorId)
.detail("TCReady", self->readyToStart.isReady())
.detail("SrcIds", describe(req.src))
.detail("Primary", self->isPrimary())
.detail("TeamSize", self->teams.size())
.detail("ValidTeamSize", validTeams.size())
.detail("UnhealthyTeamCount", unhealthyTeamCount)
.detail("DuplicatedCount", duplicatedCount)
.detail("NotEligibileTeamCount", notEligibileTeamCount);
}
req.reply.send(std::make_pair(res, false));
return Void();
} catch (Error& e) {
if (e.code() != error_code_actor_cancelled && req.reply.canBeSet())
req.reply.sendError(e);
throw;
}
}
// Return a threshold of team queue size which guarantees at least DD_LONG_STORAGE_QUEUE_TEAM_MAJORITY_PERCENTILE
// portion of teams that have longer storage queues
// A team storage queue size is defined as the longest storage queue size among all SSes of the team
static int64_t calculateTeamStorageQueueThreshold(const std::vector<Reference<TCTeamInfo>>& teams) {
if (teams.size() == 0) {
return std::numeric_limits<int64_t>::max(); // disable this funcationality
}
std::vector<int64_t> queueLengthList;
for (const auto& team : teams) {
Optional<int64_t> storageQueueSize = team->getLongestStorageQueueSize();
if (!storageQueueSize.present()) {
// This team may have an unhealthy SS, so avoid selecting it
queueLengthList.push_back(std::numeric_limits<int64_t>::max());
} else {
queueLengthList.push_back(storageQueueSize.get());
}
}
double percentile = std::max(0.0, std::min(SERVER_KNOBS->DD_LONG_STORAGE_QUEUE_TEAM_MAJORITY_PERCENTILE, 1.0));
int position = (queueLengthList.size() - 1) * (1 - percentile);
std::nth_element(queueLengthList.begin(), queueLengthList.begin() + position, queueLengthList.end());
int64_t threshold = queueLengthList[position];
TraceEvent(SevInfo, "StorageQueueAwareGotThreshold").suppressFor(5.0).detail("Threshold", threshold);
return threshold;
}
// Returns the overall best team that matches the requirement from `req`. When preferWithinShardLimit is true, it
// also tries to select a team whose existing shard is less than SERVER_KNOBS->DESIRED_MAX_SHARDS_PER_TEAM.
static Optional<Reference<IDataDistributionTeam>> getBestTeam(DDTeamCollection* self,
const GetTeamRequest& req,
bool preferWithinShardLimit,
int& numSkippedSSFailedGetQueueLength,
int& numSkippedSSQueueTooLong,
Optional<int64_t> storageQueueThreshold) {
ASSERT(!req.storageQueueAware || storageQueueThreshold.present());
auto& startIndex = req.preferLowerDiskUtil ? self->lowestUtilizationTeam : self->highestUtilizationTeam;
if (startIndex >= self->teams.size()) {
startIndex = 0;
}
Optional<Reference<IDataDistributionTeam>> bestOption;
int64_t bestLoadBytes = 0;
bool wigglingBestOption = false; // best option contains server in paused wiggle state
int bestIndex = startIndex;
for (int i = 0; i < self->teams.size(); i++) {
int currentIndex = (startIndex + i) % self->teams.size();
if (self->teams[currentIndex]->isHealthy()) {
int eligibilityType = data_distribution::EligibilityCounter::fromGetTeamRequest(req);
if (eligibilityType != data_distribution::EligibilityCounter::NONE &&
self->teams[currentIndex]->getEligibilityCount(eligibilityType) <= 0) {
continue;
}
int64_t loadBytes = self->teams[currentIndex]->getLoadBytes(true, req.inflightPenalty);
if (req.storageQueueAware) {
Optional<int64_t> storageQueueSize = self->teams[currentIndex]->getLongestStorageQueueSize();
if (!storageQueueSize.present()) {
numSkippedSSFailedGetQueueLength++;
continue; // this team may have an unhealthy SS, skip
} else if (storageQueueSize.get() > storageQueueThreshold.get()) {
numSkippedSSQueueTooLong++;
continue; // this team has a SS with a too long storage queue, skip
}
}
auto team = ShardsAffectedByTeamFailure::Team(self->teams[currentIndex]->getServerIDs(), self->primary);
if ((!req.teamMustHaveShards || self->shardsAffectedByTeamFailure->hasShards(team)) &&
// sort conditions
(!bestOption.present() ||
req.lessCompare(bestOption.get(), self->teams[currentIndex], bestLoadBytes, loadBytes))) {
// bestOption doesn't contain wiggling SS while current team does. Don't replace bestOption
// in this case
if (bestOption.present() && !wigglingBestOption &&
self->teams[currentIndex]->hasWigglePausedServer()) {
continue;
}
if (SERVER_KNOBS->ENFORCE_SHARD_COUNT_PER_TEAM && preferWithinShardLimit &&
self->shardsAffectedByTeamFailure->getNumberOfShards(team) >
SERVER_KNOBS->DESIRED_MAX_SHARDS_PER_TEAM) {
continue;
}
bestLoadBytes = loadBytes;
bestOption = self->teams[currentIndex];
bestIndex = currentIndex;
wigglingBestOption = self->teams[bestIndex]->hasWigglePausedServer();
}
}
}
startIndex = bestIndex;
return bestOption;
}
// Returns the best team from `candidates` that matches the requirement from `req`. When preferWithinShardLimit is
// true, it also tries to select a team whose existing team is less than SERVER_KNOBS->DESIRED_MAX_SHARDS_PER_TEAM.
// Do not check storage queue size since getTeam has checked the size when selecting the input candidates
static Optional<Reference<IDataDistributionTeam>> getBestTeamFromCandidates(
DDTeamCollection* self,
const GetTeamRequest& req,
const std::vector<Reference<TCTeamInfo>>& candidates,
bool preferWithinShardLimit,
int& numSkippedSSFailedGetQueueLength,
int& numSkippedSSQueueTooLong) {
Optional<Reference<IDataDistributionTeam>> bestOption;
int64_t bestLoadBytes = 0;
bool wigglingBestOption = false; // best option contains server in paused wiggle state
for (int i = 0; i < candidates.size(); i++) {
int64_t loadBytes = candidates[i]->getLoadBytes(true, req.inflightPenalty);
if (!bestOption.present() || req.lessCompare(bestOption.get(), candidates[i], bestLoadBytes, loadBytes)) {
// bestOption doesn't contain wiggling SS while current team does. Don't replace bestOption
// in this case
if (bestOption.present() && !wigglingBestOption && candidates[i]->hasWigglePausedServer()) {
continue;
}
if (SERVER_KNOBS->ENFORCE_SHARD_COUNT_PER_TEAM && preferWithinShardLimit &&
self->shardsAffectedByTeamFailure->getNumberOfShards(ShardsAffectedByTeamFailure::Team(
candidates[i]->getServerIDs(), self->primary)) > SERVER_KNOBS->DESIRED_MAX_SHARDS_PER_TEAM) {
continue;
}
bestLoadBytes = loadBytes;
bestOption = candidates[i];
wigglingBestOption = candidates[i]->hasWigglePausedServer();
}
}
return bestOption;
}
// SOMEDAY: Make bestTeam better about deciding to leave a shard where it is (e.g. in PRIORITY_TEAM_HEALTHY case)
// use keys, src, dest, metrics, priority, system load, etc.. to decide...
ACTOR static Future<Void> getTeam(DDTeamCollection* self, GetTeamRequest req) {
try {
wait(self->checkBuildTeams());
if (!self->primary && !self->readyToStart.isReady()) {
// When remote DC is not ready, DD shouldn't reply with a new team because
// a data movement to that team can't be completed and such a move
// may block the primary DC from reaching "storage_recovered".
auto team = self->findTeamFromServers(req.completeSources, /*wantHealthy=*/false);
TraceEvent("GetTeamNotReady", self->distributorId)
.suppressFor(1.0)
.detail("Primary", self->primary)
.detail("Team", team.present() ? describe(team.get()->getServerIDs()) : "");
req.reply.send(std::make_pair(team, true));
return Void();
}
// report the pivot values
self->updateTeamPivotValues();
bool foundSrc = false;
for (const auto& id : req.src) {
if (self->server_info.contains(id)) {
foundSrc = true;
break;
}
}
// Select the best team
// Currently the metric is minimum used disk space (adjusted for data in flight)
// Only healthy teams may be selected. The team has to be healthy at the moment we update
// shardsAffectedByTeamFailure or we could be dropping a shard on the floor (since team
// tracking is "edge triggered")
// SOMEDAY: Account for capacity, load (when shardMetrics load is high)
// self->teams.size() can be 0 under the ConfigureTest.txt test when we change configurations
// The situation happens rarely. We may want to eliminate this situation someday
if (!self->teams.size()) {
req.reply.send(std::make_pair(Optional<Reference<IDataDistributionTeam>>(), foundSrc));
return Void();
}
Optional<Reference<IDataDistributionTeam>> bestOption;
state int numSkippedSSFailedGetQueueLength = 0;
state int numSkippedSSQueueTooLong = 0;
if (ddLargeTeamEnabled() && req.keys.present()) {
int customReplicas = self->configuration.storageTeamSize;
for (auto it : self->userRangeConfig->intersectingRanges(req.keys->begin, req.keys->end)) {
customReplicas = std::max(customReplicas, it->value().replicationFactor.orDefault(0));
}
if (customReplicas > self->configuration.storageTeamSize) {
auto newTeam = self->buildLargeTeam(customReplicas);
auto& firstFailureTime = self->firstLargeTeamFailure[customReplicas];
if (newTeam) {
if (newTeam->size() < customReplicas) {
if (!firstFailureTime.present()) {
firstFailureTime = now();
}
if (now() - firstFailureTime.get() < SERVER_KNOBS->DD_LARGE_TEAM_DELAY) {
req.reply.send(std::make_pair(Optional<Reference<IDataDistributionTeam>>(), foundSrc));
return Void();
}
self->underReplication.insert(req.keys.get(), true);
} else {
firstFailureTime = Optional<double>();
}
TraceEvent("ReplicatingToLargeTeam", self->distributorId)
.detail("Team", newTeam->getDesc())
.detail("Healthy", newTeam->isHealthy())
.detail("DesiredReplicas", customReplicas)
.detail("UnderReplicated", newTeam->size() < customReplicas);
req.reply.send(std::make_pair(newTeam, foundSrc));
return Void();
} else {
if (!firstFailureTime.present()) {
firstFailureTime = now();
}
if (now() - firstFailureTime.get() < SERVER_KNOBS->DD_LARGE_TEAM_DELAY) {
req.reply.send(std::make_pair(Optional<Reference<IDataDistributionTeam>>(), foundSrc));
return Void();
}
TraceEvent(SevWarnAlways, "LargeTeamNotFound", self->distributorId)
.suppressFor(1.0)
.detail("Replicas", customReplicas)
.detail("StorageTeamSize", self->configuration.storageTeamSize)
.detail("LargeTeamDiff", now() - firstFailureTime.get());
self->underReplication.insert(req.keys.get(), true);
}
}
}
// Note: this block does not apply any filters from the request
if (req.teamSelect == TeamSelect::WANT_COMPLETE_SRCS) {
auto healthyTeam = self->findTeamFromServers(req.completeSources, /* wantHealthy=*/true);
if (healthyTeam.present()) {
req.reply.send(std::make_pair(healthyTeam, foundSrc));
return Void();
}
}
Optional<int64_t> storageQueueThreshold;
if (req.storageQueueAware) {
storageQueueThreshold = calculateTeamStorageQueueThreshold(self->teams);
}
if (req.teamSelect == TeamSelect::WANT_TRUE_BEST || req.wantTrueBestIfMoveout) {
ASSERT(!bestOption.present());
if (SERVER_KNOBS->ENFORCE_SHARD_COUNT_PER_TEAM && req.preferWithinShardLimit) {
bestOption = getBestTeam(self,
req,
/*preferWithinShardLimit=*/true,
numSkippedSSFailedGetQueueLength,
numSkippedSSQueueTooLong,
storageQueueThreshold);
if (!bestOption.present()) {
// In case, we may return a team whose shard count is more than DESIRED_MAX_SHARDS_PER_TEAM.
TraceEvent("GetBestTeamPreferWithinShardLimitFailed").log();
}
}
if (!bestOption.present()) {
bestOption = getBestTeam(self,
req,
/*preferWithinShardLimit=*/false,
numSkippedSSFailedGetQueueLength,
numSkippedSSQueueTooLong,
storageQueueThreshold);
}
} else {
ASSERT(!bestOption.present());
std::vector<Reference<TCTeamInfo>> randomTeams;
int nTries = 0;
while (randomTeams.size() < SERVER_KNOBS->BEST_TEAM_OPTION_COUNT &&
nTries < SERVER_KNOBS->BEST_TEAM_MAX_TEAM_TRIES) {
// If unhealthy team is majority, we may not find an ok dest in this while loop
Reference<TCTeamInfo> dest = deterministicRandom()->randomChoice(self->teams);
bool ok = dest->isHealthy();
if (ok) {
int eligibilityType = data_distribution::EligibilityCounter::fromGetTeamRequest(req);
ok = eligibilityType == data_distribution::EligibilityCounter::NONE ||
dest->getEligibilityCount(eligibilityType) > 0;
}
for (int i = 0; ok && i < randomTeams.size(); i++) {
if (randomTeams[i]->getServerIDs() == dest->getServerIDs()) {
// Found a duplicate team. Skip `dest`.
ok = false;
break;
}
}
ok = ok && (!req.teamMustHaveShards ||
self->shardsAffectedByTeamFailure->hasShards(
ShardsAffectedByTeamFailure::Team(dest->getServerIDs(), self->primary)));
if (req.storageQueueAware) {
Optional<int64_t> storageQueueSize = dest->getLongestStorageQueueSize();
if (!storageQueueSize.present()) {
numSkippedSSFailedGetQueueLength++;
ok = false; // this team may have an unhealthy SS, skip
} else if (storageQueueSize.get() > storageQueueThreshold.get()) {
numSkippedSSQueueTooLong++;
ok = false; // this team has a SS with a too long storage queue, skip
}
}
if (ok)
randomTeams.push_back(dest);
else
nTries++;
}
// Log BestTeamStuck reason when we have healthy teams but they do not have healthy free space
if (randomTeams.empty() && !self->zeroHealthyTeams->get()) {
self->bestTeamKeepStuckCount++;
} else {
self->bestTeamKeepStuckCount = 0;
}
if (!randomTeams.empty()) {
if (SERVER_KNOBS->ENFORCE_SHARD_COUNT_PER_TEAM && req.preferWithinShardLimit) {
bestOption = getBestTeamFromCandidates(self,
req,
randomTeams,
/*preferWithinShardLimit=*/true,
numSkippedSSFailedGetQueueLength,
numSkippedSSQueueTooLong);
if (!bestOption.present()) {
// In case, we may return a team whose shard count is more than DESIRED_MAX_SHARDS_PER_TEAM.
TraceEvent("GetBestTeamFromCandidatesPreferWithinShardLimitFailed").log();
}
}
if (!bestOption.present()) {
bestOption = getBestTeamFromCandidates(self,
req,
randomTeams,
/*preferWithinShardLimit=*/false,
numSkippedSSFailedGetQueueLength,
numSkippedSSQueueTooLong);
}
}
}
// Note: req.completeSources can be empty and all servers (and server teams) can be unhealthy.
// We will get stuck at this! This only happens when a DC fails. No need to consider it right now.
// Note: this block does not apply any filters from the request
if (!bestOption.present() && self->zeroHealthyTeams->get()) {
// Attempt to find the unhealthy source server team and return it
auto healthyTeam = self->findTeamFromServers(req.completeSources, /* wantHealthy=*/false);
if (healthyTeam.present()) {
req.reply.send(std::make_pair(healthyTeam, foundSrc));
return Void();
}
}
if (g_network->isSimulated() && !bestOption.present()) {
TraceEvent(SevDebug, "GetTeamReturnEmpty")
.detail("Request", req.getDesc())
.detail("HealthyTeams", self->healthyTeamCount)
.detail("PivotCPU", self->teamPivots.pivotCPU)
.detail("PivotDiskSpace", self->teamPivots.pivotAvailableSpaceRatio)
.detail("StorageQueueAware", req.storageQueueAware)
.detail("NumSkippedSSFailedGetQueueLength", numSkippedSSFailedGetQueueLength)
.detail("NumSkippedSSQueueTooLong", numSkippedSSQueueTooLong);
// self->traceAllInfo(true);
}
if (!bestOption.present() && (req.storageQueueAware || req.wantTrueBestIfMoveout)) {
// re-run getTeam without storageQueueAware and wantTrueBestIfMoveout
req.storageQueueAware = false;
req.wantTrueBestIfMoveout = false;
TraceEvent(SevWarn, "GetTeamRetry", self->distributorId)
.detail("OldStorageQueueAware", req.storageQueueAware)
.detail("OldWantTrueBestIfMoveout", req.wantTrueBestIfMoveout);
wait(getTeam(self, req));
} else {
req.reply.send(std::make_pair(bestOption, foundSrc));
}
return Void();
} catch (Error& e) {
if (e.code() != error_code_actor_cancelled && req.reply.canBeSet())
req.reply.sendError(e);
throw;
}
}
// FIXME: describe purpose
ACTOR static Future<Void> addSubsetOfEmergencyTeams(DDTeamCollection* self) {
state int idx = 0;
state std::vector<Reference<TCServerInfo>> servers;
state std::vector<UID> serverIds;
state Reference<LocalitySet> tempSet = Reference<LocalitySet>(new LocalityMap<UID>());
state LocalityMap<UID>* tempMap = (LocalityMap<UID>*)tempSet.getPtr();
state std::vector<Reference<TCTeamInfo>> largeOrBadTeams = self->badTeams;
largeOrBadTeams.insert(largeOrBadTeams.end(), self->largeTeams.begin(), self->largeTeams.end());
for (; idx < largeOrBadTeams.size(); idx++) {
servers.clear();
for (const auto& server : largeOrBadTeams[idx]->getServers()) {
if (server->isInDesiredDC() && !self->server_status.get(server->getId()).isUnhealthy()) {
servers.push_back(server);
}
}
// For the bad team that is too big (too many servers), we will try to find a subset of servers in the
// team to construct a new healthy team, so that moving data to the new healthy team will not cause too
// much data movement overhead
// FIXME: This code logic can be simplified.
if (servers.size() >= self->configuration.storageTeamSize) {
bool foundTeam = false;
for (int j = 0; j < servers.size() - self->configuration.storageTeamSize + 1 && !foundTeam; j++) {
auto const& serverTeams = servers[j]->getTeams();
for (int k = 0; k < serverTeams.size(); k++) {
auto& testTeam = serverTeams[k]->getServerIDs();
bool allInTeam = true; // All servers in testTeam belong to the healthy servers
for (int l = 0; l < testTeam.size(); l++) {
bool foundServer = false;
for (auto it : servers) {
if (it->getId() == testTeam[l]) {
foundServer = true;
break;
}
}
if (!foundServer) {
allInTeam = false;
break;
}
}
if (allInTeam) {
foundTeam = true;
break;
}
}
}
if (!foundTeam) {
if (self->satisfiesPolicy(servers)) {
if (servers.size() == self->configuration.storageTeamSize ||
self->satisfiesPolicy(servers, self->configuration.storageTeamSize)) {
servers.resize(self->configuration.storageTeamSize);
self->addTeam(servers, IsInitialTeam::True);
} else {
tempSet->clear();
for (auto it : servers) {
tempMap->add(it->getLastKnownInterface().locality, &it->getId());
}
std::vector<LocalityEntry> resultEntries, forcedEntries;
bool result = tempSet->selectReplicas(
self->configuration.storagePolicy, forcedEntries, resultEntries);
ASSERT(result && resultEntries.size() == self->configuration.storageTeamSize);
serverIds.clear();
for (auto& it : resultEntries) {
serverIds.push_back(*tempMap->getObject(it));
}
std::sort(serverIds.begin(), serverIds.end());
self->addTeam(serverIds.begin(), serverIds.end(), IsInitialTeam::True);
}
} else {
serverIds.clear();
for (auto it : servers) {
serverIds.push_back(it->getId());
}
TraceEvent(SevWarnAlways, "CannotAddSubset", self->distributorId)
.detail("Servers", describe(serverIds));
}
}
}
wait(yield());
}
// Trace and record the current number of teams for correctness test
self->traceTeamCollectionInfo();
return Void();
}
ACTOR static Future<Void> init(DDTeamCollection* self,
Reference<InitialDataDistribution> initTeams,
const DDEnabledState* ddEnabledState) {
self->userRangeConfig = initTeams->userRangeConfig;
self->healthyZone.set(initTeams->initHealthyZoneValue);
// SOMEDAY: If some servers have teams and not others (or some servers have more data than others) and there is
// an address/locality collision, should we preferentially mark the least used server as undesirable?
for (auto& [server, procClass] : initTeams->allServers) {
if (self->shouldHandleServer(server)) {
if (!self->isValidLocality(self->configuration.storagePolicy, server.locality)) {
TraceEvent(SevWarnAlways, "MissingLocality")
.detail("Server", server.uniqueID)
.detail("Locality", server.locality.toString());
auto addr = server.stableAddress();
self->invalidLocalityAddr.insert(AddressExclusion(addr.ip, addr.port));
if (self->checkInvalidLocalities.isReady()) {
self->checkInvalidLocalities = checkAndRemoveInvalidLocalityAddr(self);
self->addActor.send(self->checkInvalidLocalities);
}
}
self->addServer(server, procClass, self->serverTrackerErrorOut, 0, *ddEnabledState);
}
}
state std::set<std::vector<UID>>::iterator teamIter =
self->primary ? initTeams->primaryTeams.begin() : initTeams->remoteTeams.begin();
state std::set<std::vector<UID>>::iterator teamIterEnd =
self->primary ? initTeams->primaryTeams.end() : initTeams->remoteTeams.end();
for (; teamIter != teamIterEnd; ++teamIter) {
self->addTeam(teamIter->begin(), teamIter->end(), IsInitialTeam::True);
wait(yield());
}
return Void();
}
ACTOR static Future<Void> buildTeams(DDTeamCollection* self) {
state int desiredTeams;
state int serverCount = 0;
state std::set<Optional<Standalone<StringRef>>> machines;
// wait to see whether restartTeamBuilder is triggered
wait(delay(0, g_network->getCurrentTask()));
// make team builder don't build team during the interval between excluding the wiggled process and recruited a
// new SS to avoid redundant teams
while (self->pauseWiggle && !self->pauseWiggle->get() && self->waitUntilRecruited.get()) {
choose {
when(wait(self->waitUntilRecruited.onChange() || self->pauseWiggle->onChange())) {}
when(wait(delay(SERVER_KNOBS->PERPETUAL_WIGGLE_DELAY, g_network->getCurrentTask()))) {
break;
}
}
}
for (const auto& [serverID, server] : self->server_info) {
if (!self->server_status.get(serverID).isUnhealthy()) {
++serverCount;
LocalityData const& serverLocation = server->getLastKnownInterface().locality;
machines.insert(serverLocation.zoneId());
}
}
int uniqueMachines = machines.size();
TraceEvent("BuildTeams", self->distributorId)
.detail("ServerCount", self->server_info.size())
.detail("UniqueMachines", uniqueMachines)
.detail("Primary", self->primary)
.detail("StorageTeamSize", self->configuration.storageTeamSize);
if (uniqueMachines >= self->configuration.storageTeamSize) {
desiredTeams = SERVER_KNOBS->DESIRED_TEAMS_PER_SERVER * serverCount;
int maxTeams = SERVER_KNOBS->MAX_TEAMS_PER_SERVER * serverCount;
// Exclude teams who have members in the wrong configuration, since we don't want these teams
int teamCount = 0;
int totalTeamCount = 0;
int wigglingTeams = 0;
for (int i = 0; i < self->teams.size(); ++i) {
if (!self->teams[i]->isWrongConfiguration()) {
if (self->teams[i]->isHealthy()) {
teamCount++;
}
totalTeamCount++;
}
if (self->teams[i]->getPriority() == SERVER_KNOBS->PRIORITY_PERPETUAL_STORAGE_WIGGLE) {
wigglingTeams++;
}
}
// teamsToBuild is calculated such that we will not build too many teams in the situation
// when all (or most of) teams become unhealthy temporarily and then healthy again
state int teamsToBuild;
teamsToBuild = std::max(0, std::min(desiredTeams - teamCount, maxTeams - totalTeamCount));
if (teamCount == 0 && teamsToBuild == 0 && SERVER_KNOBS->DD_BUILD_EXTRA_TEAMS_OVERRIDE > 0) {
// Use DD_BUILD_EXTRA_TEAMS_OVERRIDE > 0 as the feature flag: Set to 0 to disable it
TraceEvent(SevWarnAlways, "BuildServerTeamsHaveTooManyUnhealthyTeams")
.detail("Hint", "Build teams may stuck and prevent DD from relocating data")
.detail("BuildExtraServerTeamsOverride", SERVER_KNOBS->DD_BUILD_EXTRA_TEAMS_OVERRIDE);
teamsToBuild = SERVER_KNOBS->DD_BUILD_EXTRA_TEAMS_OVERRIDE;
}
TraceEvent("BuildTeamsBegin", self->distributorId)
.detail("Primary", self->isPrimary())
.detail("TeamsToBuild", teamsToBuild)
.detail("DesiredTeams", desiredTeams)
.detail("MaxTeams", maxTeams)
.detail("BadServerTeams", self->badTeams.size())
.detail("PerpetualWigglingTeams", wigglingTeams)
.detail("UniqueMachines", uniqueMachines)
.detail("TeamSize", self->configuration.storageTeamSize)
.detail("Servers", self->server_info.size())
.detail("HealthyServers", serverCount)
.detail("CurrentTrackedServerTeams", self->teams.size())
.detail("HealthyTeamCount", teamCount)
.detail("TotalTeamCount", totalTeamCount)
.detail("MachineTeamCount", self->machineTeams.size())
.detail("MachineCount", self->machine_info.size())
.detail("DesiredTeamsPerServer", SERVER_KNOBS->DESIRED_TEAMS_PER_SERVER);
self->lastBuildTeamsFailed = false;
if (teamsToBuild > 0 || self->notEnoughTeamsForAServer()) {
state std::vector<std::vector<UID>> builtTeams;
// addTeamsBestOf() will not add more teams than needed.
// If the team number is more than the desired, the extra teams are added in the code path when
// a team is added as an initial team
int addedTeams = self->addTeamsBestOf(teamsToBuild, desiredTeams, maxTeams);
if (addedTeams <= 0 && self->teams.size() == 0) {
TraceEvent(SevWarn, "NoTeamAfterBuildTeam", self->distributorId)
.detail("ServerTeamNum", self->teams.size())
.detail("Debug", "Check information below");
// Debug: set true for traceAllInfo() to print out more information
self->traceAllInfo();
}
} else {
int totalHealthyMachineCount = self->calculateHealthyMachineCount();
int desiredMachineTeams = SERVER_KNOBS->DESIRED_TEAMS_PER_SERVER * totalHealthyMachineCount;
int maxMachineTeams = SERVER_KNOBS->MAX_TEAMS_PER_SERVER * totalHealthyMachineCount;
int healthyMachineTeamCount = self->getHealthyMachineTeamCount();
auto [minTeamsOnServer, maxTeamsOnServer] = self->calculateMinMaxServerTeamsOnServer();
auto [minMachineTeamsOnMachine, maxMachineTeamsOnMachine] =
self->calculateMinMaxMachineTeamsOnMachine();
TraceEvent("TeamCollectionInfo", self->distributorId)
.detail("Primary", self->primary)
.detail("AddedTeams", 0)
.detail("TeamsToBuild", teamsToBuild)
.detail("CurrentServerTeams", self->teams.size())
.detail("Servers", self->server_info.size())
.detail("HealthyServers", serverCount)
.detail("DesiredTeams", desiredTeams)
.detail("MaxTeams", maxTeams)
.detail("StorageTeamSize", self->configuration.storageTeamSize)
.detail("CurrentMachineTeams", self->machineTeams.size())
.detail("CurrentHealthyMachineTeams", healthyMachineTeamCount)
.detail("DesiredMachineTeams", desiredMachineTeams)
.detail("MaxMachineTeams", maxMachineTeams)
.detail("TotalHealthyMachines", totalHealthyMachineCount)
.detail("MinTeamsOnServer", minTeamsOnServer)
.detail("MaxTeamsOnServer", maxTeamsOnServer)
.detail("MinMachineTeamsOnMachine", maxMachineTeamsOnMachine)
.detail("MaxMachineTeamsOnMachine", minMachineTeamsOnMachine)
.detail("DoBuildTeams", self->doBuildTeams)
.trackLatest(self->teamCollectionInfoEventHolder->trackingKey);
}
} else {
// If there are too few machines to even build teams or there are too few represented datacenters, can't
// build any team.
self->lastBuildTeamsFailed = true;
TraceEvent(SevWarnAlways, "BuildTeamsLastBuildTeamsFailed", self->distributorId)
.detail("Reason", "Do not have enough unique machines")
.detail("Primary", self->primary)
.detail("UniqueMachines", uniqueMachines)
.detail("Replication", self->configuration.storageTeamSize);
}
self->evaluateTeamQuality();
// Building teams can cause servers to become undesired, which can make teams unhealthy.
// Let all of these changes get worked out before responding to the get team request
wait(delay(0, TaskPriority::DataDistributionLaunch));
return Void();
}
// Track a team and issue RelocateShards when the level of degradation changes
// A badTeam can be unhealthy or just a redundantTeam removed by machineTeamRemover() or serverTeamRemover()
ACTOR static Future<Void> teamTracker(DDTeamCollection* self,
Reference<TCTeamInfo> team,
IsBadTeam badTeam,
IsRedundantTeam redundantTeam) {
state int lastServersLeft = team->size();