-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathFileBackupAgent.cpp
More file actions
8835 lines (7653 loc) · 353 KB
/
FileBackupAgent.cpp
File metadata and controls
8835 lines (7653 loc) · 353 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
/*
* FileBackupAgent.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/CommitProxyInterface.h"
#include "fdbclient/DatabaseConfiguration.h"
#include "fdbrpc/simulator.h"
#include "flow/EncryptUtils.h"
#include "flow/FastRef.h"
#include "flow/flow.h"
#include "fmt/format.h"
#include "fdbclient/BackupAgent.h"
#include "fdbclient/BackupContainer.h"
#include "fdbclient/BackupContainerFileSystem.h"
#include "fdbclient/BulkDumping.h"
#include "fdbclient/BulkLoading.h"
#include "fdbclient/ClientBooleanParams.h"
#include "fdbclient/DatabaseContext.h"
#include "fdbclient/FDBTypes.h"
#include "fdbclient/JsonBuilder.h"
#include "fdbclient/JSONDoc.h"
#include "fdbclient/KeyBackedTypes.h"
#include "fdbclient/KeyRangeMap.h"
#include "fdbclient/Knobs.h"
#include "fdbclient/ManagementAPI.h"
#include "PartitionedLogIterator.h"
#include "RestoreInterface.h"
#include "fdbclient/Status.h"
#include "fdbclient/SystemData.h"
#include "fdbclient/TaskBucket.h"
#include "flow/network.h"
#include "flow/Trace.h"
#include "flow/Util.h"
#include <cinttypes>
#include <cstdint>
#include <ctime>
#include <climits>
#include "flow/IAsyncFile.h"
#include "flow/genericactors.actor.h"
#include "flow/Hash3.h"
#include "flow/xxhash.h"
#include <memory>
#include <numeric>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <algorithm>
#include <unordered_map>
#include <utility>
// Counters to verify BulkDump/BulkLoad were actually used (for test assertions)
std::atomic<int> g_bulkDumpTaskCompleteCount(0);
std::atomic<int> g_bulkLoadRestoreTaskCompleteCount(0);
// Helper function to monitor BulkDump job completion
// Returns true if job completed successfully, false if timed out
Future<bool> monitorBulkDumpJobCompletion(Database cx, UID jobId, double timeoutDuration, double pollInterval) {
double timeoutStart = now();
Transaction tr(cx);
while (true) {
Error err;
try {
Optional<BulkDumpState> currentJob = co_await getSubmittedBulkDumpJob(&tr);
bool stillRunning = currentJob.present() && currentJob.get().getJobId() == jobId;
if (!stillRunning) {
co_return true; // Job completed successfully
}
if (now() - timeoutStart > timeoutDuration) {
co_return false; // Timed out
}
co_await delay(pollInterval);
tr.reset();
continue;
} catch (Error& e) {
err = e;
}
co_await tr.onError(err);
}
}
// Verify that a complete BulkDump dataset exists for BulkLoad restore
// Returns true if dataset is complete, false if incomplete
// JobId corresponds to a single BulkDump job which represents one snapshot at a specific version
Future<bool> verifyBulkDumpDatasetCompleteness(Reference<IBackupContainer> bc, std::string bulkDumpJobId) {
try {
if (bulkDumpJobId.empty()) {
TraceEvent(SevWarn, "BulkLoadVerifyDatasetEmptyJobId");
co_return false;
}
// Check if job-specific directory exists: bulkdump_data/<job-uuid>/
// BulkDump stores data under data/<container>/bulkdump_data/ via getBackupDataPath(),
// which is consistent with where BackupContainer stores other files (logs, ranges, etc.)
std::string jobDirectoryPath = "bulkdump_data/" + bulkDumpJobId + "/";
Error err;
try {
// Try to list files in the job directory to verify it exists and has content
Reference<BackupContainerFileSystem> bcfs = bc.castTo<BackupContainerFileSystem>();
if (bcfs) {
// Standard listFiles works because BulkDump now writes under data/<container>/
BackupContainerFileSystem::FilesAndSizesT files = co_await bcfs->listFiles(jobDirectoryPath);
if (files.empty()) {
TraceEvent(SevWarn, "BulkLoadVerifyDatasetJobDirectoryEmpty")
.detail("JobDirectoryPath", jobDirectoryPath)
.detail("BulkDumpJobId", bulkDumpJobId);
co_return false;
}
TraceEvent("BulkLoadVerifyDatasetJobDirectoryFound")
.detail("JobDirectoryPath", jobDirectoryPath)
.detail("BulkDumpJobId", bulkDumpJobId)
.detail("FileCount", files.size());
// Basic verification: job directory exists and contains files
// More detailed verification (parsing shard manifests) is delegated to BulkLoad system
co_return true;
} else {
// Cannot verify - backup container doesn't support file listing
// Use SevWarn (not SevError) to avoid abort in simulation
TraceEvent(SevWarn, "BulkLoadVerifyDatasetCannotCast")
.detail("BulkDumpJobId", bulkDumpJobId)
.detail("Note", "BackupContainer does not support file listing required for verification");
co_return false;
}
} catch (Error& e) {
if (e.code() == error_code_file_not_found) {
TraceEvent(SevWarn, "BulkLoadVerifyDatasetJobDirectoryNotFound")
.detail("JobDirectoryPath", jobDirectoryPath)
.detail("BulkDumpJobId", bulkDumpJobId);
co_return false;
}
throw;
}
} catch (Error& e) {
TraceEvent(SevWarn, "BulkLoadVerifyDatasetError").error(e).detail("BulkDumpJobId", bulkDumpJobId);
co_return false;
}
}
// Note: BulkLoad configuration validation (shard_encode_location_metadata, enable_read_lock_on_range)
// is performed by the BulkLoad system on the server side. Client-side validation is not possible
// because SERVER_KNOBS are not accessible from fdbclient.
Optional<std::string> fileBackupAgentProxy = Optional<std::string>();
#define SevFRTestInfo SevVerbose
// #define SevFRTestInfo SevInfo
static std::string boolToYesOrNo(bool val) {
return val ? std::string("Yes") : std::string("No");
}
static std::string versionToString(Optional<Version> version) {
if (version.present())
return std::to_string(version.get());
else
return "N/A";
}
static std::string timeStampToString(Optional<int64_t> epochs) {
if (!epochs.present())
return "N/A";
return BackupAgentBase::formatTime(epochs.get());
}
static Future<Optional<int64_t>> getTimestampFromVersion(Optional<Version> ver,
Reference<ReadYourWritesTransaction> tr) {
if (!ver.present())
return Optional<int64_t>();
return timeKeeperEpochsFromVersion(ver.get(), tr);
}
// Time format :
// <= 59 seconds
// <= 59.99 minutes
// <= 23.99 hours
// N.NN days
std::string secondsToTimeFormat(int64_t seconds) {
if (seconds >= 86400)
return format("%.2f day(s)", seconds / 86400.0);
else if (seconds >= 3600)
return format("%.2f hour(s)", seconds / 3600.0);
else if (seconds >= 60)
return format("%.2f minute(s)", seconds / 60.0);
else
return format("%lld second(s)", seconds);
}
const Key FileBackupAgent::keyLastRestorable = "last_restorable"_sr;
// For convenience
using ERestoreState = FileBackupAgent::ERestoreState;
StringRef FileBackupAgent::restoreStateText(ERestoreState id) {
switch (id) {
case ERestoreState::UNINITIALIZED:
return "uninitialized"_sr;
case ERestoreState::QUEUED:
return "queued"_sr;
case ERestoreState::STARTING:
return "starting"_sr;
case ERestoreState::RUNNING:
return "running"_sr;
case ERestoreState::COMPLETED:
return "completed"_sr;
case ERestoreState::ABORTED:
return "aborted"_sr;
default:
return "Unknown"_sr;
}
}
Key FileBackupAgent::getPauseKey() {
FileBackupAgent backupAgent;
return backupAgent.taskBucket->getPauseKey();
}
Future<std::vector<KeyBackedTag>> TagUidMap::getAll_impl(TagUidMap* tagsMap,
Reference<ReadYourWritesTransaction> tr,
Snapshot snapshot) {
Key prefix = tagsMap->prefix; // Copying it here as tagsMap lifetime is not tied to this actor
TagMap::RangeResultType tagPairs = co_await tagsMap->getRange(tr, std::string(), {}, 1e6, snapshot);
std::vector<KeyBackedTag> results;
for (auto& p : tagPairs.results)
results.push_back(KeyBackedTag(p.first, prefix));
co_return results;
}
KeyBackedTag::KeyBackedTag(std::string tagName, StringRef tagMapPrefix)
: KeyBackedProperty<UidAndAbortedFlagT>(TagUidMap(tagMapPrefix).getProperty(tagName)), tagName(tagName),
tagMapPrefix(tagMapPrefix) {}
// Lists all backups and find if any partitioned backup is running.
Future<bool> anyPartitionedBackupRunning(Reference<ReadYourWritesTransaction> tr) {
tr->setOption(FDBTransactionOptions::ACCESS_SYSTEM_KEYS);
tr->setOption(FDBTransactionOptions::LOCK_AWARE);
std::vector<KeyBackedTag> tags = co_await getAllBackupTags(tr);
std::vector<Future<Optional<UidAndAbortedFlagT>>> futures;
for (const auto& tag : tags) {
futures.push_back(tag.get(tr));
}
co_await waitForAll(futures);
int i = 0;
for (i = 0; i < futures.size(); i++) {
if (futures[i].get().present()) {
Optional<MutationLogType> mutationLogType;
EBackupState eState;
BackupConfig config(futures[i].get().get().first);
co_await (store(eState, config.stateEnum().getD(tr, Snapshot::False, EBackupState::STATE_NEVERRAN)) &&
store(mutationLogType, config.mutationLogType().get(tr)));
if (FileBackupAgent::isRunnable(eState) &&
mutationLogType.orDefault(MutationLogType::DEFAULT) == MutationLogType::PARTITIONED_LOG) {
co_return true;
}
}
}
co_return false;
}
// Lists all backups and find if any range-partitioned backup is running.
Future<bool> anyRangePartitionedBackupRunning(Reference<ReadYourWritesTransaction> tr) {
tr->setOption(FDBTransactionOptions::ACCESS_SYSTEM_KEYS);
tr->setOption(FDBTransactionOptions::LOCK_AWARE);
std::vector<KeyBackedTag> tags = co_await getAllBackupTags(tr);
std::vector<Future<Optional<UidAndAbortedFlagT>>> futures;
for (const auto& tag : tags) {
futures.push_back(tag.get(tr));
}
co_await waitForAll(futures);
int i = 0;
for (i = 0; i < futures.size(); i++) {
if (futures[i].get().present()) {
Optional<MutationLogType> mutationLogType;
EBackupState eState;
BackupConfig config(futures[i].get().get().first);
co_await (store(eState, config.stateEnum().getD(tr, Snapshot::False, EBackupState::STATE_NEVERRAN)) &&
store(mutationLogType, config.mutationLogType().get(tr)));
if (FileBackupAgent::isRunnable(eState) &&
mutationLogType.orDefault(MutationLogType::DEFAULT) == MutationLogType::RANGE_PARTITIONED_LOG) {
co_return true;
}
}
}
co_return false;
}
class RestoreConfig : public KeyBackedTaskConfig {
public:
explicit RestoreConfig(UID uid = UID()) : KeyBackedTaskConfig(fileRestorePrefixRange.begin, uid) {}
explicit RestoreConfig(Reference<Task> task) : KeyBackedTaskConfig(fileRestorePrefixRange.begin, task) {}
KeyBackedProperty<ERestoreState> stateEnum() { return configSpace.pack(__FUNCTION__sr); }
Future<StringRef> stateText(Reference<ReadYourWritesTransaction> tr) {
return map(stateEnum().getD(tr),
[](ERestoreState s) -> StringRef { return FileBackupAgent::restoreStateText(s); });
}
KeyBackedProperty<Key> addPrefix() { return configSpace.pack(__FUNCTION__sr); }
KeyBackedProperty<Key> removePrefix() { return configSpace.pack(__FUNCTION__sr); }
KeyBackedProperty<bool> onlyApplyMutationLogs() { return configSpace.pack(__FUNCTION__sr); }
KeyBackedProperty<bool> inconsistentSnapshotOnly() { return configSpace.pack(__FUNCTION__sr); }
KeyBackedProperty<bool> unlockDBAfterRestore() { return configSpace.pack(__FUNCTION__sr); }
KeyBackedProperty<MutationLogType> mutationLogType() { return configSpace.pack(__FUNCTION__sr); }
// BulkLoad integration properties
KeyBackedProperty<bool> useRangeFileRestore() { return configSpace.pack(__FUNCTION__sr); }
KeyBackedProperty<std::string> bulkDumpJobId() { return configSpace.pack(__FUNCTION__sr); }
KeyBackedProperty<Key> bulkLoadCompleteFuture() { return configSpace.pack(__FUNCTION__sr); }
KeyBackedProperty<bool> bulkLoadComplete() { return configSpace.pack(__FUNCTION__sr); }
// Original BulkLoad mode before restore enabled it - used to restore state after completion/crash
KeyBackedProperty<int> originalBulkLoadMode() { return configSpace.pack(__FUNCTION__sr); }
// XXX: Remove restoreRange() once it is safe to remove. It has been changed to restoreRanges
KeyBackedProperty<KeyRange> restoreRange() { return configSpace.pack(__FUNCTION__sr); }
// XXX: Changed to restoreRangeSet. It can be removed.
KeyBackedProperty<std::vector<KeyRange>> restoreRanges() { return configSpace.pack(__FUNCTION__sr); }
KeyBackedSet<KeyRange> restoreRangeSet() { return configSpace.pack(__FUNCTION__sr); }
KeyBackedProperty<Key> batchFuture() { return configSpace.pack(__FUNCTION__sr); }
KeyBackedProperty<Version> beginVersion() { return configSpace.pack(__FUNCTION__sr); }
KeyBackedProperty<Version> restoreVersion() { return configSpace.pack(__FUNCTION__sr); }
KeyBackedProperty<Version> firstConsistentVersion() { return configSpace.pack(__FUNCTION__sr); }
KeyBackedProperty<Reference<IBackupContainer>> sourceContainer() { return configSpace.pack(__FUNCTION__sr); }
// Get the source container as a bare URL, without creating a container instance
KeyBackedProperty<Value> sourceContainerURL() { return configSpace.pack("sourceContainer"_sr); }
// Total bytes written by all log and range restore tasks.
KeyBackedBinaryValue<int64_t> bytesWritten() { return configSpace.pack(__FUNCTION__sr); }
// File blocks that have had tasks created for them by the Dispatch task
KeyBackedBinaryValue<int64_t> filesBlocksDispatched() { return configSpace.pack(__FUNCTION__sr); }
// File blocks whose tasks have finished
KeyBackedBinaryValue<int64_t> fileBlocksFinished() { return configSpace.pack(__FUNCTION__sr); }
// Total number of files in the fileMap
KeyBackedBinaryValue<int64_t> fileCount() { return configSpace.pack(__FUNCTION__sr); }
// Total number of file blocks in the fileMap
KeyBackedBinaryValue<int64_t> fileBlockCount() { return configSpace.pack(__FUNCTION__sr); }
// BulkLoad sub-phase task counts for detailed progress tracking
KeyBackedBinaryValue<int64_t> bulkLoadSubmittedTasks() { return configSpace.pack(__FUNCTION__sr); }
KeyBackedBinaryValue<int64_t> bulkLoadTriggeredTasks() { return configSpace.pack(__FUNCTION__sr); }
KeyBackedBinaryValue<int64_t> bulkLoadRunningTasks() { return configSpace.pack(__FUNCTION__sr); }
KeyBackedBinaryValue<int64_t> bulkLoadTotalTasks() { return configSpace.pack(__FUNCTION__sr); }
Future<std::vector<KeyRange>> getRestoreRangesOrDefault(Reference<ReadYourWritesTransaction> tr) {
return getRestoreRangesOrDefault_impl(this, tr);
}
static Future<std::vector<KeyRange>> getRestoreRangesOrDefault_impl(RestoreConfig* self,
Reference<ReadYourWritesTransaction> tr) {
std::vector<KeyRange> ranges;
int batchSize = buggify() ? 1 : CLIENT_KNOBS->RESTORE_RANGES_READ_BATCH;
Optional<KeyRange> begin;
Arena arena;
while (true) {
KeyBackedSet<KeyRange>::RangeResultType rangeResult =
co_await self->restoreRangeSet().getRange(tr, begin, {}, batchSize);
ranges.insert(ranges.end(), rangeResult.results.begin(), rangeResult.results.end());
if (!rangeResult.more) {
break;
}
ASSERT(!rangeResult.results.empty());
begin = KeyRangeRef(KeyRef(arena, ranges.back().begin), keyAfter(ranges.back().end, arena));
}
// fall back to original fields if the new field is empty
if (ranges.empty()) {
std::vector<KeyRange> _ranges = co_await self->restoreRanges().getD(tr);
ranges = _ranges;
if (ranges.empty()) {
KeyRange range = co_await self->restoreRange().getD(tr);
ranges.push_back(range);
}
}
co_return ranges;
}
// Describes a file to load blocks from during restore. Ordered by version and then fileName to enable
// incrementally advancing through the map, saving the version and path of the next starting point.
struct RestoreFile {
Version version; // this is beginVersion, not endVersion
std::string fileName;
bool isRange{ false }; // false for log file
int64_t blockSize{ 0 };
int64_t fileSize{ 0 };
Version endVersion{ ::invalidVersion }; // not meaningful for range files
int64_t tagId = -1; // only meaningful to log files, Log router tag. Non-negative for new backup format.
int64_t totalTags = -1; // only meaningful to log files, Total number of log router tags.
Tuple pack() const {
return Tuple::makeTuple(
version, fileName, (int64_t)isRange, fileSize, blockSize, endVersion, tagId, totalTags);
}
static RestoreFile unpack(Tuple const& t) {
RestoreFile r;
int i = 0;
r.version = t.getInt(i++);
r.fileName = t.getString(i++).toString();
r.isRange = t.getInt(i++) != 0;
r.fileSize = t.getInt(i++);
r.blockSize = t.getInt(i++);
r.endVersion = t.getInt(i++);
r.tagId = t.getInt(i++);
r.totalTags = t.getInt(i++);
return r;
}
};
using FileSetT = KeyBackedSet<RestoreFile>;
FileSetT fileSet() { return configSpace.pack(__FUNCTION__sr); }
FileSetT logFileSet() { return configSpace.pack(__FUNCTION__sr); }
FileSetT rangeFileSet() { return configSpace.pack(__FUNCTION__sr); }
Future<bool> isRunnable(Reference<ReadYourWritesTransaction> tr) {
return map(stateEnum().getD(tr), [](ERestoreState s) -> bool {
return s != ERestoreState::ABORTED && s != ERestoreState::COMPLETED && s != ERestoreState::UNINITIALIZED;
});
}
Future<Void> logError(Database cx, Error e, std::string const& details, void* taskInstance = nullptr) {
if (!uid.isValid()) {
TraceEvent(SevError, "FileRestoreErrorNoUID").error(e).detail("Description", details);
return Void();
}
TraceEvent t(SevWarn, "FileRestoreError");
t.error(e)
.detail("RestoreUID", uid)
.detail("Description", details)
.detail("TaskInstance", (uint64_t)taskInstance);
// key_not_found could happen
if (e.code() == error_code_key_not_found)
t.backtrace();
return updateErrorInfo(cx, e, details);
}
Key mutationLogPrefix() { return uidPrefixKey(applyLogKeys.begin, uid); }
Key applyMutationsMapPrefix() { return uidPrefixKey(applyMutationsKeyVersionMapRange.begin, uid); }
static Future<int64_t> getApplyVersionLag_impl(Reference<ReadYourWritesTransaction> tr, UID uid) {
Future<Optional<Value>> beginVal = tr->get(uidPrefixKey(applyMutationsBeginRange.begin, uid), Snapshot::True);
Future<Optional<Value>> endVal = tr->get(uidPrefixKey(applyMutationsEndRange.begin, uid), Snapshot::True);
co_await (success(beginVal) && success(endVal));
if (!beginVal.get().present() || !endVal.get().present())
co_return 0;
Version beginVersion = BinaryReader::fromStringRef<Version>(beginVal.get().get(), Unversioned());
Version endVersion = BinaryReader::fromStringRef<Version>(endVal.get().get(), Unversioned());
co_return endVersion - beginVersion;
}
Future<int64_t> getApplyVersionLag(Reference<ReadYourWritesTransaction> tr) {
return getApplyVersionLag_impl(tr, uid);
}
void initApplyMutations(Reference<ReadYourWritesTransaction> tr,
Key addPrefix,
Key removePrefix,
OnlyApplyMutationLogs onlyApplyMutationLogs) {
// Set these because they have to match the applyMutations values.
this->addPrefix().set(tr, addPrefix);
this->removePrefix().set(tr, removePrefix);
clearApplyMutationsKeys(tr);
// Initialize add/remove prefix, range version map count and set the map's start key to InvalidVersion
tr->set(uidPrefixKey(applyMutationsAddPrefixRange.begin, uid), addPrefix);
tr->set(uidPrefixKey(applyMutationsRemovePrefixRange.begin, uid), removePrefix);
int64_t startCount = 0;
tr->set(uidPrefixKey(applyMutationsKeyVersionCountRange.begin, uid), StringRef((uint8_t*)&startCount, 8));
Key mapStart = uidPrefixKey(applyMutationsKeyVersionMapRange.begin, uid);
tr->set(mapStart, BinaryWriter::toValue<Version>(invalidVersion, Unversioned()));
}
void clearApplyMutationsKeys(Reference<ReadYourWritesTransaction> tr) {
tr->setOption(FDBTransactionOptions::COMMIT_ON_FIRST_PROXY);
// Clear add/remove prefix keys
tr->clear(uidPrefixKey(applyMutationsAddPrefixRange.begin, uid));
tr->clear(uidPrefixKey(applyMutationsRemovePrefixRange.begin, uid));
// Clear range version map and count key
tr->clear(uidPrefixKey(applyMutationsKeyVersionCountRange.begin, uid));
Key mapStart = uidPrefixKey(applyMutationsKeyVersionMapRange.begin, uid);
tr->clear(KeyRangeRef(mapStart, strinc(mapStart)));
// Clear any loaded mutations that have not yet been applied
Key mutationPrefix = mutationLogPrefix();
tr->clear(KeyRangeRef(mutationPrefix, strinc(mutationPrefix)));
// Clear end and begin versions (intentionally in this order)
tr->clear(uidPrefixKey(applyMutationsEndRange.begin, uid));
tr->clear(uidPrefixKey(applyMutationsBeginRange.begin, uid));
}
void setApplyBeginVersion(Reference<ReadYourWritesTransaction> tr, Version ver) {
tr->set(uidPrefixKey(applyMutationsBeginRange.begin, uid), BinaryWriter::toValue(ver, Unversioned()));
}
Future<Version> getApplyBeginVersion(Reference<ReadYourWritesTransaction> tr) {
return map(tr->get(uidPrefixKey(applyMutationsBeginRange.begin, uid)),
[=](Optional<Value> const& value) -> Version {
return value.present() ? BinaryReader::fromStringRef<Version>(value.get(), Unversioned()) : 0;
});
}
void setApplyEndVersion(Reference<ReadYourWritesTransaction> tr, Version ver) {
tr->set(uidPrefixKey(applyMutationsEndRange.begin, uid), BinaryWriter::toValue(ver, Unversioned()));
}
Future<Version> getApplyEndVersion(Reference<ReadYourWritesTransaction> tr) {
return map(tr->get(uidPrefixKey(applyMutationsEndRange.begin, uid)),
[=](Optional<Value> const& value) -> Version {
return value.present() ? BinaryReader::fromStringRef<Version>(value.get(), Unversioned()) : 0;
});
}
static Future<Version> getCurrentVersion_impl(RestoreConfig* self, Reference<ReadYourWritesTransaction> tr) {
ERestoreState status = co_await self->stateEnum().getD(tr);
Version version = -1;
if (status == ERestoreState::RUNNING) {
version = co_await self->getApplyBeginVersion(tr);
} else if (status == ERestoreState::COMPLETED) {
version = co_await self->restoreVersion().getD(tr);
}
co_return version;
}
Future<Version> getCurrentVersion(Reference<ReadYourWritesTransaction> tr) {
return getCurrentVersion_impl(this, tr);
}
static Future<std::string> getProgress_impl(RestoreConfig restore, Reference<ReadYourWritesTransaction> tr);
Future<std::string> getProgress(Reference<ReadYourWritesTransaction> tr) { return getProgress_impl(*this, tr); }
static Future<std::string> getFullStatus_impl(RestoreConfig restore, Reference<ReadYourWritesTransaction> tr);
Future<std::string> getFullStatus(Reference<ReadYourWritesTransaction> tr) { return getFullStatus_impl(*this, tr); }
};
using RestoreFile = RestoreConfig::RestoreFile;
// Helper to count bulkload task progress for a job
// Returns: <completedTasks, submittedTasks, triggeredTasks, runningTasks, totalTasks, completedBytes>
// Sub-phases help track progress during the long "running" period:
// - Submitted: task created, waiting to be picked up by DD
// - Triggered: assigned to storage server, waiting to start
// - Running: storage server actively downloading/ingesting SST files
Future<std::tuple<int64_t, int64_t, int64_t, int64_t, int64_t, int64_t>> getBulkLoadTaskProgress(Database cx,
UID jobId) {
Transaction tr(cx);
Key readBegin = normalKeys.begin;
Key readEnd = normalKeys.end;
int64_t completedTasks = 0;
int64_t submittedTasks = 0;
int64_t triggeredTasks = 0;
int64_t runningTasks = 0;
int64_t totalTasks = 0;
int64_t completedBytes = 0;
while (readBegin < readEnd) {
Error err;
try {
tr.setOption(FDBTransactionOptions::READ_SYSTEM_KEYS);
tr.setOption(FDBTransactionOptions::LOCK_AWARE);
RangeResult rangeResult = co_await krmGetRanges(&tr, bulkLoadTaskPrefix, KeyRangeRef(readBegin, readEnd));
if (rangeResult.empty()) {
break;
}
for (int i = 0; i < static_cast<int>(rangeResult.size()) - 1; ++i) {
if (rangeResult[i].value.empty()) {
continue;
}
BulkLoadTaskState task = decodeBulkLoadTaskState(rangeResult[i].value);
if (task.getJobId() != jobId) {
// Different job, stop counting
co_return std::make_tuple(
completedTasks, submittedTasks, triggeredTasks, runningTasks, totalTasks, completedBytes);
}
int manifestCount = task.getManifests().size();
totalTasks += manifestCount;
if (task.phase == BulkLoadPhase::Complete) {
completedTasks += manifestCount;
// Sum bytes from manifest data sizes
for (const auto& manifest : task.getManifests()) {
completedBytes += manifest.getTotalBytes();
}
} else if (task.phase == BulkLoadPhase::Submitted) {
submittedTasks += manifestCount;
} else if (task.phase == BulkLoadPhase::Triggered) {
triggeredTasks += manifestCount;
} else if (task.phase == BulkLoadPhase::Running) {
runningTasks += manifestCount;
}
}
readBegin = rangeResult.back().key;
} catch (Error& e) {
err = e;
}
if (err.isValid() && err.code() != error_code_success) {
TraceEvent(SevWarn, "BulkLoadTaskProgressRetry").error(err).detail("JobId", jobId);
co_await tr.onError(err);
}
}
co_return std::make_tuple(completedTasks, submittedTasks, triggeredTasks, runningTasks, totalTasks, completedBytes);
}
// Monitor BulkLoad job completion and update restore progress counters
// restoreUid is used to update the RestoreConfig progress
Future<bool> monitorBulkLoadJobCompletionWithProgress(Database cx,
UID jobId,
UID restoreUid,
int64_t totalBlocks,
double timeoutDuration,
double pollInterval,
bool lockAware) {
double timeoutStart = now();
RestoreConfig restore(restoreUid);
while (true) {
Optional<BulkLoadJobState> currentJob = co_await getRunningBulkLoadJob(cx, lockAware);
bool stillRunning = currentJob.present() && currentJob.get().getJobId() == jobId;
if (!stillRunning) {
co_return true;
}
// Update progress based on completed bulkload tasks
try {
auto [completed, submitted, triggered, running, total, bytes] = co_await getBulkLoadTaskProgress(cx, jobId);
if (total > 0) {
// For bulkload restores, fileBlockCount is 0, so use task count as "blocks"
// This provides meaningful progress tracking for the restore status display
// Include all in-progress tasks in dispatched count to show scheduling progress
int64_t inProgress = submitted + triggered + running;
int64_t effectiveTotalBlocks = totalBlocks > 0 ? totalBlocks : total;
int64_t blocksFinished = totalBlocks > 0 ? (totalBlocks * completed) / total : completed;
int64_t blocksDispatched =
totalBlocks > 0 ? (totalBlocks * (completed + inProgress)) / total : (completed + inProgress);
Reference<ReadYourWritesTransaction> tr(new ReadYourWritesTransaction(cx));
tr->setOption(FDBTransactionOptions::ACCESS_SYSTEM_KEYS);
if (lockAware) {
tr->setOption(FDBTransactionOptions::LOCK_AWARE);
}
restore.fileBlocksFinished().set(tr, blocksFinished);
restore.filesBlocksDispatched().set(tr, blocksDispatched);
restore.fileBlockCount().set(tr, effectiveTotalBlocks);
restore.bytesWritten().set(tr, bytes);
// Store sub-phase counts for detailed progress display
restore.bulkLoadSubmittedTasks().set(tr, submitted);
restore.bulkLoadTriggeredTasks().set(tr, triggered);
restore.bulkLoadRunningTasks().set(tr, running);
restore.bulkLoadTotalTasks().set(tr, total);
co_await tr->commit();
TraceEvent("BulkLoadRestoreProgress")
.detail("RestoreUID", restoreUid)
.detail("JobId", jobId)
.detail("CompletedTasks", completed)
.detail("SubmittedTasks", submitted)
.detail("TriggeredTasks", triggered)
.detail("RunningTasks", running)
.detail("TotalTasks", total)
.detail("BlocksFinished", blocksFinished)
.detail("BlocksDispatched", blocksDispatched)
.detail("EffectiveTotalBlocks", effectiveTotalBlocks)
.detail("BytesWritten", bytes);
}
} catch (Error& e) {
// Log but don't fail - progress updates are best-effort
TraceEvent(SevWarn, "BulkLoadRestoreProgressError").error(e).detail("JobId", jobId);
}
if (now() - timeoutStart > timeoutDuration) {
co_return false; // Timed out
}
co_await delay(pollInterval);
}
}
Future<std::string> RestoreConfig::getProgress_impl(RestoreConfig restore, Reference<ReadYourWritesTransaction> tr) {
tr->setOption(FDBTransactionOptions::ACCESS_SYSTEM_KEYS);
tr->setOption(FDBTransactionOptions::LOCK_AWARE);
Future<int64_t> fileCount = restore.fileCount().getD(tr);
Future<int64_t> fileBlockCount = restore.fileBlockCount().getD(tr);
Future<int64_t> fileBlocksDispatched = restore.filesBlocksDispatched().getD(tr);
Future<int64_t> fileBlocksFinished = restore.fileBlocksFinished().getD(tr);
Future<int64_t> bytesWritten = restore.bytesWritten().getD(tr);
Future<StringRef> status = restore.stateText(tr);
Future<Version> currentVersion = restore.getCurrentVersion(tr);
Future<Version> lag = restore.getApplyVersionLag(tr);
Future<Version> firstConsistentVersion = restore.firstConsistentVersion().getD(tr);
Future<std::string> tag = restore.tag().getD(tr);
Future<std::pair<std::string, Version>> lastError = restore.lastError().getD(tr);
Future<int64_t> submittedTasks = restore.bulkLoadSubmittedTasks().getD(tr);
Future<int64_t> triggeredTasks = restore.bulkLoadTriggeredTasks().getD(tr);
Future<int64_t> runningTasks = restore.bulkLoadRunningTasks().getD(tr);
Future<int64_t> totalTasks = restore.bulkLoadTotalTasks().getD(tr);
Future<Optional<bool>> useRangeFileRestore = restore.useRangeFileRestore().get(tr);
UID uid = restore.getUid();
co_await (success(fileCount) && success(fileBlockCount) && success(fileBlocksDispatched) &&
success(fileBlocksFinished) && success(bytesWritten) && success(status) && success(currentVersion) &&
success(lag) && success(firstConsistentVersion) && success(tag) && success(lastError) &&
success(submittedTasks) && success(triggeredTasks) && success(runningTasks) && success(totalTasks) &&
success(useRangeFileRestore));
bool useRangeFile = !useRangeFileRestore.get().present() || useRangeFileRestore.get().get();
std::string errstr = "None";
if (lastError.get().second != 0)
errstr = format("'%s' %" PRId64 "s ago.\n",
lastError.get().first.c_str(),
(tr->getReadVersion().get() - lastError.get().second) / CLIENT_KNOBS->CORE_VERSIONSPERSECOND);
TraceEvent("FileRestoreProgress")
.detail("RestoreUID", uid)
.detail("Tag", tag.get())
.detail("State", status.get().toString())
.detail("FileCount", fileCount.get())
.detail("FileBlocksFinished", fileBlocksFinished.get())
.detail("FileBlocksTotal", fileBlockCount.get())
.detail("FileBlocksInProgress", fileBlocksDispatched.get() - fileBlocksFinished.get())
.detail("SubmittedTasks", submittedTasks.get())
.detail("TriggeredTasks", triggeredTasks.get())
.detail("RunningTasks", runningTasks.get())
.detail("TotalTasks", totalTasks.get())
.detail("BytesWritten", bytesWritten.get())
.detail("CurrentVersion", currentVersion.get())
.detail("FirstConsistentVersion", firstConsistentVersion.get())
.detail("ApplyLag", lag.get());
std::string progressStr;
if (useRangeFile) {
progressStr = format("Tag: %s UID: %s State: %s\n",
tag.get().c_str(),
uid.toString().c_str(),
status.get().toString().c_str());
progressStr += format(" Blocks: %lld/%lld complete\n", fileBlocksFinished.get(), fileBlockCount.get());
progressStr += format(" Files: %lld\n", fileCount.get());
progressStr += format(" Bytes written: %s\n", formatBytesHumanReadable(bytesWritten.get()).c_str());
progressStr += format(" Apply version lag: %s\n", versionToString(lag.get()).c_str());
} else {
progressStr = format("Tag: %s UID: %s State: %s\n",
tag.get().c_str(),
uid.toString().c_str(),
status.get().toString().c_str());
progressStr += format(" Tasks submitted: %lld triggered: %lld running: %lld\n",
submittedTasks.get(),
triggeredTasks.get(),
runningTasks.get());
progressStr += format(" Tasks triggered: %lld / %lld total\n", triggeredTasks.get(), totalTasks.get());
progressStr += format(" Bytes written: %s\n", formatBytesHumanReadable(bytesWritten.get()).c_str());
double avgBytesPerTask = triggeredTasks.get() > 0 ? (double)bytesWritten.get() / triggeredTasks.get() : 0;
if (avgBytesPerTask > 0) {
progressStr += format(" Avg bytes/task: %s\n", formatBytesHumanReadable((int64_t)avgBytesPerTask).c_str());
}
}
co_return progressStr;
}
Future<std::string> RestoreConfig::getFullStatus_impl(RestoreConfig restore, Reference<ReadYourWritesTransaction> tr) {
tr->setOption(FDBTransactionOptions::ACCESS_SYSTEM_KEYS);
tr->setOption(FDBTransactionOptions::LOCK_AWARE);
Future<std::vector<KeyRange>> ranges = restore.getRestoreRangesOrDefault(tr);
Future<Key> addPrefix = restore.addPrefix().getD(tr);
Future<Key> removePrefix = restore.removePrefix().getD(tr);
Future<Key> url = restore.sourceContainerURL().getD(tr);
Future<Version> restoreVersion = restore.restoreVersion().getD(tr);
Future<std::string> progress = restore.getProgress(tr);
Future<ERestoreState> restoreState = restore.stateEnum().getD(tr);
Future<Optional<bool>> useRangeFileRestore = restore.useRangeFileRestore().get(tr);
Future<Optional<bool>> bulkLoadComplete = restore.bulkLoadComplete().get(tr);
// restore might no longer be valid after the first wait so make sure it is not needed anymore.
co_await (success(ranges) && success(addPrefix) && success(removePrefix) && success(url) &&
success(restoreVersion) && success(progress) && success(restoreState) && success(useRangeFileRestore) &&
success(bulkLoadComplete));
std::string returnStr;
returnStr = format("%s URL: %s", progress.get().c_str(), url.get().toString().c_str());
for (auto& range : ranges.get()) {
returnStr += format(" Range: '%s'-'%s'", printable(range.begin).c_str(), printable(range.end).c_str());
}
returnStr += format(" AddPrefix: '%s' RemovePrefix: '%s' Version: %lld",
printable(addPrefix.get()).c_str(),
printable(removePrefix.get()).c_str(),
restoreVersion.get());
// Add enhanced status fields for BulkLoad integration
bool usingBulkLoad = useRangeFileRestore.get().present() && !useRangeFileRestore.get().get();
std::string snapshotMethod = usingBulkLoad ? "bulkload" : "rangefile";
returnStr += format(" Snapshot Method: %s", snapshotMethod.c_str());
// Add phase status information
ERestoreState currentState = restoreState.get();
bool bulkLoadDone = bulkLoadComplete.get().present() && bulkLoadComplete.get().get();
if (currentState == ERestoreState::RUNNING) {
if (usingBulkLoad) {
std::string snapshotPhase = bulkLoadDone ? "complete" : "in_progress";
returnStr += format(" Snapshot Phase: %s", snapshotPhase.c_str());
std::string mutationPhase = bulkLoadDone ? "in_progress" : "not_started";
returnStr += format(" Mutation Log Phase: %s", mutationPhase.c_str());
} else {
returnStr += " Snapshot Phase: in_progress Mutation Log Phase: in_progress";
}
} else if (currentState == ERestoreState::COMPLETED) {
returnStr += " Snapshot Phase: complete Mutation Log Phase: complete";
}
co_return returnStr;
}
// two buffers are alternatively serving data and reading data from file
// thus when one buffer is serving data through peek()
// the other buffer is reading data from file to provide pipelining.
class TwoBuffers : public ReferenceCounted<TwoBuffers>, NonCopyable {
public:
class IteratorBuffer : public ReferenceCounted<IteratorBuffer> {
public:
std::shared_ptr<char[]> data;
// has_value means there is data, otherwise it means there is no data being fetched or ready
// is_valid means data is being fetched, is_ready means data is ready
std::optional<Future<Void>> fetchingData;
size_t size;
int index;
int capacity;
explicit IteratorBuffer(int _capacity) {
capacity = _capacity;
data = std::shared_ptr<char[]>(new char[capacity]());
fetchingData.reset();
size = 0;
}
bool is_valid() { return fetchingData.has_value(); }
void reset() {
size = 0;
index = 0;
fetchingData.reset();
}
};
TwoBuffers(int capacity, Reference<IBackupContainer> _bc, std::vector<RestoreConfig::RestoreFile>& _files, int tag);
// ready need to be called first before calling peek
// because a shared_ptr cannot be wrapped by a Future
// this method ensures the current buffer has available data
Future<Void> ready();
static Future<Void> ready(Reference<TwoBuffers> self);
// fill buffer[index] with the next block of file
// it has side effects to change currentFileIndex and currentFilePosition
static Future<Void> readNextBlock(Reference<TwoBuffers> self, int index);
// peek can only be called after ready is called
// it returns the pointer to the active buffer
std::shared_ptr<char[]> peek();
int getFileIndex();
void setFileIndex(int);
bool hasNext();
void reset();
// discard the current buffer and swap to the next one
void discardAndSwap();
// try to fill the buffer[index]
// but no-op if the buffer have valid data or it is actively being filled
void fillBufferIfAbsent(int index);
size_t getBufferSize();
private:
Reference<IteratorBuffer> buffers[2]; // Two buffers for alternating
size_t bufferCapacity; // Size of each buffer in bytes
Reference<IBackupContainer> bc;
std::vector<RestoreConfig::RestoreFile> files;
int tag;
int cur; // Index of the current active buffer (0 or 1)
size_t currentFileIndex; // Index of the current file being read
size_t currentFilePosition; // Current read position in the current file
};
TwoBuffers::TwoBuffers(int capacity,
Reference<IBackupContainer> _bc,
std::vector<RestoreConfig::RestoreFile>& _files,
int _tag)
: currentFileIndex(0), currentFilePosition(0), cur(0), bufferCapacity(capacity), files(_files), bc(_bc), tag(_tag) {
buffers[0] = makeReference<IteratorBuffer>(capacity);
buffers[1] = makeReference<IteratorBuffer>(capacity);
}
bool TwoBuffers::hasNext() {
// if it is being load (valid but not ready, what would be the size?)
while (currentFileIndex < files.size() && currentFilePosition >= files[currentFileIndex].fileSize) {
currentFileIndex++;
currentFilePosition = 0;
}
if (buffers[0]->is_valid() || buffers[1]->is_valid()) {
return true;
}
return currentFileIndex != files.size();
}
Future<Void> TwoBuffers::ready() {
return ready(Reference<TwoBuffers>::addRef(this));
}
Future<Void> TwoBuffers::ready(Reference<TwoBuffers> self) {
// if cur is not ready, then wait
if (!self->hasNext()) {
co_return;
}
// try to fill the current buffer, and wait before it is filled
self->fillBufferIfAbsent(self->cur);
co_await self->buffers[self->cur]->fetchingData.value();
// try to fill the next buffer, do not wait for the filling
if (self->hasNext()) {
self->fillBufferIfAbsent(1 - self->cur);
}
}
std::shared_ptr<char[]> TwoBuffers::peek() {
return buffers[cur]->data;
}
int TwoBuffers::getFileIndex() {
return buffers[cur]->index;
}
void TwoBuffers::setFileIndex(int newIndex) {
if (newIndex < 0 || newIndex >= files.size()) {
TraceEvent(SevError, "TwoBuffersFileIndexOutOfBound")
.detail("FilesSize", files.size())
.detail("NewIndex", newIndex)
.log();
}
currentFileIndex = newIndex;
}
void TwoBuffers::discardAndSwap() {
// invalidate cur and change cur to next
buffers[cur]->fetchingData.reset();
cur = 1 - cur;
}
void TwoBuffers::reset() {
// invalidate cur and change cur to next
buffers[0]->reset();
buffers[1]->reset();
cur = 0;
currentFileIndex = 0;
currentFilePosition = 0;
}
size_t TwoBuffers::getBufferSize() {
return buffers[cur]->size;
}
// only one readNextBlock can be run at a single time, otherwie the same block might be loaded twice
Future<Void> TwoBuffers::readNextBlock(Reference<TwoBuffers> self, int index) {
if (self->currentFileIndex >= self->files.size()) {
TraceEvent(SevError, "ReadNextBlockOutOfBound")
.detail("FileIndex", self->currentFileIndex)
.detail("Tag", self->tag)
.detail("Position", self->currentFilePosition)