-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathLogSystem.cpp
More file actions
3052 lines (2778 loc) · 120 KB
/
Copy pathLogSystem.cpp
File metadata and controls
3052 lines (2778 loc) · 120 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
/*
* LogSystem.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 "fdbserver/logsystem/LogSystem.h"
#include "fdbserver/logsystem/LogSystemConsumer.h"
#include "fdbclient/FDBTypes.h"
#include "fdbserver/core/OTELSpanContextMessage.h"
#include "fdbserver/core/SpanContextMessage.h"
#include "flow/serialize.h"
bool logSystemHasRemoteLogs(LogSystem const& logSystem) {
return logSystem.hasRemoteLogs();
}
void logSystemGetPushLocations(LogSystem const& logSystem,
VectorRef<Tag> tags,
std::vector<int>& locations,
bool allLocations,
Optional<std::vector<Reference<LocalitySet>>> fromLocations) {
logSystem.getPushLocations(tags, locations, allLocations, fromLocations);
}
std::vector<Reference<LocalitySet>> logSystemGetPushLocationsForTags(LogSystem const& logSystem,
std::vector<int>& fromLocations) {
return logSystem.getPushLocationsForTags(fromLocations);
}
Tag logSystemGetRandomRouterTag(LogSystem const& logSystem) {
return logSystem.getRandomRouterTag();
}
int logSystemGetLogRouterTags(LogSystem const& logSystem) {
return logSystem.getLogRouterTags();
}
Tag logSystemGetRandomTxsTag(LogSystem const& logSystem) {
return logSystem.getRandomTxsTag();
}
TLogVersion logSystemGetTLogVersion(LogSystem const& logSystem) {
return logSystem.getTLogVersion();
}
LogPushData::LogPushData(Reference<LogSystem> logSystem, int tlogCount) : logSystem(logSystem), subsequence(1) {
ASSERT(tlogCount > 0);
messagesWriter.reserve(tlogCount);
for (int i = 0; i < tlogCount; i++) {
messagesWriter.emplace_back(AssumeVersion(g_network->protocolVersion()));
}
messagesWritten = std::vector<bool>(tlogCount, false);
}
void LogPushData::addTxsTag() {
next_message_tags.push_back(logSystemGetRandomTxsTag(*logSystem));
}
void LogPushData::addTransactionInfo(SpanContext const& context) {
CODE_PROBE(!spanContext.isValid(), "addTransactionInfo with invalid SpanContext");
spanContext = context;
writtenLocations.clear();
}
void LogPushData::writeMessage(StringRef rawMessageWithoutLength, bool usePreviousLocations) {
if (!usePreviousLocations) {
prev_tags.clear();
if (logSystemHasRemoteLogs(*logSystem)) {
prev_tags.push_back(chooseRouterTag());
}
for (auto& tag : next_message_tags) {
prev_tags.push_back(tag);
}
msg_locations.clear();
logSystemGetPushLocations(*logSystem, VectorRef<Tag>((Tag*)prev_tags.data(), prev_tags.size()), msg_locations);
written_tags.insert(next_message_tags.begin(), next_message_tags.end());
next_message_tags.clear();
}
uint32_t subseq = this->subsequence++;
uint32_t msgsize =
rawMessageWithoutLength.size() + sizeof(subseq) + sizeof(uint16_t) + sizeof(Tag) * prev_tags.size();
for (int loc : msg_locations) {
BinaryWriter& wr = messagesWriter[loc];
wr << msgsize << subseq << uint16_t(prev_tags.size());
for (auto& tag : prev_tags)
wr << tag;
wr.serializeBytes(rawMessageWithoutLength);
}
}
std::vector<Standalone<StringRef>> LogPushData::getAllMessages() const {
std::vector<Standalone<StringRef>> results;
results.reserve(messagesWriter.size());
for (int loc = 0; loc < messagesWriter.size(); loc++) {
results.push_back(getMessages(loc));
}
return results;
}
void LogPushData::recordEmptyMessage(int loc, const Standalone<StringRef>& value) {
if (!messagesWritten[loc]) {
BinaryWriter w(AssumeVersion(g_network->protocolVersion()));
Standalone<StringRef> v = w.toValue();
if (value.size() > v.size()) {
messagesWritten[loc] = true;
}
}
}
float LogPushData::getEmptyMessageRatio() const {
auto count = std::count(messagesWritten.begin(), messagesWritten.end(), false);
ASSERT_WE_THINK(!messagesWritten.empty());
return 1.0 * count / messagesWritten.size();
}
bool LogPushData::writeTransactionInfo(int location, uint32_t subseq) {
if (!FLOW_KNOBS->WRITE_TRACING_ENABLED || logSystemGetTLogVersion(*logSystem) < TLogVersion::V6 ||
writtenLocations.contains(location)) {
return false;
}
CODE_PROBE(true, "Wrote SpanContextMessage to a transaction log");
writtenLocations.insert(location);
BinaryWriter& wr = messagesWriter[location];
int offset = wr.getLength();
wr << uint32_t(0) << subseq << uint16_t(prev_tags.size());
for (auto& tag : prev_tags)
wr << tag;
if (logSystemGetTLogVersion(*logSystem) >= TLogVersion::V7) {
OTELSpanContextMessage contextMessage(spanContext);
wr << contextMessage;
} else {
SpanContextMessage contextMessage;
if (spanContext.isSampled()) {
CODE_PROBE(true, "Converting OTELSpanContextMessage to traced SpanContextMessage");
contextMessage = SpanContextMessage(UID(spanContext.traceID.first(), spanContext.traceID.second()));
} else {
CODE_PROBE(true, "Converting OTELSpanContextMessage to untraced SpanContextMessage");
contextMessage = SpanContextMessage(UID(0, 0));
}
wr << contextMessage;
}
int length = wr.getLength() - offset;
*(uint32_t*)((uint8_t*)wr.getData() + offset) = length - sizeof(uint32_t);
return true;
}
void LogPushData::setMutations(uint32_t totalMutations, VectorRef<StringRef> mutations) {
ASSERT_EQ(subsequence, 1);
subsequence = totalMutations + 1;
ASSERT_EQ(messagesWriter.size(), mutations.size());
BinaryWriter w(AssumeVersion(g_network->protocolVersion()));
Standalone<StringRef> v = w.toValue();
const int header = v.size();
for (int i = 0; i < mutations.size(); i++) {
BinaryWriter& wr = messagesWriter[i];
wr.serializeBytes(mutations[i].substr(header));
}
}
#include <boost/dynamic_bitset.hpp>
#include <utility>
#include "fdbrpc/ReplicationUtils.h"
#include "fdbserver/core/WaitFailure.h"
#include "flow/CoroUtils.h"
namespace {
TLogSet toTLogSet(const LogSet& rhs) {
TLogSet result;
result.tLogWriteAntiQuorum = rhs.tLogWriteAntiQuorum;
result.tLogReplicationFactor = rhs.tLogReplicationFactor;
result.tLogLocalities = rhs.tLogLocalities;
result.tLogVersion = rhs.tLogVersion;
result.tLogPolicy = rhs.tLogPolicy;
result.isLocal = rhs.isLocal;
result.locality = rhs.locality;
result.startVersion = rhs.startVersion;
result.satelliteTagLocations = rhs.satelliteTagLocations;
for (const auto& tlog : rhs.logServers) {
result.tLogs.push_back(tlog->get());
}
for (const auto& logRouter : rhs.logRouters) {
result.logRouters.push_back(logRouter->get());
}
for (const auto& worker : rhs.backupWorkers) {
result.backupWorkers.push_back(worker->get());
}
return result;
}
CoreTLogSet toCoreTLogSet(const LogSet& logset) {
CoreTLogSet result;
result.tLogWriteAntiQuorum = logset.tLogWriteAntiQuorum;
result.tLogReplicationFactor = logset.tLogReplicationFactor;
result.tLogLocalities = logset.tLogLocalities;
result.tLogPolicy = logset.tLogPolicy;
result.isLocal = logset.isLocal;
result.locality = logset.locality;
result.startVersion = logset.startVersion;
result.satelliteTagLocations = logset.satelliteTagLocations;
result.tLogVersion = logset.tLogVersion;
for (const auto& log : logset.logServers) {
result.tLogs.push_back(log->get().id());
}
return result;
}
OldTLogConf toOldTLogConf(const OldLogData& oldLogData) {
OldTLogConf result;
result.epochBegin = oldLogData.epochBegin;
result.epochEnd = oldLogData.epochEnd;
result.recoverAt = oldLogData.recoverAt;
result.logRouterTags = oldLogData.logRouterTags;
result.txsTags = oldLogData.txsTags;
result.rangeBackupWorkerTags = oldLogData.rangeBackupWorkerTags;
result.pseudoLocalities = oldLogData.pseudoLocalities;
result.epoch = oldLogData.epoch;
for (const Reference<LogSet>& logSet : oldLogData.tLogs) {
result.tLogs.push_back(toTLogSet(*logSet));
}
return result;
}
OldTLogCoreData toOldTLogCoreData(const OldLogData& oldData) {
OldTLogCoreData result;
result.logRouterTags = oldData.logRouterTags;
result.txsTags = oldData.txsTags;
result.rangeBackupWorkerTags = oldData.rangeBackupWorkerTags;
result.epochBegin = oldData.epochBegin;
result.epochEnd = oldData.epochEnd;
result.recoverAt = oldData.recoverAt;
result.pseudoLocalities = oldData.pseudoLocalities;
result.epoch = oldData.epoch;
for (const Reference<LogSet>& logSet : oldData.tLogs) {
if (!logSet->logServers.empty()) {
result.tLogs.push_back(toCoreTLogSet(*logSet));
}
}
return result;
}
} // namespace
Future<Version> minVersionWhenReady(Future<Void> f, std::vector<std::pair<UID, Future<TLogCommitReply>>> replies) {
try {
co_await f;
Version minVersion = std::numeric_limits<Version>::max();
for (const auto& [_tlogID, reply] : replies) {
if (reply.isReady() && !reply.isError()) {
minVersion = std::min(minVersion, reply.get().version);
}
}
co_return minVersion;
} catch (Error& err) {
if (err.code() == error_code_operation_cancelled) {
TraceEvent(g_network->isSimulated() ? SevInfo : SevWarnAlways, "TLogPushCancelled");
int index = 0;
for (const auto& [tlogID, reply] : replies) {
if (reply.isReady()) {
continue;
}
std::string message;
if (reply.isError()) {
// FIXME Use C++20 format when it is available
message = format("TLogPushRespondError%04d", index++);
} else {
message = format("TLogPushNoResponse%04d", index++);
}
TraceEvent(g_network->isSimulated() ? SevInfo : SevWarnAlways, message.c_str())
.detail("TLogID", tlogID);
}
}
throw;
}
}
LogSet::LogSet(const TLogSet& tLogSet)
: tLogWriteAntiQuorum(tLogSet.tLogWriteAntiQuorum), tLogReplicationFactor(tLogSet.tLogReplicationFactor),
tLogLocalities(tLogSet.tLogLocalities), tLogVersion(tLogSet.tLogVersion), tLogPolicy(tLogSet.tLogPolicy),
isLocal(tLogSet.isLocal), locality(tLogSet.locality), startVersion(tLogSet.startVersion),
satelliteTagLocations(tLogSet.satelliteTagLocations) {
for (const auto& log : tLogSet.tLogs) {
logServers.push_back(makeReference<AsyncVar<OptionalInterface<TLogInterface>>>(log));
}
for (const auto& log : tLogSet.logRouters) {
logRouters.push_back(makeReference<AsyncVar<OptionalInterface<TLogInterface>>>(log));
}
for (const auto& log : tLogSet.backupWorkers) {
backupWorkers.push_back(makeReference<AsyncVar<OptionalInterface<BackupInterface>>>(log));
}
filterLocalityDataForPolicy(tLogPolicy, &tLogLocalities);
updateLocalitySet(tLogLocalities);
}
LogSet::LogSet(const CoreTLogSet& coreSet)
: tLogWriteAntiQuorum(coreSet.tLogWriteAntiQuorum), tLogReplicationFactor(coreSet.tLogReplicationFactor),
tLogLocalities(coreSet.tLogLocalities), tLogVersion(coreSet.tLogVersion), tLogPolicy(coreSet.tLogPolicy),
isLocal(coreSet.isLocal), locality(coreSet.locality), startVersion(coreSet.startVersion),
satelliteTagLocations(coreSet.satelliteTagLocations) {
for (const auto& log : coreSet.tLogs) {
logServers.push_back(
makeReference<AsyncVar<OptionalInterface<TLogInterface>>>(OptionalInterface<TLogInterface>(log)));
}
// Do NOT recover coreSet.backupWorkers, because master will recruit new ones.
filterLocalityDataForPolicy(tLogPolicy, &tLogLocalities);
updateLocalitySet(tLogLocalities);
}
Reference<LogSystemConsumer> LogSystem::makeConsumer() {
return makeReference<LogSystemConsumer>(Reference<LogSystem>::addRef(this));
}
void LogSystem::stopRejoins() {
rejoins = Future<Void>();
}
void LogSystem::addref() {
ReferenceCounted<LogSystem>::addref();
}
void LogSystem::delref() {
ReferenceCounted<LogSystem>::delref();
}
std::string LogSystem::describe() const {
std::string result;
for (int i = 0; i < tLogs.size(); i++) {
result += format("%d: ", i);
for (int j = 0; j < tLogs[i]->logServers.size(); j++) {
result +=
tLogs[i]->logServers[j]->get().id().toString() + ((j == tLogs[i]->logServers.size() - 1) ? " " : ", ");
}
}
return result;
}
UID LogSystem::getDebugID() const {
return dbgid;
}
void LogSystem::addPseudoLocality(int8_t locality) {
ASSERT(locality < 0);
pseudoLocalities.insert(locality);
for (uint16_t i = 0; i < logRouterTags; i++) {
pseudoLocalityPopVersion[Tag(locality, i)] = 0;
}
}
Tag LogSystem::getPseudoPopTag(Tag tag, ProcessClass::ClassType type) const {
switch (type) {
case ProcessClass::LogRouterClass:
if (tag.locality == tagLocalityLogRouter) {
ASSERT(pseudoLocalities.contains(tagLocalityLogRouterMapped));
tag.locality = tagLocalityLogRouterMapped;
}
break;
case ProcessClass::BackupClass:
if (tag.locality == tagLocalityLogRouter) {
ASSERT(pseudoLocalities.contains(tagLocalityBackup));
tag.locality = tagLocalityBackup;
}
break;
default: // This should be an error at caller site.
break;
}
return tag;
}
bool LogSystem::hasPseudoLocality(int8_t locality) const {
return pseudoLocalities.contains(locality);
}
Version LogSystem::popPseudoLocalityTag(Tag tag, Version upTo) {
ASSERT(isPseudoLocality(tag.locality) && hasPseudoLocality(tag.locality));
Version& localityVersion = pseudoLocalityPopVersion[tag];
localityVersion = std::max(localityVersion, upTo);
Version minVersion = localityVersion;
// Why do we need to use the minimum popped version among all tags? Reason: for example,
// 2 pseudo tags pop 100 or 150, respectively. It's only safe to pop min(100, 150),
// because [101,150) is needed by another pseudo tag.
for (const int8_t locality : pseudoLocalities) {
minVersion = std::min(minVersion, pseudoLocalityPopVersion[Tag(locality, tag.id)]);
}
// TraceEvent("TLogPopPseudoTag", dbgid).detail("Tag", tag).detail("Version", upTo).detail("PopVersion", minVersion);
return minVersion;
}
Future<Void> LogSystem::recoverAndEndEpoch(Reference<AsyncVar<Reference<LogSystem>>> const& outLogSystem,
UID const& dbgid,
DBCoreState const& oldState,
FutureStream<TLogRejoinRequest> const& rejoins,
LocalityData const& locality,
bool* forceRecovery) {
return epochEnd(outLogSystem, dbgid, oldState, rejoins, locality, forceRecovery);
}
Reference<LogSystem> LogSystem::fromLogSystemConfig(UID const& dbgid,
LocalityData const& locality,
LogSystemConfig const& lsConf,
bool excludeRemote,
bool useRecoveredAt,
Optional<PromiseStream<Future<Void>>> addActor) {
ASSERT(lsConf.logSystemType == LogSystemType::tagPartitioned ||
(lsConf.logSystemType == LogSystemType::empty && lsConf.tLogs.empty()));
// ASSERT(lsConf.epoch == epoch); //< FIXME
auto logSystem = makeReference<LogSystem>(dbgid, locality, lsConf.epoch, addActor);
logSystem->tLogs.reserve(lsConf.tLogs.size());
logSystem->expectedLogSets = lsConf.expectedLogSets;
logSystem->logRouterTags = lsConf.logRouterTags;
logSystem->txsTags = lsConf.txsTags;
logSystem->rangeBackupWorkerTags = lsConf.rangeBackupWorkerTags;
logSystem->recruitmentID = lsConf.recruitmentID;
logSystem->stopped = lsConf.stopped;
if (useRecoveredAt) {
logSystem->recoveredAt = lsConf.recoveredAt;
}
logSystem->pseudoLocalities = lsConf.pseudoLocalities;
for (const TLogSet& tLogSet : lsConf.tLogs) {
if (!excludeRemote || tLogSet.isLocal) {
logSystem->tLogs.push_back(makeReference<LogSet>(tLogSet));
}
}
for (const auto& oldTlogConf : lsConf.oldTLogs) {
logSystem->oldLogData.emplace_back(oldTlogConf);
//TraceEvent("BWFromLSConf")
// .detail("Epoch", logSystem->oldLogData.back().epoch)
// .detail("Version", logSystem->oldLogData.back().epochEnd);
}
logSystem->logSystemType = lsConf.logSystemType;
logSystem->oldestBackupEpoch = lsConf.oldestBackupEpoch;
logSystem->knownLockedTLogIds = lsConf.knownLockedTLogIds;
return logSystem;
}
Reference<LogSystem> LogSystem::fromOldLogSystemConfig(UID const& dbgid,
LocalityData const& locality,
LogSystemConfig const& lsConf) {
ASSERT(lsConf.logSystemType == LogSystemType::tagPartitioned ||
(lsConf.logSystemType == LogSystemType::empty && lsConf.tLogs.empty()));
// ASSERT(lsConf.epoch == epoch); //< FIXME
const LogEpoch e = !lsConf.oldTLogs.empty() ? lsConf.oldTLogs[0].epoch : 0;
auto logSystem = makeReference<LogSystem>(dbgid, locality, e);
if (!lsConf.oldTLogs.empty()) {
for (const TLogSet& tLogSet : lsConf.oldTLogs[0].tLogs) {
logSystem->tLogs.push_back(makeReference<LogSet>(tLogSet));
}
logSystem->logRouterTags = lsConf.oldTLogs[0].logRouterTags;
logSystem->txsTags = lsConf.oldTLogs[0].txsTags;
logSystem->rangeBackupWorkerTags = lsConf.oldTLogs[0].rangeBackupWorkerTags;
// logSystem->epochEnd = lsConf.oldTLogs[0].epochEnd;
for (int i = 1; i < lsConf.oldTLogs.size(); i++) {
logSystem->oldLogData.emplace_back(lsConf.oldTLogs[i]);
}
}
logSystem->logSystemType = lsConf.logSystemType;
logSystem->stopped = true;
logSystem->pseudoLocalities = lsConf.pseudoLocalities;
return logSystem;
}
void LogSystem::purgeOldRecoveredGenerationsCoreState(DBCoreState& newState) {
Version oldestGenerationRecoverAtVersion = std::min(recoveredVersion->get(), remoteRecoveredVersion->get());
TraceEvent("ToCoreStateOldestGenerationRecoverAtVersion")
.detail("RecoveredVersion", recoveredVersion->get())
.detail("RemoteRecoveredVersion", remoteRecoveredVersion->get())
.detail("OldestBackupEpoch", oldestBackupEpoch);
for (int i = 0; i < newState.oldTLogData.size(); ++i) {
const auto& oldData = newState.oldTLogData[i];
// Remove earlier generation that TLog data are
// - consumed by all storage servers
// - no longer used by backup workers
if (oldData.recoverAt < oldestGenerationRecoverAtVersion && oldData.epoch < oldestBackupEpoch) {
if (g_network->isSimulated()) {
ASSERT(oldLogData.size() == newState.oldTLogData.size());
for (int j = 0; j < oldLogData.size(); ++j) {
TraceEvent("AllOldGenerations")
.detail("Index", j)
.detail("Purge", i + 1)
.detail("Begin", oldLogData[j].epochBegin)
.detail("RecoverAt", oldLogData[j].recoverAt);
}
for (int j = i + 1; j < newState.oldTLogData.size(); ++j) {
ASSERT(newState.oldTLogData[j].recoverAt < oldestGenerationRecoverAtVersion);
ASSERT(oldLogData[i].tLogs[0]->backupWorkers.empty() ||
newState.oldTLogData[j].epoch < oldestBackupEpoch);
}
}
for (int j = i; j < newState.oldTLogData.size(); ++j) {
TraceEvent("PurgeOldTLogGenerationCoreState", dbgid)
.detail("Begin", newState.oldTLogData[j].epochBegin)
.detail("End", newState.oldTLogData[j].epochEnd)
.detail("Epoch", newState.oldTLogData[j].epoch)
.detail("RecoverAt", newState.oldTLogData[j].recoverAt)
.detail("Index", j);
}
newState.oldTLogData.resize(i);
break;
}
}
}
void LogSystem::purgeOldRecoveredGenerationsInMemory(const DBCoreState& newState) {
auto generations = newState.oldTLogData.size();
if (generations < oldLogData.size()) {
TraceEvent("PurgeOldTLogGenerationsInMemory", dbgid)
.detail("OldGenerations", oldLogData.size())
.detail("NewGenerations", generations);
oldLogData.resize(generations);
}
}
void LogSystem::toCoreState(DBCoreState& newState) const {
if (recoveryComplete.isValid() && recoveryComplete.isError())
throw recoveryComplete.getError();
if (remoteRecoveryComplete.isValid() && remoteRecoveryComplete.isError())
throw remoteRecoveryComplete.getError();
newState.tLogs.clear();
newState.logRouterTags = logRouterTags;
newState.txsTags = txsTags;
newState.rangeBackupWorkerTags = rangeBackupWorkerTags;
newState.pseudoLocalities = pseudoLocalities;
for (const auto& t : tLogs) {
if (!t->logServers.empty()) {
newState.tLogs.push_back(toCoreTLogSet(*t));
newState.tLogs.back().tLogLocalities.clear();
for (const auto& log : t->logServers) {
newState.tLogs.back().tLogLocalities.push_back(log->get().interf().filteredLocality);
}
}
}
newState.oldTLogData.clear();
if (!recoveryComplete.isValid() || !recoveryComplete.isReady() ||
(repopulateRegionAntiQuorum == 0 && (!remoteRecoveryComplete.isValid() || !remoteRecoveryComplete.isReady())) ||
epoch != oldestBackupEpoch) {
for (const auto& oldData : oldLogData) {
newState.oldTLogData.push_back(toOldTLogCoreData(oldData));
TraceEvent("BWToCore")
.detail("Epoch", newState.oldTLogData.back().epoch)
.detail("TotalTags", newState.oldTLogData.back().logRouterTags)
.detail("RangeBackupWorkerTags", newState.oldTLogData.back().rangeBackupWorkerTags)
.detail("BeginVersion", newState.oldTLogData.back().epochBegin)
.detail("EndVersion", newState.oldTLogData.back().epochEnd);
}
}
newState.logSystemType = logSystemType;
}
bool LogSystem::remoteStorageRecovered() const {
return remoteRecoveryComplete.isValid() && remoteRecoveryComplete.isReady();
}
Future<Void> LogSystem::onCoreStateChanged() const {
std::vector<Future<Void>> changes;
changes.push_back(Never());
if (recoveryComplete.isValid() && !recoveryComplete.isReady()) {
changes.push_back(recoveryComplete);
}
if (remoteRecovery.isValid() && !remoteRecovery.isReady()) {
changes.push_back(remoteRecovery);
}
if (remoteRecoveryComplete.isValid() && !remoteRecoveryComplete.isReady()) {
changes.push_back(remoteRecoveryComplete);
}
changes.push_back(backupWorkerChanged.onTrigger()); // changes to oldestBackupEpoch
changes.push_back(recoveredVersion->onChange());
changes.push_back(remoteRecoveredVersion->onChange());
return waitForAny(changes);
}
void LogSystem::coreStateWritten(DBCoreState const& newState) {
if (newState.oldTLogData.empty()) {
recoveryCompleteWrittenToCoreState.set(true);
}
for (auto& t : newState.tLogs) {
if (!t.isLocal) {
TraceEvent("RemoteLogsWritten", dbgid).log();
remoteLogsWrittenToCoreState = true;
break;
}
}
}
Future<Void> LogSystem::onError() const {
// Never returns normally, but throws an error if the subsystem stops working
while (true) {
std::vector<Future<Void>> failed;
std::vector<Future<Void>> routerFailed;
std::vector<Future<Void>> backupFailed(1, Never());
std::vector<Future<Void>> changes;
for (auto& it : tLogs) {
for (auto& t : it->logServers) {
if (t->get().present()) {
failed.push_back(waitFailureClient(t->get().interf().waitFailure,
/* failureReactionTime */ SERVER_KNOBS->TLOG_TIMEOUT,
/* failureReactionSlope */ -SERVER_KNOBS->TLOG_TIMEOUT /
SERVER_KNOBS->SECONDS_BEFORE_NO_FAILURE_DELAY,
/* trace */ true,
/* traceMsg */ "TLogFailed"_sr));
} else {
changes.push_back(t->onChange());
}
}
for (auto& t : it->logRouters) {
if (t->get().present()) {
routerFailed.push_back(waitFailureClient(t->get().interf().waitFailure,
/* failureReactionTime */ SERVER_KNOBS->TLOG_TIMEOUT,
/* failureReactionSlope */ -SERVER_KNOBS->TLOG_TIMEOUT /
SERVER_KNOBS->SECONDS_BEFORE_NO_FAILURE_DELAY,
/* trace */ true,
/* traceMsg */ "LogRouterFailed"_sr));
} else {
changes.push_back(t->onChange());
}
}
for (const auto& worker : it->backupWorkers) {
if (worker->get().present()) {
backupFailed.push_back(waitFailureClient(worker->get().interf().waitFailure,
/* failureReactionTime */ SERVER_KNOBS->BACKUP_TIMEOUT,
/* failureReactionSlope */ -SERVER_KNOBS->BACKUP_TIMEOUT /
SERVER_KNOBS->SECONDS_BEFORE_NO_FAILURE_DELAY,
/* trace */ true,
/* traceMsg */ "BackupWorkerFailed"_sr));
} else {
changes.push_back(worker->onChange());
}
}
}
if (!recoveryCompleteWrittenToCoreState.get()) {
failed.insert(failed.end(), routerFailed.begin(), routerFailed.end());
routerFailed.clear();
for (auto& old : oldLogData) {
for (auto& it : old.tLogs) {
for (auto& t : it->logRouters) {
if (t->get().present()) {
failed.push_back(waitFailureClient(t->get().interf().waitFailure,
/* failureReactionTime */ SERVER_KNOBS->TLOG_TIMEOUT,
/* failureReactionSlope */ -SERVER_KNOBS->TLOG_TIMEOUT /
SERVER_KNOBS->SECONDS_BEFORE_NO_FAILURE_DELAY,
/* trace */ true,
/* traceMsg */ "OldLogRouterFailed"_sr));
} else {
changes.push_back(t->onChange());
}
}
}
// Monitor changes of backup workers for old epochs.
for (const auto& worker : old.tLogs[0]->backupWorkers) {
if (worker->get().present()) {
backupFailed.push_back(
waitFailureClient(worker->get().interf().waitFailure,
/* failureReactionTime */ SERVER_KNOBS->BACKUP_TIMEOUT,
/* failureReactionSlope */ -SERVER_KNOBS->BACKUP_TIMEOUT /
SERVER_KNOBS->SECONDS_BEFORE_NO_FAILURE_DELAY,
/* trace */ true,
/* traceMsg */ "OldBackupWorkerFailed"_sr));
} else {
changes.push_back(worker->onChange());
}
}
}
}
if (SERVER_KNOBS->CC_RERECRUIT_LOG_ROUTER_ENABLED) {
// Don't monitor current generation log routers after full recovery.
// They are monitored and recruited by monitorAndRecruitLogRouters().
routerFailed.clear();
} else {
failed.insert(failed.end(), routerFailed.begin(), routerFailed.end());
}
if (hasRemoteServers && (!remoteRecovery.isReady() || remoteRecovery.isError())) {
changes.push_back(remoteRecovery);
}
changes.push_back(recoveryCompleteWrittenToCoreState.onChange());
changes.push_back(backupWorkerChanged.onTrigger());
ASSERT(!failed.empty());
co_await (
quorum(changes, 1) ||
tagError<Void>(traceAfter(quorum(failed, 1), "TPLSOnErrorLogSystemFailed"), tlog_failed()) ||
tagError<Void>(traceAfter(quorum(backupFailed, 1), "TPLSOnErrorBackupFailed"), backup_worker_failed()));
}
}
Future<Void> LogSystem::pushResetChecker(Reference<ConnectionResetInfo> self, NetworkAddress addr) {
self->slowReplies = 0;
self->fastReplies = 0;
co_await delay(SERVER_KNOBS->PUSH_STATS_INTERVAL);
TraceEvent("SlowPushStats")
.detail("PeerAddress", addr)
.detail("SlowReplies", self->slowReplies)
.detail("FastReplies", self->fastReplies);
if (self->slowReplies >= SERVER_KNOBS->PUSH_STATS_SLOW_AMOUNT &&
self->slowReplies / double(self->slowReplies + self->fastReplies) >= SERVER_KNOBS->PUSH_STATS_SLOW_RATIO) {
FlowTransport::transport().resetConnection(addr);
self->lastReset = now();
}
}
Future<TLogCommitReply> LogSystem::recordPushMetrics(Reference<ConnectionResetInfo> self,
Reference<Histogram> dist,
NetworkAddress addr,
Future<TLogCommitReply> in) {
double startTime = now();
TLogCommitReply t = co_await in;
if (now() - self->lastReset > SERVER_KNOBS->PUSH_RESET_INTERVAL) {
if (now() - startTime > SERVER_KNOBS->PUSH_MAX_LATENCY) {
if (self->resetCheck.isReady()) {
self->resetCheck = LogSystem::pushResetChecker(self, addr);
}
self->slowReplies++;
} else {
self->fastReplies++;
}
}
dist->sampleSeconds(now() - startTime);
co_return t;
}
Future<Version> LogSystem::push(const LogPushVersionSet& versionSet,
LogPushData& data,
SpanContext const& spanContext,
Optional<UID> debugID,
Optional<std::unordered_map<uint16_t, Version>> tpcvMap) {
// FIXME: Randomize request order as in LegacyLogSystem?
Version prevVersion = versionSet.prevVersion; // this might be updated when version vector unicast is enabled
Version seqPrevVersion = versionSet.prevVersion; // a copy of the prevVersion provided by the sequencer
std::unordered_map<uint8_t, uint16_t> tLogCount;
std::unordered_map<uint8_t, std::vector<uint16_t>> tLogLocIds;
if (SERVER_KNOBS->ENABLE_VERSION_VECTOR_TLOG_UNICAST) {
uint16_t location = 0;
uint8_t logGroupLocal = 0;
const auto& tpcvMapRef = tpcvMap.get();
for (const auto& it : tLogs) {
if (!it->isLocal) {
continue;
}
if (it->logServers.empty()) {
continue;
}
for (size_t loc = 0; loc < it->logServers.size(); loc++) {
if (tpcvMapRef.contains(location)) {
tLogCount[logGroupLocal]++;
tLogLocIds[logGroupLocal].push_back(location);
}
location++;
}
logGroupLocal++;
}
}
uint16_t location = 0;
uint8_t logGroupLocal = 0;
std::vector<Future<Void>> quorumResults;
std::vector<std::pair<UID, Future<TLogCommitReply>>> allReplies;
const Span span("TPLS:push"_loc, spanContext);
for (auto& it : tLogs) {
if (!it->isLocal) {
// Remote TLogs should read from LogRouter
continue;
}
if (it->logServers.empty()) {
// Empty TLog set
continue;
}
if (it->connectionResetTrackers.empty()) {
for (int i = 0; i < it->logServers.size(); i++) {
it->connectionResetTrackers.push_back(makeReference<ConnectionResetInfo>());
}
}
if (it->tlogPushDistTrackers.empty()) {
for (int i = 0; i < it->logServers.size(); i++) {
it->tlogPushDistTrackers.push_back(
Histogram::getHistogram("ToTlog_" + it->logServers[i]->get().interf().uniqueID.toString(),
it->logServers[i]->get().interf().address().toString(),
Histogram::Unit::milliseconds));
}
}
std::vector<Future<Void>> tLogCommitResults;
for (size_t loc = 0; loc < it->logServers.size(); loc++) {
Standalone<StringRef> msg = data.getMessages(location);
data.recordEmptyMessage(location, msg);
if (SERVER_KNOBS->ENABLE_VERSION_VECTOR_TLOG_UNICAST) {
if (tpcvMap.get().contains(location)) {
prevVersion = tpcvMap.get()[location];
} else {
ASSERT(msg.empty());
location++;
continue;
}
}
const auto& interface = it->logServers[loc]->get().interf();
const auto request = TLogCommitRequest(spanContext,
msg.arena(),
prevVersion,
versionSet.version,
versionSet.knownCommittedVersion,
versionSet.minKnownCommittedVersion,
seqPrevVersion,
msg,
tLogCount[logGroupLocal],
tLogLocIds[logGroupLocal],
debugID);
auto tLogReply = recordPushMetrics(it->connectionResetTrackers[loc],
it->tlogPushDistTrackers[loc],
interface.address(),
interface.commit.getReply(request, TaskPriority::ProxyTLogCommitReply));
allReplies.emplace_back(interface.id(), tLogReply);
Future<Void> commitSuccess = success(tLogReply);
addActor.get().send(commitSuccess);
tLogCommitResults.push_back(commitSuccess);
location++;
}
quorumResults.push_back(quorum(tLogCommitResults, tLogCommitResults.size() - it->tLogWriteAntiQuorum));
logGroupLocal++;
}
return minVersionWhenReady(waitForAll(quorumResults), allReplies);
}
// Version vector/unicast specific: If the best server is not known to have been locked/stopped
// then is not guaranteed to have received all versions that are relevant to a tag(s) that it is
// buddy of, hence do not treat such a server as the best server. Note that this reset logic gets
// invoked only in the context of peeks that get done during recovery, and the best server should
// always be available for peeking after recovery is done.
void LogSystem::resetBestServerIfNotLocked(
int bestSet,
int& bestServer,
Optional<Version> end,
const Optional<std::map<uint8_t, std::vector<uint16_t>>>& knownLockedTLogIds) {
ASSERT(SERVER_KNOBS->ENABLE_VERSION_VECTOR_TLOG_UNICAST);
if (bestSet >= 0 && bestServer >= 0 && end.present() && end.get() != std::numeric_limits<Version>::max()) {
ASSERT_WE_THINK(knownLockedTLogIds.present() && !knownLockedTLogIds.get().empty());
ASSERT_WE_THINK(knownLockedTLogIds.get().contains(bestSet));
if (std::find(knownLockedTLogIds.get().at(bestSet).begin(),
knownLockedTLogIds.get().at(bestSet).end(),
bestServer) == knownLockedTLogIds.get().at(bestSet).end()) {
bestServer = -1;
return;
}
}
}
Version LogSystem::getKnownCommittedVersion() {
Version result = invalidVersion;
for (auto& it : lockResults) {
auto durableVersionInfo = LogSystem::getDurableVersion(dbgid, it);
if (durableVersionInfo.present()) {
result = std::max(result, durableVersionInfo.get().knownCommittedVersion);
}
}
return result;
}
Future<Void> LogSystem::onKnownCommittedVersionChange() {
std::vector<Future<Void>> result;
for (auto& it : lockResults) {
result.push_back(LogSystem::getDurableVersionChanged(it));
}
if (result.empty()) {
return Never();
}
return waitForAny(result);
}
Future<Void> LogSystem::popFromLog(Reference<AsyncVar<OptionalInterface<TLogInterface>>> log,
Tag tag,
double delayBeforePop,
bool popLogRouter) {
Version last = 0;
while (true) {
co_await delay(delayBeforePop, TaskPriority::TLogPop);
// to: first is upto version, second is durableKnownComittedVersion
std::pair<Version, Version> to = outstandingPops[std::make_pair(log->get().id(), tag)];
if (to.first <= last) {
outstandingPops.erase(std::make_pair(log->get().id(), tag));
co_return;
}
try {
if (!log->get().present())
co_return;
co_await log->get().interf().popMessages.getReply(TLogPopRequest(to.first, to.second, tag),
TaskPriority::TLogPop);
if (popLogRouter) {
logRouterLastPops[std::make_pair(log->get().id(), tag)] = to.first;
}
last = to.first;
} catch (Error& e) {
if (e.code() == error_code_actor_cancelled)
throw;
TraceEvent((e.code() == error_code_broken_promise) ? SevInfo : SevError, "LogPopError", dbgid)
.error(e)
.detail("Log", log->get().id());
co_return; // Leaving outstandingPops filled in means no further pop requests to this tlog from this
// logSystem
}
}
}
Future<Version> LogSystem::getPoppedFromTLog(Reference<AsyncVar<OptionalInterface<TLogInterface>>> log, Tag tag) {
while (true) {
const auto logInterface = log->get();
if (!logInterface.present()) {
co_await log->onChange();
continue;
}
auto res = co_await race(
brokenPromiseToNever(logInterface.interf().peekMessages.getReply(TLogPeekRequest(-1, tag, false, false))),
log->onChange());
if (res.index() == 0) {
TLogPeekReply rep = std::get<0>(std::move(res));
ASSERT(rep.popped.present());
co_return rep.popped.get();
}
}
}
Future<Version> LogSystem::getPoppedTxs() {
std::vector<std::vector<Future<Version>>> poppedFutures;
std::vector<Future<Void>> poppedReady;
if (!tLogs.empty()) {
poppedFutures.push_back(std::vector<Future<Version>>());
for (auto& it : tLogs) {
for (auto& log : it->logServers) {
poppedFutures.back().push_back(LogSystem::getPoppedFromTLog(log, Tag(tagLocalityTxs, 0)));
}
}
poppedReady.push_back(waitForAny(poppedFutures.back()));
}
for (auto& old : oldLogData) {
if (!old.tLogs.empty()) {
poppedFutures.push_back(std::vector<Future<Version>>());
for (auto& it : old.tLogs) {
for (auto& log : it->logServers) {
poppedFutures.back().push_back(LogSystem::getPoppedFromTLog(log, Tag(tagLocalityTxs, 0)));
}
}
poppedReady.push_back(waitForAny(poppedFutures.back()));
}
}
UID dbgid = this->dbgid;
Future<Void> maxGetPoppedDuration = delay(SERVER_KNOBS->TXS_POPPED_MAX_DELAY);
co_await (waitForAll(poppedReady) || maxGetPoppedDuration);
if (maxGetPoppedDuration.isReady()) {
TraceEvent(SevWarnAlways, "PoppedTxsNotReady", dbgid).log();
}
Version maxPopped = 1;