-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathDataDistribution.cpp
More file actions
5429 lines (5133 loc) · 236 KB
/
DataDistribution.cpp
File metadata and controls
5429 lines (5133 loc) · 236 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
/*
* DataDistribution.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 "fdbclient/Audit.h"
#include "fdbclient/AuditUtils.h"
#include "fdbclient/BulkDumping.h"
#include "fdbclient/BulkLoading.h"
#include "fdbclient/DatabaseContext.h"
#include "fdbclient/FDBOptions.g.h"
#include "fdbclient/FDBTypes.h"
#include "fdbclient/Knobs.h"
#include "fdbclient/ManagementAPI.h"
#include "fdbclient/RunRYWTransaction.h"
#include "fdbclient/StorageServerInterface.h"
#include "fdbclient/SystemData.h"
#include "fdbserver/core/BackupPartitionMap.h"
#include "fdbserver/core/BulkDumpUtil.h"
#include "fdbserver/core/BulkLoadUtil.h"
#include "fdbserver/datadistributor/DataDistributor.h"
#include "fdbserver/datadistributor/DDSharedContext.h"
#include "fdbserver/datadistributor/DDTeamCollection.h"
#include "fdbserver/datadistributor/DataDistribution.h"
#include "DDRelocationQueue.h"
#include "fdbserver/core/Knobs.h"
#include "fdbserver/core/MoveKeys.h"
#include "fdbserver/core/QuietDatabase.h"
#include "fdbserver/core/TLogInterface.h"
#include "fdbserver/core/WaitFailure.h"
#include "fdbserver/core/WorkloadKeys.h"
#include "fdbserver/datadistributor/MockDataDistributor.h"
#include "flow/ActorCollection.h"
#include "flow/Arena.h"
#include "flow/Buggify.h"
#include "flow/Error.h"
#include "flow/Platform.h"
#include "flow/TxnCounters.h"
#include "flow/Trace.h"
#include "flow/UnitTest.h"
#include "flow/flow.h"
#include "flow/genericactors.actor.h"
#include "flow/serialize.h"
#include "flow/CoroUtils.h"
static const std::string ddServerBulkDumpFolder = "ddBulkDumpFiles";
static const std::string ddServerBulkLoadFolder = "ddBulkLoadFiles";
DataMoveType getDataMoveTypeFromDataMoveId(const UID& dataMoveId) {
bool assigned, emptyRange;
DataMoveType dataMoveType;
DataMovementReason dataMoveReason;
decodeDataMoveId(dataMoveId, assigned, emptyRange, dataMoveType, dataMoveReason);
return dataMoveType;
}
void RelocateShard::setParentRange(KeyRange const& parent) {
ASSERT(reason == RelocateReason::WRITE_SPLIT || reason == RelocateReason::SIZE_SPLIT);
parent_range = parent;
}
Optional<KeyRange> RelocateShard::getParentRange() const {
return parent_range;
}
namespace {
std::set<int> const& normalDDQueueErrors() {
static std::set<int> s{ error_code_movekeys_conflict,
error_code_broken_promise,
error_code_data_move_cancelled,
error_code_data_move_dest_team_not_found,
error_code_finish_move_keys_too_many_retries,
error_code_start_move_keys_too_many_retries };
return s;
}
} // anonymous namespace
enum class DDAuditContext : uint8_t {
INVALID = 0,
RESUME = 1,
LAUNCH = 2,
RETRY = 3,
};
struct DDAudit {
explicit(false) DDAudit(AuditStorageState coreState)
: coreState(coreState), actors(true), foundError(false), auditStorageAnyChildFailed(false), retryCount(0),
cancelled(false), overallCompleteDoAuditCount(0), overallIssuedDoAuditCount(0), overallSkippedDoAuditCount(0),
remainingBudgetForAuditTasks(SERVER_KNOBS->CONCURRENT_AUDIT_TASK_COUNT_MAX), context(DDAuditContext::INVALID) {}
AuditStorageState coreState;
ActorCollection actors;
Future<Void> auditActor;
bool foundError;
int retryCount;
bool auditStorageAnyChildFailed;
bool cancelled; // use to cancel any actor beyond auditActor
int64_t overallIssuedDoAuditCount;
int64_t overallCompleteDoAuditCount;
int64_t overallSkippedDoAuditCount;
AsyncVar<int> remainingBudgetForAuditTasks;
DDAuditContext context;
std::unordered_set<UID> serversFinishedSSShardAudit; // dedicated to ssshard
inline void setAuditRunActor(Future<Void> actor) { auditActor = actor; }
inline Future<Void> getAuditRunActor() { return auditActor; }
inline void setDDAuditContext(DDAuditContext context_) { this->context = context_; }
inline DDAuditContext getDDAuditContext() const { return context; }
// auditActor and actors are guaranteed to deliver a cancel signal
void cancel() {
auditActor.cancel();
actors.clear(true);
cancelled = true;
}
bool isCancelled() const { return cancelled; }
};
void DataMove::validateShard(const DDShardInfo& shard, KeyRangeRef range, int priority) {
if (!valid) {
if (shard.hasDest && shard.destId != anonymousShardId) {
TraceEvent(SevError, "DataMoveValidationError")
.detail("Range", range)
.detail("Reason", "DataMoveMissing")
.detail("DestID", shard.destId)
.detail("ShardPrimaryDest", describe(shard.primaryDest))
.detail("ShardRemoteDest", describe(shard.remoteDest));
}
return;
}
if (this->meta.ranges.empty()) {
TraceEvent(SevError, "DataMoveValidationError")
.detail("Range", range)
.detail("Reason", "DataMoveMetatdataRangeEmpty")
.detail("DestID", shard.destId)
.detail("DataMoveMetaData", this->meta.toString())
.detail("ShardPrimaryDest", describe(shard.primaryDest))
.detail("ShardRemoteDest", describe(shard.remoteDest));
ASSERT(false);
}
if (!this->meta.ranges.front().contains(range)) {
TraceEvent(SevError, "DataMoveValidationError")
.detail("Range", range)
.detail("Reason", "DataMoveMetatdataRangeMismatch")
.detail("DestID", shard.destId)
.detail("DataMoveMetaData", this->meta.toString())
.detail("ShardPrimaryDest", describe(shard.primaryDest))
.detail("ShardRemoteDest", describe(shard.remoteDest));
ASSERT(false);
}
if (!shard.hasDest) {
TraceEvent(SevWarnAlways, "DataMoveValidationError")
.detail("Range", range)
.detail("Reason", "ShardMissingDest")
.detail("DataMoveMetaData", this->meta.toString())
.detail("DataMovePrimaryDest", describe(this->primaryDest))
.detail("DataMoveRemoteDest", describe(this->remoteDest));
cancelled = true;
return;
}
if (shard.destId != this->meta.id) {
TraceEvent(SevWarnAlways, "DataMoveValidationError")
.detail("Range", range)
.detail("Reason", "DataMoveIDMissMatch")
.detail("DataMoveMetaData", this->meta.toString())
.detail("ShardMoveID", shard.destId);
cancelled = true;
return;
}
if (!std::equal(
this->primaryDest.begin(), this->primaryDest.end(), shard.primaryDest.begin(), shard.primaryDest.end()) ||
!std::equal(
this->remoteDest.begin(), this->remoteDest.end(), shard.remoteDest.begin(), shard.remoteDest.end())) {
TraceEvent(g_network->isSimulated() ? SevWarn : SevError, "DataMoveValidationError")
.detail("Range", range)
.detail("Reason", "DataMoveDestMissMatch")
.detail("DataMoveMetaData", this->meta.toString())
.detail("DataMovePrimaryDest", describe(this->primaryDest))
.detail("DataMoveRemoteDest", describe(this->remoteDest))
.detail("ShardPrimaryDest", describe(shard.primaryDest))
.detail("ShardRemoteDest", describe(shard.remoteDest));
cancelled = true;
}
}
Future<Void> StorageWiggler::onCheck() const {
return delay(MIN_ON_CHECK_DELAY_SEC);
}
// add server to wiggling queue
void StorageWiggler::addServer(const UID& serverId, const StorageMetadataType& metadata) {
// std::cout << "size: " << pq_handles.size() << " add " << serverId.toString() << " DC: "
// << teamCollection->isPrimary() << std::endl;
ASSERT(!pq_handles.contains(serverId));
pq_handles[serverId] = wiggle_pq.emplace(metadata, serverId);
}
void StorageWiggler::removeServer(const UID& serverId) {
// std::cout << "size: " << pq_handles.size() << " remove " << serverId.toString() << " DC: "
// << teamCollection->isPrimary() << std::endl;
if (contains(serverId)) { // server haven't been popped
auto handle = pq_handles.at(serverId);
pq_handles.erase(serverId);
wiggle_pq.erase(handle);
}
}
void StorageWiggler::updateMetadata(const UID& serverId, const StorageMetadataType& metadata) {
// std::cout << "size: " << pq_handles.size() << " update " << serverId.toString()
// << " DC: " << teamCollection->isPrimary() << std::endl;
auto handle = pq_handles.at(serverId);
if ((*handle).first == metadata) {
return;
}
wiggle_pq.update(handle, std::make_pair(metadata, serverId));
}
bool StorageWiggler::necessary(const UID& serverId, const StorageMetadataType& metadata) const {
return metadata.wrongConfiguredForWiggle ||
(now() - metadata.createdTime > SERVER_KNOBS->DD_STORAGE_WIGGLE_MIN_SS_AGE_SEC);
}
Optional<UID> StorageWiggler::getNextServerId(bool necessaryOnly) {
if (!wiggle_pq.empty()) {
auto [metadata, id] = wiggle_pq.top();
if (necessaryOnly && !necessary(id, metadata)) {
return {};
}
wiggle_pq.pop();
pq_handles.erase(id);
return Optional<UID>(id);
}
return Optional<UID>();
}
Future<Void> StorageWiggler::resetStats() {
metrics.reset();
return runRYWTransaction(
teamCollection->dbContext(), [this](Reference<ReadYourWritesTransaction> tr) -> Future<Void> {
return wiggleData.resetStorageWiggleMetrics(tr, PrimaryRegion(teamCollection->isPrimary()), metrics);
});
}
Future<Void> StorageWiggler::restoreStats() {
auto readFuture = wiggleData.storageWiggleMetrics(PrimaryRegion(teamCollection->isPrimary()))
.getD(teamCollection->dbContext().getReference(), Snapshot::False, metrics);
return store(metrics, readFuture);
}
Future<Void> StorageWiggler::startWiggle() {
metrics.last_wiggle_start = StorageMetadataType::currentTime();
if (shouldStartNewRound()) {
metrics.last_round_start = metrics.last_wiggle_start;
}
return runRYWTransaction(
teamCollection->dbContext(), [this](Reference<ReadYourWritesTransaction> tr) -> Future<Void> {
return wiggleData.updateStorageWiggleMetrics(tr, metrics, PrimaryRegion(teamCollection->isPrimary()));
});
}
Future<Void> StorageWiggler::finishWiggle() {
metrics.last_wiggle_finish = StorageMetadataType::currentTime();
metrics.finished_wiggle += 1;
auto duration = metrics.last_wiggle_finish - metrics.last_wiggle_start;
metrics.smoothed_wiggle_duration.setTotal((double)duration);
if (shouldFinishRound()) {
metrics.last_round_finish = metrics.last_wiggle_finish;
metrics.finished_round += 1;
duration = metrics.last_round_finish - metrics.last_round_start;
metrics.smoothed_round_duration.setTotal((double)duration);
}
return runRYWTransaction(
teamCollection->dbContext(), [this](Reference<ReadYourWritesTransaction> tr) -> Future<Void> {
return wiggleData.updateStorageWiggleMetrics(tr, metrics, PrimaryRegion(teamCollection->isPrimary()));
});
}
Future<Void> remoteRecovered(Reference<AsyncVar<ServerDBInfo> const> db) {
TraceEvent("DDTrackerStarting").log();
while (db->get().recoveryState < RecoveryState::ALL_LOGS_RECRUITED) {
TraceEvent("DDTrackerStarting").detail("RecoveryState", (int)db->get().recoveryState);
co_await db->onChange();
}
}
// Watches backupPartitionRequiredKey.
// On value=1, computes the user keyspace partitions and writes them to backupPartitionListKey.
// On value=2, clears backupPartitionListKey.
// In both cases the request key is cleared in the same commit.
Future<Void> monitorBackupPartitionRequired(Database cx, KeyRangeMap<ShardTrackedData>* shards, UID ddId) {
// The partition computation can wait arbitrarily long on shard-metrics tracking, so it runs OUTSIDE any
// transaction to avoid transaction_too_old. A short re-read in the write transaction protects against
// the race where a value=2 (cleanup) arrives while we are computing for a value=1.
while (true) {
// Phase 1: peek the request key in a loop. If nothing pending, park on watch and wait, then re-read.
int8_t requestType = 0;
while (requestType == 0) {
ReadYourWritesTransaction tr(cx);
Error err;
try {
tr.setOption(FDBTransactionOptions::ACCESS_SYSTEM_KEYS);
tr.setOption(FDBTransactionOptions::LOCK_AWARE);
Optional<Value> value = co_await tr.get(backupPartitionRequiredKey);
requestType = value.present() ? decodeBackupPartitionRequiredValue(value.get()) : 0;
if (requestType == 0) {
Future<Void> watchFuture = tr.watch(backupPartitionRequiredKey);
co_await tr.commit();
co_await watchFuture;
}
continue;
} catch (Error& e) {
err = e;
}
co_await tr.onError(err);
}
// Phase 2: compute outside any transaction (may wait long on shard metrics).
std::vector<KeyRange> partitions;
if (requestType == 1) {
partitions = co_await calculateBackupPartitionKeyRanges(shards);
}
// Phase 3: short txn to re-check the request value and write the result.
{
ReadYourWritesTransaction tr(cx);
while (true) {
Error err;
try {
tr.setOption(FDBTransactionOptions::ACCESS_SYSTEM_KEYS);
tr.setOption(FDBTransactionOptions::LOCK_AWARE);
Optional<Value> value = co_await tr.get(backupPartitionRequiredKey);
int8_t currentType = value.present() ? decodeBackupPartitionRequiredValue(value.get()) : 0;
if (currentType != requestType) {
// Someone wrote a new request while we were computing partitions; restart the outer loop
// so the next iteration acts on the new value.
break;
}
if (requestType == 1) {
tr.set(backupPartitionListKey, encodeBackupPartitionListValue(partitions));
tr.clear(backupPartitionRequiredKey);
co_await tr.commit();
TraceEvent("DDBackupPartitionsComputed", ddId).detail("NumPartitions", partitions.size());
} else {
tr.clear(backupPartitionListKey);
tr.clear(backupPartitionRequiredKey);
co_await tr.commit();
TraceEvent("DDBackupPartitionsCleared", ddId);
}
break;
} catch (Error& e) {
err = e;
}
co_await tr.onError(err);
}
}
}
}
// Ensures that the serverKeys key space is properly coalesced
// This method is only used for testing and is not implemented in a manner that is safe for large databases
Future<Void> debugCheckCoalescing(Database cx) {
Transaction tr(cx);
while (true) {
Error err;
try {
RangeResult serverList = co_await tr.getRange(serverListKeys, CLIENT_KNOBS->TOO_MANY);
ASSERT(!serverList.more && serverList.size() < CLIENT_KNOBS->TOO_MANY);
int i{ 0 };
for (i = 0; i < serverList.size(); i++) {
UID id = decodeServerListValue(serverList[i].value).id();
RangeResult ranges = co_await krmGetRanges(&tr, serverKeysPrefixFor(id), allKeys);
ASSERT(ranges.end()[-1].key == allKeys.end);
for (int j = 0; j < ranges.size() - 2; j++)
if (ranges[j].value == ranges[j + 1].value)
TraceEvent(SevError, "UncoalescedValues", id)
.detail("Key1", ranges[j].key)
.detail("Key2", ranges[j + 1].key)
.detail("Value", ranges[j].value);
}
TraceEvent("DoneCheckingCoalescing").log();
co_return;
} catch (Error& e) {
err = e;
}
co_await tr.onError(err);
}
}
struct DataDistributor;
void runAuditStorage(
Reference<DataDistributor> self,
AuditStorageState auditStates,
int retryCount,
DDAuditContext context,
Optional<std::unordered_set<UID>> serversFinishedSSShardAudit = Optional<std::unordered_set<UID>>());
Future<Void> auditStorageCore(Reference<DataDistributor> self, UID auditID, AuditType auditType, int currentRetryCount);
Future<UID> launchAudit(Reference<DataDistributor> self,
KeyRange auditRange,
AuditType auditType,
KeyValueStoreType auditStorageEngineType);
Future<Void> auditStorage(Reference<DataDistributor> self, TriggerAuditRequest req);
Future<Void> periodicAuditLocationMetadata(Reference<DataDistributor> self);
void loadAndDispatchAudit(Reference<DataDistributor> self, std::shared_ptr<DDAudit> audit);
Future<Void> dispatchAuditStorageServerShard(Reference<DataDistributor> self, std::shared_ptr<DDAudit> audit);
Future<Void> scheduleAuditStorageShardOnServer(Reference<DataDistributor> self,
std::shared_ptr<DDAudit> audit,
StorageServerInterface ssi);
Future<Void> dispatchAuditStorage(Reference<DataDistributor> self, std::shared_ptr<DDAudit> audit);
Future<Void> dispatchAuditLocationMetadata(Reference<DataDistributor> self,
std::shared_ptr<DDAudit> audit,
KeyRange range);
Future<Void> doAuditLocationMetadata(Reference<DataDistributor> self,
std::shared_ptr<DDAudit> audit,
KeyRange auditRange);
Future<Void> scheduleAuditOnRange(Reference<DataDistributor> self, std::shared_ptr<DDAudit> audit, KeyRange range);
Future<Void> doAuditOnStorageServer(Reference<DataDistributor> self,
std::shared_ptr<DDAudit> audit,
StorageServerInterface ssi,
AuditStorageRequest req);
Future<Void> skipAuditOnRange(Reference<DataDistributor> self, std::shared_ptr<DDAudit> audit, KeyRange rangeToSkip);
void runBulkLoadTaskAsync(Reference<DataDistributor> self, KeyRange range, UID taskId, bool restart);
Future<Void> scheduleBulkLoadTasks(Reference<DataDistributor> self);
struct DDBulkLoadJobManager {
BulkLoadJobState jobState;
BulkLoadTransportMethod jobTransportMethod;
// manifestEntryMap is a map from the begin key of the manifest to the manifest entry.
// The end key of the current manifest is the begin key of the next manifest.
// When the task range is aligned with the manifest range, every key is the begin key of the corresponding manifest.
// When the task range is not aligned with the manifest range, the first key is the task begin key which can be
// larger than the corresponding manifest begin key.
std::shared_ptr<BulkLoadManifestFileMap> manifestEntryMap;
std::string manifestLocalTempFolder;
bool allTaskSubmitted = false;
DDBulkLoadJobManager() = default;
DDBulkLoadJobManager(const BulkLoadJobState& jobState, const std::string& manifestLocalTempFolder)
: jobState(jobState), manifestLocalTempFolder(manifestLocalTempFolder), allTaskSubmitted(false) {
manifestEntryMap = std::make_shared<BulkLoadManifestFileMap>();
}
bool isValid() const { return jobState.isValid(); }
};
struct DDBulkDumpJobManager {
BulkDumpState jobState;
std::map<Key, BulkLoadManifest> taskManifestMap;
DDBulkDumpJobManager() = default;
explicit DDBulkDumpJobManager(const BulkDumpState& jobState) : jobState(jobState) {}
bool isValid() const { return jobState.isValid(); }
};
struct DataDistributor : NonCopyable, ReferenceCounted<DataDistributor> {
public:
Reference<AsyncVar<ServerDBInfo> const> dbInfo;
Reference<DDSharedContext> context;
UID ddId;
PromiseStream<Future<Void>> addActor;
// State initialized when bootstrap
Reference<IDDTxnProcessor> txnProcessor;
MoveKeysLock& lock; // reference to context->lock
DatabaseConfiguration& configuration; // reference to context->configuration
std::vector<Optional<Key>> primaryDcId;
std::vector<Optional<Key>> remoteDcIds;
Reference<InitialDataDistribution> initData;
Reference<EventCacheHolder> initialDDEventHolder;
Reference<EventCacheHolder> movingDataEventHolder;
Reference<EventCacheHolder> totalDataInFlightEventHolder;
Reference<EventCacheHolder> totalDataInFlightRemoteEventHolder;
// Optional components that can be set after ::init(). They're optional when test, but required for DD being
// fully-functional.
DDTeamCollection* teamCollection;
Reference<ShardsAffectedByTeamFailure> shardsAffectedByTeamFailure;
// consumer is a yield stream from producer. The RelocateShard is pushed into relocationProducer and popped from
// relocationConsumer (by DDQueue)
PromiseStream<RelocateShard> relocationProducer, relocationConsumer;
PromiseStream<BulkLoadShardRequest> triggerShardBulkLoading;
Reference<PhysicalShardCollection> physicalShardCollection;
Reference<BulkLoadTaskCollection> bulkLoadTaskCollection;
Promise<Void> initialized;
std::unordered_map<AuditType, std::unordered_map<UID, std::shared_ptr<DDAudit>>> audits;
FlowLock auditStorageHaLaunchingLock;
FlowLock auditStorageReplicaLaunchingLock;
FlowLock auditStorageLocationMetadataLaunchingLock;
FlowLock auditStorageSsShardLaunchingLock;
FlowLock auditStorageRestoreLaunchingLock;
Promise<Void> auditStorageInitialized;
bool auditStorageInitStarted;
// monitor DD configuration change
Promise<Version> configChangeWatching;
Future<Void> onConfigChange;
ActorCollection bulkLoadActors;
bool bulkLoadEnabled = false;
ParallelismLimitor bulkLoadParallelismLimitor;
ParallelismLimitor bulkLoadEngineParallelismLimitor;
std::string bulkLoadFolder;
Optional<DDBulkLoadJobManager> bulkLoadJobManager;
bool bulkDumpEnabled = false;
ParallelismLimitor bulkDumpParallelismLimitor;
std::string folder;
std::string bulkDumpFolder;
DDBulkDumpJobManager bulkDumpJobManager;
DataDistributor(Reference<AsyncVar<ServerDBInfo> const> const& db,
UID id,
Reference<DDSharedContext> context,
std::string folder)
: dbInfo(db), context(context), ddId(id), txnProcessor(nullptr), lock(context->lock),
configuration(context->configuration), initialDDEventHolder(makeReference<EventCacheHolder>("InitialDD")),
movingDataEventHolder(makeReference<EventCacheHolder>("MovingData")),
totalDataInFlightEventHolder(makeReference<EventCacheHolder>("TotalDataInFlight")),
totalDataInFlightRemoteEventHolder(makeReference<EventCacheHolder>("TotalDataInFlightRemote")),
teamCollection(nullptr), bulkLoadTaskCollection(nullptr), auditStorageHaLaunchingLock(1),
auditStorageReplicaLaunchingLock(1), auditStorageLocationMetadataLaunchingLock(1),
auditStorageSsShardLaunchingLock(1), auditStorageInitStarted(false), bulkLoadActors(false),
bulkLoadEnabled(false), bulkLoadParallelismLimitor(SERVER_KNOBS->DD_BULKLOAD_PARALLELISM),
bulkLoadEngineParallelismLimitor(SERVER_KNOBS->DD_BULKLOAD_PARALLELISM), bulkDumpEnabled(false),
bulkDumpParallelismLimitor(SERVER_KNOBS->DD_BULKDUMP_PARALLELISM), folder(folder) {
if (!folder.empty()) {
bulkDumpFolder = abspath(joinPath(folder, ddServerBulkDumpFolder));
// TODO(BulkDump): clear this folder in the presence of crash
bulkLoadFolder = abspath(joinPath(folder, ddServerBulkLoadFolder));
// TODO(BulkLoad): clear this folder in the presence of crash
}
}
// bootstrap steps
Future<Void> takeMoveKeysLock() { return store(lock, txnProcessor->takeMoveKeysLock(ddId)); }
Future<Void> loadDatabaseConfiguration() { return store(configuration, txnProcessor->getDatabaseConfiguration()); }
Future<Void> updateReplicaKeys() {
return txnProcessor->updateReplicaKeys(primaryDcId, remoteDcIds, configuration);
}
Future<Void> loadInitialDataDistribution() {
return store(initData,
txnProcessor->getInitialDataDistribution(
ddId,
lock,
configuration.usableRegions > 1 ? remoteDcIds : std::vector<Optional<Key>>(),
context->ddEnabledState.get(),
SkipDDModeCheck::False));
}
void initDcInfo() {
primaryDcId.clear();
remoteDcIds.clear();
const std::vector<RegionInfo>& regions = configuration.regions;
if (!configuration.regions.empty()) {
primaryDcId.push_back(regions[0].dcId);
}
if (configuration.regions.size() > 1) {
remoteDcIds.push_back(regions[1].dcId);
}
}
Future<Void> waitDataDistributorEnabled() const {
return txnProcessor->waitForDataDistributionEnabled(context->ddEnabledState.get());
}
// Resume in-memory audit instances and issue background audit metadata cleanup
void resumeAuditStorage(Reference<DataDistributor> self, std::vector<AuditStorageState> auditStates) {
for (const auto& auditState : auditStates) {
if (auditState.getPhase() != AuditPhase::Running) {
TraceEvent(g_network->isSimulated() ? SevError : SevWarnAlways, "WrongAuditStateToResume")
.detail("AuditState", auditState.toString());
return;
}
if (self->audits.contains(auditState.getType()) &&
self->audits[auditState.getType()].contains(auditState.id)) {
// Ignore any RUNNING auditState with an alive audit
// instance in DD audits map
continue;
}
runAuditStorage(self, auditState, 0, DDAuditContext::RESUME);
TraceEvent(SevInfo, "AuditStorageResumed", self->ddId)
.detail("AuditID", auditState.id)
.detail("AuditType", auditState.getType())
.detail("AuditState", auditState.toString());
}
return;
}
static Future<Void> initAuditStorage(Reference<DataDistributor> self) {
self->auditStorageInitStarted = true;
MoveKeyLockInfo lockInfo;
lockInfo.myOwner = self->lock.myOwner;
lockInfo.prevOwner = self->lock.prevOwner;
lockInfo.prevWrite = self->lock.prevWrite;
std::vector<AuditStorageState> auditStatesToResume =
co_await initAuditMetadata(self->txnProcessor->context(),
lockInfo,
self->context->isDDEnabled(),
self->ddId,
SERVER_KNOBS->PERSIST_FINISH_AUDIT_COUNT);
self->resumeAuditStorage(self, auditStatesToResume);
self->auditStorageInitialized.send(Void());
}
static Future<Void> waitUntilDataDistributorExitSecurityMode(Reference<DataDistributor> self) {
Transaction tr(self->txnProcessor->context());
while (true) {
co_await delay(SERVER_KNOBS->DD_ENABLED_CHECK_DELAY, TaskPriority::DataDistribution);
tr.setOption(FDBTransactionOptions::READ_LOCK_AWARE);
tr.setOption(FDBTransactionOptions::READ_SYSTEM_KEYS);
tr.setOption(FDBTransactionOptions::PRIORITY_SYSTEM_IMMEDIATE);
Error err;
try {
Optional<Value> mode = co_await tr.get(dataDistributionModeKey);
if (!mode.present()) {
co_return;
}
BinaryReader rd(mode.get(), Unversioned());
int ddMode = 1;
rd >> ddMode;
if (ddMode != 2) {
co_return;
}
co_await checkMoveKeysLockReadOnly(&tr, self->context->lock, self->context->ddEnabledState.get());
tr.reset();
continue;
} catch (Error& e) {
err = e;
}
co_await tr.onError(err);
}
}
// Initialize the required internal states of DataDistributor from system metadata. It's necessary before
// DataDistributor start working. Doesn't include initialization of optional components, like DDQueue,
// Tracker, TeamCollection. The components should call its own ::init methods.
//
// DD Startup Progress (trace events in order):
// DDInitRunning - DD process recruited and starting init
// DDInitTakingMoveKeysLock - Acquiring move keys lock
// DDInitTookMoveKeysLock - Lock acquired
// DDInitGotConfiguration - Database configuration loaded
// DDInitUpdatedReplicaKeys - Replica keys updated
// DDInitSlowDataMoveRead - (SevWarn) dataMoveKeys read taking >5s
// DDInitServerListAndDataMoveReadComplete - Server list + data moves read: NumDataMoves, NumServers,
// ElapsedSeconds
// DDInitKeyServerScanProgress - (every 30s) keyServer scan: BeginKey, Batches, ShardsScanned
// DDInitKeyServerScanComplete - keyServer scan done: NumShards, ElapsedSeconds
// DDInitGotInitialDD - Init data loaded: NumShards, NumServers
// DDInitDataLoaded - Init data loaded, ElapsedSeconds (does NOT mean DD is fully operational)
//
// After init(), the following startup events fire from other components:
// DDInitResumeDataMovesProgress - (every 30s) data move resume: ValidMoves, CancelledMoves, EmptyMoves
// DDInitResumedDataMoves - Data move resume complete with counts
// TrackInitialShards - Shard tracker setup started with InitialShardCount
// TrackInitialShardsComplete - Shard trackers created: ShardsTracked
// DDTrackerStarting - Teams ready (fires from DDTeamCollection after readyToStart + delay)
// TrackInitialShardsMetricsComplete - All shard metrics received: ElapsedSeconds
// WaitStorageMetricsHandleError may fire (SevWarn after 60s) if a
// shard's metrics read is stuck retrying: Keys, Retries
// DDInitDone - DD is fully operational with all shard sizes loaded
static Future<Void> init(Reference<DataDistributor> self) {
while (true) {
co_await self->waitDataDistributorEnabled();
TraceEvent("DataDistributionEnabled").log();
TraceEvent("DDInitTakingMoveKeysLock", self->ddId).log();
co_await self->takeMoveKeysLock();
TraceEvent("DDInitTookMoveKeysLock", self->ddId).log();
// AuditStorage does not rely on DatabaseConfiguration
// AuditStorage read necessary info purely from system key space
if (!self->auditStorageInitStarted) {
// AuditStorage currently does not support DDMockTxnProcessor
if (!self->txnProcessor->isMocked()) {
// Avoid multiple initAuditStorages
self->addActor.send(self->initAuditStorage(self));
}
}
// It is possible that an audit request arrives and then DDMode
// is set to 2 at this point
// No polling MoveKeyLock is running
// So, we need to check MoveKeyLock when waitUntilDataDistributorExitSecurityMode
if (!self->txnProcessor->isMocked()) {
// AuditStorage currently does not support DDMockTxnProcessor
co_await waitUntilDataDistributorExitSecurityMode(self); // Trap DDMode == 2
}
// It is possible DDMode begins with 2 and passes
// waitDataDistributorEnabled and then set to 0 before
// waitUntilDataDistributorExitSecurityMode. For this case,
// after waitUntilDataDistributorExitSecurityMode, DDMode is 0.
// The init loop does not break and the loop will stuct at
// waitDataDistributorEnabled in the next iteration.
TraceEvent("DataDistributorExitSecurityMode").log();
co_await self->loadDatabaseConfiguration();
self->initDcInfo();
TraceEvent("DDInitGotConfiguration", self->ddId)
.setMaxFieldLength(-1)
.detail("Conf", self->configuration.toString());
if (self->configuration.storageServerStoreType == KeyValueStoreType::SSD_SHARDED_ROCKSDB &&
!SERVER_KNOBS->SHARD_ENCODE_LOCATION_METADATA) {
TraceEvent(SevError, "PhysicalShardNotEnabledForShardedRocks", self->ddId)
.detail("EnableServerKnob", "SHARD_ENCODE_LOCATION_METADATA");
throw internal_error();
}
co_await self->updateReplicaKeys();
TraceEvent("DDInitUpdatedReplicaKeys", self->ddId).log();
co_await self->loadInitialDataDistribution();
if (self->initData->shards.size() > 1) {
TraceEvent("DDInitGotInitialDD", self->ddId)
.detail("B", self->initData->shards.end()[-2].key)
.detail("E", self->initData->shards.end()[-1].key)
.detail("Src", describe(self->initData->shards.end()[-2].primarySrc))
.detail("Dest", describe(self->initData->shards.end()[-2].primaryDest))
.detail("NumShards", self->initData->shards.size())
.detail("NumServers", self->initData->allServers.size())
.trackLatest(self->initialDDEventHolder->trackingKey);
} else {
TraceEvent("DDInitGotInitialDD", self->ddId)
.detail("B", "")
.detail("E", "")
.detail("Src", "[no items]")
.detail("Dest", "[no items]")
.detail("NumShards", self->initData->shards.size())
.detail("NumServers", self->initData->allServers.size())
.trackLatest(self->initialDDEventHolder->trackingKey);
}
if (self->initData->mode == 1 && self->context->isDDEnabled()) {
// mode may be set true by system operator using fdbcli and isEnabled() set to true
TraceEvent("DataDistributionInitComplete", self->ddId).log();
break;
}
TraceEvent("DataDistributionDisabled", self->ddId)
.detail("Mode", self->initData->mode)
.detail("Enabled", self->context->isDDEnabled());
TraceEvent("MovingData", self->ddId)
.detail("InFlight", 0)
.detail("InQueue", 0)
.detail("AverageShardSize", -1)
.detail("UnhealthyRelocations", 0)
.detail("HighestPriority", 0)
.detail("BytesWritten", 0)
.detail("BytesWrittenAverageRate", 0)
.detail("PriorityRecoverMove", 0)
.detail("PriorityRebalanceUnderutilizedTeam", 0)
.detail("PriorityRebalannceOverutilizedTeam", 0)
.detail("PriorityTeamHealthy", 0)
.detail("PriorityTeamContainsUndesiredServer", 0)
.detail("PriorityTeamRedundant", 0)
.detail("PriorityMergeShard", 0)
.detail("PriorityTeamUnhealthy", 0)
.detail("PriorityTeam2Left", 0)
.detail("PriorityTeam1Left", 0)
.detail("PriorityTeam0Left", 0)
.detail("PrioritySplitShard", 0)
.trackLatest(self->movingDataEventHolder->trackingKey);
TraceEvent("TotalDataInFlight", self->ddId)
.detail("Primary", true)
.detail("TotalBytes", 0)
.detail("UnhealthyServers", 0)
.detail("HighestPriority", 0)
.trackLatest(self->totalDataInFlightEventHolder->trackingKey);
TraceEvent("TotalDataInFlight", self->ddId)
.detail("Primary", false)
.detail("TotalBytes", 0)
.detail("UnhealthyServers", 0)
.detail("HighestPriority", self->configuration.usableRegions > 1 ? 0 : -1)
.trackLatest(self->totalDataInFlightRemoteEventHolder->trackingKey);
}
}
static Future<Void> removeDataMoveTombstoneBackground(Reference<DataDistributor> self) {
static auto* counters = makeCounters("/dd/removeDataMoveTombstone");
UID currentID;
try {
Database cx = openDBOnServer(self->dbInfo, TaskPriority::DefaultEndpoint, LockAware::True);
Transaction tr(cx);
while (true) {
counters->started->increment(1);
Error err;
try {
tr.setOption(FDBTransactionOptions::ACCESS_SYSTEM_KEYS);
tr.setOption(FDBTransactionOptions::PRIORITY_SYSTEM_IMMEDIATE);
for (UID& dataMoveID : self->initData->toCleanDataMoveTombstone) {
currentID = dataMoveID;
tr.clear(dataMoveKeyFor(currentID));
TraceEvent(SevDebug, "RemoveDataMoveTombstone", self->ddId).detail("DataMoveID", currentID);
}
co_await tr.commit();
counters->committed->increment(1);
break;
} catch (Error& e) {
counters->aborted->increment(1);
err = e;
}
co_await tr.onError(err);
}
} catch (Error& e) {
if (e.code() == error_code_actor_cancelled) {
throw;
}
TraceEvent(SevWarn, "RemoveDataMoveTombstoneError", self->ddId)
.errorUnsuppressed(e)
.detail("CurrentDataMoveID", currentID);
// DD needs not restart when removing tombstone gets failed unless this actor gets cancelled
// So, do not throw error
}
}
static Future<Void> resumeFromShards(Reference<DataDistributor> self, bool traceShard) {
// All physicalShard init must be completed before issuing data move
if (SERVER_KNOBS->SHARD_ENCODE_LOCATION_METADATA && SERVER_KNOBS->ENABLE_DD_PHYSICAL_SHARD) {
for (int i = 0; i < self->initData->shards.size() - 1; i++) {
const DDShardInfo& iShard = self->initData->shards[i];
KeyRangeRef keys = KeyRangeRef(iShard.key, self->initData->shards[i + 1].key);
std::vector<ShardsAffectedByTeamFailure::Team> teams;
teams.emplace_back(iShard.primarySrc, /*primary=*/true);
if (self->configuration.usableRegions > 1) {
teams.emplace_back(iShard.remoteSrc, /*primary=*/false);
}
self->physicalShardCollection->initPhysicalShardCollection(keys, teams, iShard.srcId.first(), 0);
}
}
std::vector<Key> customBoundaries;
if (bulkLoadIsEnabled(self->initData->bulkLoadMode)) {
// Bulk load does not allow boundary change
TraceEvent(SevInfo, "DDInitCustomRangeConfigDisabledByBulkLoadMode", self->ddId);
} else {
for (auto it : self->initData->userRangeConfig->ranges()) {
auto range = it->range();
customBoundaries.push_back(range.begin);
TraceEvent(SevDebug, "DDInitCustomRangeConfig", self->ddId)
.detail("Range", KeyRangeRef(range.begin, range.end))
.detail("Config", it->value());
}
}
int shard = 0;
int customBoundary = 0;
int overreplicatedCount = 0;
for (; shard < self->initData->shards.size() - 1; shard++) {
const DDShardInfo& iShard = self->initData->shards[shard];
std::vector<KeyRangeRef> ranges;
Key beginKey = iShard.key;
Key endKey = self->initData->shards[shard + 1].key;
while (customBoundary < customBoundaries.size() && customBoundaries[customBoundary] <= beginKey) {
customBoundary++;
}
while (customBoundary < customBoundaries.size() && customBoundaries[customBoundary] < endKey) {
ranges.push_back(KeyRangeRef(beginKey, customBoundaries[customBoundary]));
beginKey = customBoundaries[customBoundary];
customBoundary++;
}
ranges.push_back(KeyRangeRef(beginKey, endKey));
std::vector<ShardsAffectedByTeamFailure::Team> teams;
teams.push_back(ShardsAffectedByTeamFailure::Team(iShard.primarySrc, true));
if (self->configuration.usableRegions > 1) {
teams.push_back(ShardsAffectedByTeamFailure::Team(iShard.remoteSrc, false));
}
for (int r = 0; r < ranges.size(); r++) {
auto& keys = ranges[r];
self->shardsAffectedByTeamFailure->defineShard(keys);
auto it = self->initData->userRangeConfig->rangeContaining(keys.begin);
int customReplicas =
std::max(self->configuration.storageTeamSize, it->value().replicationFactor.orDefault(0));
ASSERT_WE_THINK(KeyRangeRef(it->range().begin, it->range().end).contains(keys));
bool unhealthy = iShard.primarySrc.size() != customReplicas;
if (!unhealthy && self->configuration.usableRegions > 1) {
unhealthy = iShard.remoteSrc.size() != customReplicas;
}
if (!unhealthy && iShard.primarySrc.size() > self->configuration.storageTeamSize) {
if (++overreplicatedCount > SERVER_KNOBS->DD_MAX_SHARDS_ON_LARGE_TEAMS) {
unhealthy = true;
}
}
if (traceShard) {
TraceEvent(SevDebug, "DDInitShard", self->ddId)
.detail("Keys", keys)
.detail("PrimarySrc", describe(iShard.primarySrc))
.detail("RemoteSrc", describe(iShard.remoteSrc))
.detail("PrimaryDest", describe(iShard.primaryDest))
.detail("RemoteDest", describe(iShard.remoteDest))
.detail("SrcID", iShard.srcId)
.detail("DestID", iShard.destId)
.detail("CustomReplicas", customReplicas)
.detail("StorageTeamSize", self->configuration.storageTeamSize)
.detail("Unhealthy", unhealthy)
.detail("Overreplicated", overreplicatedCount);
}
self->shardsAffectedByTeamFailure->moveShard(keys, teams);
if ((ddLargeTeamEnabled() && (unhealthy || r > 0)) ||
(iShard.hasDest && iShard.destId == anonymousShardId)) {
// This shard is already in flight. Ideally we should use dest in ShardsAffectedByTeamFailure and
// generate a dataDistributionRelocator directly in DataDistributionQueue to track it, but it's
// easier to just (with low priority) schedule it for movement.
DataMovementReason reason = DataMovementReason::RECOVER_MOVE;
if (unhealthy) {
reason = DataMovementReason::TEAM_UNHEALTHY;
} else if (r > 0) {
reason = DataMovementReason::SPLIT_SHARD;
}
self->relocationProducer.send(RelocateShard(keys, reason, RelocateReason::OTHER));
}
}
co_await yield(TaskPriority::DataDistribution);
}
}
// TODO: unit test needed
static Future<Void> resumeFromDataMoves(Reference<DataDistributor> self, Future<Void> readyToStart) {
KeyRangeMap<std::shared_ptr<DataMove>>::iterator it = self->initData->dataMoveMap.ranges().begin();
int validMoves = 0;
int cancelledMoves = 0;
int emptyMoves = 0;
double resumeStart = now();
double lastLogTime = now();
co_await readyToStart;
for (; it != self->initData->dataMoveMap.ranges().end(); ++it) {
const DataMoveMetaData& meta = it.value()->meta;
DataMoveType dataMoveType = getDataMoveTypeFromDataMoveId(meta.id);
if (meta.ranges.empty()) {
TraceEvent(SevInfo, "EmptyDataMoveRange", self->ddId).detail("DataMoveMetaData", meta.toString());
emptyMoves++;
continue;
}
if (meta.bulkLoadTaskState.present()) {
RelocateShard rs(meta.ranges.front(), DataMovementReason::RECOVER_MOVE, RelocateReason::OTHER);
rs.dataMoveId = meta.id;
rs.cancelled = true;
self->relocationProducer.send(rs);
// Cancel data move for old bulk loading
// Do not assign bulk load to rs so that this is a normal data move cancellation signal
TraceEvent(SevWarnAlways, "DDBulkLoadTaskCancelDataMove", self->ddId)
.detail("Reason", "DDInit")
.detail("DataMove", meta.toString());
cancelledMoves++;
} else if (dataMoveType == DataMoveType::LOGICAL_BULKLOAD ||
dataMoveType == DataMoveType::PHYSICAL_BULKLOAD) {
// The metadata is from the old system
RelocateShard rs(meta.ranges.front(), DataMovementReason::RECOVER_MOVE, RelocateReason::OTHER);
rs.dataMoveId = meta.id;
rs.cancelled = true;