forked from phaistos-networks/TANK
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathservice.cpp
More file actions
5811 lines (4698 loc) · 254 KB
/
service.cpp
File metadata and controls
5811 lines (4698 loc) · 254 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
#include "service.h"
#include <ansifmt.h>
#include <compress.h>
#include <date.h>
#include <fcntl.h>
#include <fs.h>
#include <future>
#include <random>
#include <set>
#include <signal.h>
#include <switch_mallocators.h>
#include <sys/stat.h>
#include <sys/uio.h>
#include <text.h>
#include <text.h>
#include <thread>
#include <timings.h>
#include <unistd.h>
#ifndef LEAN_SWITCH
#include <switch_debug.h>
#endif
// From SENDFILE(2): The original Linux sendfile() system call was not designed to handle large file offsets.
// Consequently, Linux 2.4 added sendfile64(), with a wider type for the offset argument.
// The glibc sendfile() wrapper function transparently deals with the kernel differences.
#define HAVE_SENDFILE64 1
static constexpr bool trace{false};
static Switch::mutex mboxLock;
static Switch::vector<std::pair<int, int>> mbox;
static Buffer basePath_;
static bool cleanupTrackerIsDirty{false};
static std::vector<topic_partition_log *> cleanupTracker;
static int Rename(const char *oldpath, const char *newpath)
{
if (trace)
SLog("rename(", oldpath, ", ", newpath, ")\n");
return rename(oldpath, newpath);
}
static int Unlink(const char *pathname)
{
if (trace)
SLog("unlink(", pathname, ")\n");
return unlink(pathname);
}
ro_segment::ro_segment(const uint64_t absSeqNum, const uint64_t lastAbsSeqNum, const strwlen32_t base, const uint32_t creationTS, const bool wideEntries)
: baseSeqNum{absSeqNum}, lastAvailSeqNum{lastAbsSeqNum}, createdTS{creationTS}, haveWideEntries{wideEntries}
{
int fd, indexFd;
struct stat64 st;
if (trace)
SLog("New ro_segment(this = ", ptr_repr(this), ", baseSeqNum = ", baseSeqNum, ", lastAbsSeqNum = ", lastAbsSeqNum, ", createdTS = ", createdTS, ", haveWideEntries = ", haveWideEntries, "\n");
require(lastAbsSeqNum >= baseSeqNum);
index.data = nullptr;
if (createdTS)
fd = open(Buffer::build(base, "/", absSeqNum, "-", lastAbsSeqNum, "_", createdTS, ".ilog").data(), O_RDONLY | O_LARGEFILE | O_NOATIME);
else
fd = open(Buffer::build(base, "/", absSeqNum, "-", lastAbsSeqNum, ".ilog").data(), O_RDONLY | O_LARGEFILE | O_NOATIME);
if (fd == -1)
throw Switch::system_error("Failed to access log file:", strerror(errno));
fdh.reset(new fd_handle(fd));
Drequire(fdh.use_count() == 2);
fdh->Release();
if (fstat64(fd, &st) == -1)
throw Switch::system_error("Failed to fstat():", strerror(errno));
auto size = st.st_size;
if (unlikely(size == (off64_t)-1))
throw Switch::system_error("lseek64() failed: ", strerror(errno));
Drequire(size < std::numeric_limits<std::remove_reference<decltype(fileSize)>::type>::max());
fileSize = size;
if (trace)
SLog(ansifmt::bold, "fileSize = ", fileSize, ", createdTS = ", Date::ts_repr(creationTS), ansifmt::reset, "\n");
if (haveWideEntries)
indexFd = open(Buffer::build(base, "/", absSeqNum, "_64.index").data(), O_RDONLY | O_LARGEFILE | O_NOATIME);
else
indexFd = open(Buffer::build(base, "/", absSeqNum, ".index").data(), O_RDONLY | O_LARGEFILE | O_NOATIME);
Defer({ if (indexFd != -1) close(indexFd); });
if (indexFd == -1)
{
if (haveWideEntries)
indexFd = open(Buffer::build(base, "/", absSeqNum, "_64.index").data(), O_RDWR | O_LARGEFILE | O_CREAT | O_NOATIME, 0775);
else
indexFd = open(Buffer::build(base, "/", absSeqNum, ".index").data(), O_RDWR | O_LARGEFILE | O_CREAT | O_NOATIME, 0775);
if (indexFd == -1)
throw Switch::system_error("Failed to rebuild index file:", strerror(errno));
if (haveWideEntries)
{
IMPLEMENT_ME();
}
Service::rebuild_index(fdh->fd, indexFd);
}
size = lseek64(indexFd, 0, SEEK_END);
if (unlikely(size == (off64_t)-1))
throw Switch::system_error("lseek64() failed: ", strerror(errno));
Drequire(size < std::numeric_limits<std::remove_reference<decltype(index.fileSize)>::type>::max());
// TODO: if (haveWideEntries), index.lastRecorded.relSeqNum should be a union, and we should
// properly set index.lastRecorded here
require(haveWideEntries == false); // not implemented yet
index.fileSize = size;
index.lastRecorded.relSeqNum = index.lastRecorded.absPhysical = 0;
if (size)
{
auto data = mmap(nullptr, index.fileSize, PROT_READ, MAP_SHARED, indexFd, 0);
if (unlikely(data == MAP_FAILED))
throw Switch::system_error("Failed to access the index file. mmap() failed:", strerror(errno));
index.data = static_cast<const uint8_t *>(data);
if (likely(index.fileSize >= sizeof(uint32_t) + sizeof(uint32_t)))
{
// last entry in the index; very handy
const auto *const p = (uint32_t *)(index.data + index.fileSize - sizeof(uint32_t) - sizeof(uint32_t));
index.lastRecorded.relSeqNum = p[0];
index.lastRecorded.absPhysical = p[1];
if (trace)
SLog("lastRecorded = ", index.lastRecorded.relSeqNum, "(", index.lastRecorded.relSeqNum + baseSeqNum, "), ", index.lastRecorded.absPhysical, "\n");
}
}
else
index.data = nullptr;
}
std::pair<uint32_t, uint32_t> ro_segment::snapDown(const uint64_t absSeqNum) const
{
if (haveWideEntries)
{
if (trace)
SLog("haveWideEntries for ", ptr_repr(this), "\n");
IMPLEMENT_ME();
}
const auto relSeqNum = uint32_t(absSeqNum - baseSeqNum);
if (relSeqNum == baseSeqNum)
{
// optimization
return {relSeqNum, 0};
}
const auto *const all = reinterpret_cast<const index_record *>(index.data);
const auto *const end = all + index.fileSize / sizeof(index_record);
const auto it = std::upper_bound_or_match(all, end, relSeqNum, [](const auto &a, const auto num) {
return TrivialCmp(num, a.relSeqNum);
});
if (it == end)
{
// no index record where record.relSeqNum <= relSeqNum
// that is, the first index record.relSeqNum > relSeqNum
return {0, 0};
}
else
return {it->relSeqNum, it->absPhysical};
}
std::pair<uint32_t, uint32_t> ro_segment::snapUp(const uint64_t absSeqNum) const
{
if (haveWideEntries)
{
IMPLEMENT_ME();
}
const auto relSeqNum = uint32_t(absSeqNum - baseSeqNum);
const auto *const all = reinterpret_cast<const index_record *>(index.data);
const auto *const end = all + index.fileSize / sizeof(index_record);
const auto it = std::lower_bound(all, end, relSeqNum, [](const auto &a, const auto num) {
return a.relSeqNum < num;
});
if (it == end)
{
// no index record where record.relSeqNum >= relSeqNum
// that is, the last index record.relSeqNum < relSeqNum
return {UINT32_MAX, UINT32_MAX};
}
else
return {it->relSeqNum, it->absPhysical};
}
// Searches forward starting from `fileOffset` until it finds a message(set) with absSeqNum > `maxAbsSeqNum`, and
// returns the file offset of that message(which is the end of file before
// that message); also respects maxSize
// TODO: read in 4k chunks/time or something more appropriate
static uint32_t search_before_offset(uint64_t baseSeqNum, const uint32_t maxSize, const uint64_t maxAbsSeqNum, int fd, const uint32_t fileSize, uint32_t fileOffset)
{
uint8_t buf[128];
auto o = fileOffset;
const auto limit = maxSize != UINT32_MAX ? Min<uint32_t>(fileSize, fileOffset + maxSize) : fileSize;
uint64_t lastMsgSeqNum;
if (trace)
SLog("Searching for offset ", maxAbsSeqNum, ", limit = ", limit, "(maxSize = ", maxSize, ", baseSeqNum = ", baseSeqNum, ", fileOffset = ", fileOffset, ")\n");
while (fileOffset < limit)
{
const auto r = pread64(fd, buf, sizeof(buf), fileOffset);
if (unlikely(r == -1))
throw Switch::system_error("pread() failed:", strerror(errno));
const auto *p = buf;
const auto bundleLen = Compression::UnpackUInt32(p);
const auto encodedBundleLenLen = p - buf;
const auto bundleFlags = *p++;
const bool sparseBundleBitSet = bundleFlags & (1u << 6);
uint32_t msgSetSize = (bundleFlags >> 2) & 0xf;
if (!msgSetSize)
msgSetSize = Compression::UnpackUInt32(p);
if (sparseBundleBitSet)
{
const auto firstMsgSeqNum = *(uint64_t *)p;
p += sizeof(uint64_t);
if (msgSetSize != 1)
{
lastMsgSeqNum = firstMsgSeqNum + Compression::UnpackUInt32(p) + 1;
}
else
{
lastMsgSeqNum = firstMsgSeqNum;
}
if (trace)
SLog("sparseBundleBitSet is set, firstMsgSeqNum = ", firstMsgSeqNum, ", lastMsgSeqNum = ", lastMsgSeqNum, "\n");
}
if (trace)
SLog("abs = ", baseSeqNum, "(msgSetSize = ", msgSetSize, ") VS ", maxAbsSeqNum, " at ", o, "\n");
if (baseSeqNum > maxAbsSeqNum)
break;
else
{
if (sparseBundleBitSet)
{
baseSeqNum = lastMsgSeqNum + 1;
}
else
{
baseSeqNum += msgSetSize;
}
fileOffset += bundleLen + encodedBundleLenLen;
}
}
if (trace)
SLog("Returning fileOffset = ", fileOffset, "\n");
return fileOffset;
}
// We are operating on index boundaries, so our res.fileOffset is aligned on an index boundary, which means
// we may stream (0, partition_config::indexInterval] excess bytes.
// This is probably fine, but we may as well
// scan ahead from that fileOffset until we find an more appropriate file offset to begin streaming for, and adjust
// res.fileOffset and res.baseSeqNum accordidly if we can.
//
// Kafka does something similar(see its FileMessageSet.scala#searchFor() impl.)
//
// If we don't adjust_range_start(), we'll avoid the scanning I/O cost, which should be minimal anyway, but we can potentially send
// more data at the expense of network I/O and transfer costs
//
// it returns true if it parsed the first bundle to stream, and that bundle is a sparse bundle (which means
// it encodes the sequence number of its first message in its header)
static bool adjust_range_start(lookup_res &res, const uint64_t absSeqNum)
{
uint64_t baseSeqNum = res.absBaseSeqNum;
if (trace == false) // explicitly allow so that we can verify it does the right thing when tracing
{
if (baseSeqNum == absSeqNum || absSeqNum <= 1)
{
// No need for any adjustments
if (trace)
SLog("No need for any adjustments\n");
return false;
}
}
int fd = res.fdh->fd;
uint8_t tinyBuf[sizeof(uint8_t) + sizeof(uint64_t) + sizeof(uint64_t)];
const auto baseOffset = res.fileOffset;
auto o = baseOffset;
const auto fileOffsetCeiling = res.fileOffsetCeiling;
uint64_t before = trace ? Timings::Microseconds::Tick() : 0, lastMsgSeqNum;
bool firstBundleIsSparse{false};
if (trace)
SLog(ansifmt::bold, ansifmt::color_brown, "About to adjust range fileOffset ", baseOffset, ", absBaseSeqNum(", baseSeqNum, "), absSeqNum(", absSeqNum, ")", ansifmt::reset, "\n");
while (o < fileOffsetCeiling)
{
const auto r = pread64(fd, tinyBuf, sizeof(tinyBuf), o);
if (unlikely(r == -1))
throw Switch::system_error("pread64() failed:", strerror(errno));
const auto *const baseBuf = tinyBuf;
const uint8_t *p = baseBuf;
const auto bundleLen = Compression::UnpackUInt32(p);
require(bundleLen);
const auto encodedBundleLenLen = p - baseBuf;
const auto bundleFlags = *p++;
const bool sparseBundleBitSet = bundleFlags & (1u << 6);
uint32_t msgSetSize = (bundleFlags >> 2) & 0xf;
if (!msgSetSize)
msgSetSize = Compression::UnpackUInt32(p);
if (sparseBundleBitSet)
{
const auto firstMsgSeqNum = *(uint64_t *)p;
p += sizeof(uint64_t);
if (msgSetSize != 1)
{
lastMsgSeqNum = firstMsgSeqNum + Compression::UnpackUInt32(p) + 1;
}
else
{
lastMsgSeqNum = firstMsgSeqNum;
}
if (trace)
SLog("sparseBundleBitSet, firstMsgSeqNum = ", firstMsgSeqNum, ", lastMsgSeqNum, ", lastMsgSeqNum, "\n");
firstBundleIsSparse = true;
}
else
firstBundleIsSparse = false;
const auto nextBundleBaseSeqNum = sparseBundleBitSet ? lastMsgSeqNum + 1 : baseSeqNum + msgSetSize;
if (trace)
SLog("Now at bundle(", baseSeqNum, "), msgSetSize(", msgSetSize, "), bundleFlags(", bundleFlags, "), nextBundleBaseSeqNum = ", nextBundleBaseSeqNum, "\n");
if (absSeqNum >= nextBundleBaseSeqNum)
{
// Our target is in later bundle
if (trace)
SLog("Target in later bundle\n");
o += bundleLen + encodedBundleLenLen;
baseSeqNum = nextBundleBaseSeqNum;
}
else
{
// Our target is in this bundle
if (trace)
SLog("Target in this bundle(", o, ")\n");
res.fileOffset = o;
res.absBaseSeqNum = baseSeqNum;
break;
}
}
if (trace)
SLog(ansifmt::color_blue, "After adjustement, fileOffset ", res.fileOffset, ", absBaseSeqNum(", res.absBaseSeqNum, "), took ", duration_repr(Timings::Microseconds::Since(before)), ansifmt::reset, "\n");
return firstBundleIsSparse;
}
lookup_res topic_partition_log::read_cur(const uint64_t absSeqNum, const uint32_t maxSize, const uint64_t maxAbsSeqNum)
{
// lock is expected to be locked
require(absSeqNum >= cur.baseSeqNum);
if (cur.index.haveWideEntries)
{
// need to use the appropriate skipList64 and a different index encoding format
IMPLEMENT_ME();
}
lookup_res res;
const auto highWatermark = lastAssignedSeqNum;
bool inSkiplist;
const auto relSeqNum = uint32_t(absSeqNum - cur.baseSeqNum);
const auto &skipList = cur.index.skipList;
const auto end = skipList.end();
const auto it = std::upper_bound_or_match(skipList.begin(), end, relSeqNum, [](const auto &a, const auto seqNum) {
return TrivialCmp(seqNum, a.first);
});
res.fdh = cur.fdh;
if (it != end)
{
if (trace)
SLog("Found in skiplist\n");
res.absBaseSeqNum = cur.baseSeqNum + it->first;
res.fileOffset = it->second;
inSkiplist = true;
}
else
{
require(cur.index.ondisk.span); // we checked if it's in this current segment
if (trace)
SLog("Considering ondisk index (cur.fileSize = ", cur.fileSize, ")\n");
const auto size = cur.index.ondisk.span;
const auto *const all = reinterpret_cast<const index_record *>(cur.index.ondisk.data);
const auto *const e = all + size / sizeof(index_record);
const auto i = std::upper_bound_or_match(all, e, relSeqNum, [](const auto &a, const auto seqNum) {
return TrivialCmp(seqNum, a.relSeqNum);
});
if (i != e)
{
if (trace)
SLog("In ondisk index (relSeqNum:", i->relSeqNum, ", absPhysical:", i->absPhysical, ")\n");
res.absBaseSeqNum = cur.baseSeqNum + i->relSeqNum;
res.fileOffset = i->absPhysical;
}
else
{
res.absBaseSeqNum = cur.baseSeqNum;
res.fileOffset = 0;
}
inSkiplist = false;
}
if (maxAbsSeqNum != UINT64_MAX)
{
index_record ref;
if (inSkiplist)
{
const auto it = std::upper_bound_or_match(skipList.begin(), skipList.end(), uint32_t(maxAbsSeqNum - cur.baseSeqNum), [](const auto &a, const auto seqNum) {
return TrivialCmp(seqNum, a.first);
});
ref.relSeqNum = it->first;
ref.absPhysical = it->second;
}
else
{
const auto size = cur.index.ondisk.span;
const auto *const all = reinterpret_cast<const index_record *>(cur.index.ondisk.data);
const auto *const e = all + size / sizeof(index_record);
const auto it = std::upper_bound_or_match(all, e, uint32_t(maxAbsSeqNum - cur.baseSeqNum), [](const auto &a, const uint32_t seqNum) {
return TrivialCmp(seqNum, a.relSeqNum);
});
ref = *it;
}
#if 0
res.fileOffsetCeiling = ref.absPhysical; // XXX: we actually need to set this to (it + 1).absPhysical so that we may not skip a bundle that includes
// both the highwater mark but also messages with seqnum < highwater mark
#else
// Yes, incur some tiny I/O overhead so that we 'll properly cut-off the content
res.fileOffsetCeiling = search_before_offset(cur.baseSeqNum, maxSize, maxAbsSeqNum, cur.fdh->fd, cur.fileSize, ref.absPhysical);
#endif
if (trace)
SLog("maxAbsSeqNum = ", maxAbsSeqNum, " ", res.fileOffsetCeiling, "\n");
}
else
{
res.fileOffsetCeiling = cur.fileSize;
if (trace)
SLog("res.fileOffsetCeiling = ", res.fileOffsetCeiling, "\n");
}
res.highWatermark = highWatermark;
return res;
}
template <typename T>
struct PubSubQueue
{
alignas(64 /* cache line size */) std::atomic<T *> list{nullptr};
void push_back(T *const v)
{
T *old;
do
{
old = list.load(std::memory_order_relaxed);
v->next = old;
} while (!list.compare_exchange_weak(old, v, std::memory_order_release, std::memory_order_relaxed));
}
bool any() const
{
return list.load(std::memory_order_relaxed);
}
inline T *drain()
{
if (!list.load(std::memory_order_relaxed))
return nullptr;
else
return list.exchange(nullptr, std::memory_order_acquire);
}
};
// basic type-erasure for the callable of std::bind
struct mainthread_closure
{
struct callable
{
virtual void invoke() = 0;
virtual ~callable()
{
}
};
template <typename T>
struct internal
: public callable
{
T v;
internal(T &&call)
: v(std::move(call))
{
}
virtual void invoke() override
{
v();
}
};
template <typename T>
mainthread_closure(T &&foo)
: L{new internal<T>(std::move(foo))}
{
}
void operator()()
{
L->invoke();
}
mainthread_closure *next;
std::unique_ptr<callable> L;
};
static PubSubQueue<mainthread_closure> mainThreadClosures;
template <typename F, typename... Arg>
static void run_on_main_thread(F &&l, Arg &&... args)
{
mainThreadClosures.push_back(new mainthread_closure(std::bind(l, std::forward<Arg>(args)...)));
}
static void compact_partition(topic_partition_log *const log, const char *const basePartitionPath, std::vector<ro_segment *> prevSegments)
{
struct msg
{
strwlen8_t key;
uint64_t seqNum;
uint64_t ts;
strwlen32_t content;
};
static constexpr bool trace{false};
uint64_t firstMsgSeqNum, lastMsgSeqNum, msgSeqNum;
range_base<const uint8_t *, size_t> msgSetContent;
strwlen8_t key;
strwlen32_t msgContent, msgValue;
bool anyDropped{false};
std::vector<std::unique_ptr<IOBuffer>> pool;
IOBuffer *cur{nullptr};
size_t base{0};
static constexpr uint64_t ptrBit{uint64_t(1) << (sizeof(uintptr_t) * 8 - 1)};
const auto compact = [&anyDropped](Switch::vector<msg> &msgs) {
std::sort(msgs.begin(), msgs.end(), [](const auto &a, const auto &b) {
return a.key.Cmp(b.key) < 0;
});
auto *out = msgs.data();
for (const auto *it = out, *const e = it + msgs.size(); it != e;)
{
const auto k = it->key;
if (!k)
{
do
{
*out++ = *it;
} while (++it != e && !it->key);
}
else
{
auto last = it->seqNum;
auto sel = it;
for (++it; it != e && it->key == k; ++it)
{
if (it->seqNum > last)
{
last = it->seqNum;
sel = it;
}
}
*out++ = *sel;
}
}
const auto n = out - msgs.data();
if (n == msgs.size())
{
if (!anyDropped)
{
// Nothing to do here, and no tombstones found, no compaction necessary
return false;
}
}
else
{
// need to resize anyway
msgs.resize(n);
std::sort(msgs.begin(), msgs.end(), [](const auto &a, const auto &b) {
return a.seqNum < b.seqNum;
});
}
return true;
};
Switch::vector<msg> msgs;
std::vector<std::pair<void *, size_t>> vmas;
Defer(
{
while (vmas.size())
{
auto it = vmas.back();
madvise(it.first, it.second, MADV_DONTNEED);
munmap(it.first, it.second);
vmas.pop_back();
}
});
if (trace)
SLog(prevSegments.size(), " segments\n");
for (auto it : prevSegments)
{
int fd = it->fdh->fd;
const auto fileSize = it->fileSize;
const auto baseSeqNum = it->baseSeqNum;
auto *const fileData = mmap(nullptr, fileSize, PROT_READ, MAP_SHARED, fd, 0);
if (fileData == MAP_FAILED)
throw Switch::system_error("mmap() failed:", strerror(errno));
vmas.push_back({fileData, fileSize});
if (trace)
SLog("baseSeqNum for segment ", baseSeqNum, "\n");
msgSeqNum = baseSeqNum;
for (const auto *p = static_cast<const uint8_t *>(fileData), *const e = p + fileSize; p != e;)
{
const auto bundleLen = Compression::UnpackUInt32(p);
const auto nextBundle = p + bundleLen;
const auto bundleFlags = *p++;
const auto codec = bundleFlags & 3;
const bool sparseBundleBitSet = bundleFlags & (1u << 6);
uint32_t msgsSetSize = (bundleFlags >> 2) & 0xf;
if (!msgsSetSize)
msgsSetSize = Compression::UnpackUInt32(p);
if (trace)
SLog("New bundle msgSetSize = ", msgsSetSize, ", bundleFlags = ", bundleFlags, ", codec = ", codec, "\n");
if (sparseBundleBitSet)
{
firstMsgSeqNum = *(uint64_t *)p;
p += sizeof(uint64_t);
if (msgsSetSize != 1)
{
lastMsgSeqNum = firstMsgSeqNum + Compression::UnpackUInt32(p) + 1;
}
else
{
lastMsgSeqNum = firstMsgSeqNum;
}
if (trace)
SLog("sparse bundle (first ", firstMsgSeqNum, ", last ", lastMsgSeqNum, ")\n");
}
if (codec)
{
if (!cur || cur->Reserved() > 64 * 1024 * 1024) // XXX: arbitrary
{
const auto n = msgs.size();
while (base != n)
{
auto &it = msgs[base++];
const auto ptr = uintptr_t(it.content.p);
const auto to = ptr & (~ptrBit);
if (ptr != to)
it.content.p = cur->At(to);
if (it.key)
{
const auto ptr = uintptr_t(it.key.p);
const auto to = ptr & (~ptrBit);
if (ptr != to)
it.key.p = cur->At(to);
}
}
auto owner = std::make_unique<IOBuffer>();
cur = owner.get();
pool.push_back(std::move(owner));
}
const auto len = cur->size();
if (!Compression::UnCompress(Compression::Algo::SNAPPY, p, nextBundle - p, cur))
throw Switch::system_error("failed to decompress message set");
msgSetContent.Set(reinterpret_cast<const uint8_t *>(cur->at(len)), cur->size() - len);
}
else
{
msgSetContent.Set(p, nextBundle - p);
}
p = nextBundle;
uint64_t msgTs{0};
uint32_t msgIdx{0};
const auto *const ptrBase = cur ? cur->data() : nullptr;
if (trace)
SLog("Parsing Message Set\n");
for (const auto *p = msgSetContent.offset, *const e = p + msgSetContent.len; p != e; ++msgIdx, ++msgSeqNum)
{
const auto flags = *p++;
if (trace)
SLog("Message ", msgIdx, ", flags ", flags, "\n");
if (sparseBundleBitSet)
{
if (msgIdx == 0)
msgSeqNum = firstMsgSeqNum;
else if (msgIdx == msgsSetSize - 1)
msgSeqNum = lastMsgSeqNum;
else if (flags & uint8_t(TankFlags::BundleMsgFlags::SeqNumPrevPlusOne))
{
// incremented in for()
if (trace)
SLog("SeqNumPrevPlusOne set\n");
}
else
{
// we encode delta from last - 1, but we already ++msgSeqNum in for()
msgSeqNum += Compression::UnpackUInt32(p);
if (trace)
SLog("Adjusting delta\n");
}
}
if (trace)
SLog("SeqNum = ", msgSeqNum, "\n");
if (!(flags & uint8_t(TankFlags::BundleMsgFlags::UseLastSpecifiedTS)))
{
msgTs = *(uint64_t *)p;
p += sizeof(uint64_t);
}
if (flags & uint8_t(TankFlags::BundleMsgFlags::HaveKey))
{
key.Set((char *)p + 1, *p);
p += key.len + sizeof(uint8_t);
if (trace)
SLog("MSG ", msgSeqNum, ", key [", key, "] ", Date::ts_repr(Timings::Milliseconds::ToSeconds(msgTs)), "\n");
if (codec)
key.p = (char *)uintptr_t(key.p - ptrBase);
}
else
{
key.reset();
}
const auto msgLen = Compression::UnpackUInt32(p);
if (msgLen || !key)
{
msgValue.Set((char *)p, msgLen);
p += msgLen;
if (trace)
SLog("value [", msgValue, "]\n");
if (codec)
msgValue.p = (char *)uintptr_t(msgValue.p - ptrBase);
msgs.push_back({key, msgSeqNum, msgTs, msgValue});
}
else
{
// Drop deleted messages(messages with a key and no content)
anyDropped = true;
}
}
}
}
if (cur)
{
const auto n = msgs.size();
while (base != n)
{
auto &it = msgs[base++];
const auto ptr = uintptr_t(it.content.p);
const auto to = ptr & (~ptrBit);
if (ptr != to)
it.content.p = cur->At(to);
if (it.key)
{
const auto ptr = uintptr_t(it.key.p);
const auto to = ptr & (~ptrBit);
if (ptr != to)
it.key.p = cur->At(to);
}
}
}
if (!compact(msgs))
{
#if 1
if (trace)
SLog("No need for compaction\n");
run_on_main_thread([log]() {
log->compacting = false;
Print("Did not need to compact log\n");
});
return;
#else
Print("ENABLE AGAIN\n");
std::sort(msgs.begin(), msgs.end(), [](const auto &a, const auto &b) {
return a.seqNum < b.seqNum;
});
#endif
}
if (trace)
{
for (const auto &it : msgs)
Print(it.seqNum, " [", it.key, "] [", it.content, "]\n");
}
// go through all segments, rebuild each of them by keeping only the messages that existed in that segment (we can just use a range check for first available, last assigned)
// but if after compaction a segment's too small (in terms of file size), then include into it messages from successive segments, and in that case
// use the last segment's timestamp that is to be encoded in the filename
static constexpr size_t sinceLastUpdateBytesThreshold{10000}, sinceLastUpdateMsgsCntThreshold{128}, maxBundleMsgsSetSize{5}, maxBundleMsgsSetSizeBytes{65536}; // XXX: arbitrary
static constexpr size_t minSegmentLogFileSize{64 * 1024}; // XXX: arbitrary
std::vector<ro_segment *> newSegments;
int fd;
char logPath[PATH_MAX];
const auto n = msgs.size();
const auto *const all = msgs.data();
IOBuffer out, cbuf, index;
struct iovec iov[1024];
uint32_t iovLen{0};
const auto flush = [&iovLen, &iov, &out, &cbuf, &fd]() {
for (uint32_t i{0}; i != iovLen; ++i)
{
auto &it = iov[i];
auto ptr = uintptr_t(it.iov_base);
if (ptr & (1u << 31))
{
ptr &= ~(1u << 31);
it.iov_base = out.At(ptr);
}
else
{
ptr &= ~(1u << 30);
it.iov_base = cbuf.At(ptr);
}
}
if (trace)
SLog("Flushing ", iovLen, "\n");
const auto r = writev(fd, iov, iovLen);
if (unlikely(r == -1))
throw Switch::system_error("writev() failed:", strerror(errno));
out.clear();
cbuf.clear();
iovLen = 0;
};
try
{
const char *destPartitionPath;
uint32_t curSegmentIdx{0};
#if 0
if (getenv("FOOOOO"))
destPartitionPath = "/tmp/foo/0/";
else
{
destPartitionPath = "/tmp/tankREPO/msgs/0/";
}
#else
destPartitionPath = basePartitionPath;
#endif
// Process all collected messages, pack into segments
for (uint32_t i{0}; i != n;)
{
uint8_t bundleFlags;
size_t outFileSize{0};
size_t sinceLastUpdateBytes{UINT32_MAX}, sinceLastUpdateMsgsCnt{UINT32_MAX};
auto curSegment = prevSegments[curSegmentIdx];
const auto baseSeqNum{all[i].seqNum};
auto curSegmentLastAvailSeqNum = curSegment->lastAvailSeqNum;
index_record indexLastRecorded;
auto expected = all[i].seqNum;
if (trace)
SLog(ansifmt::bold, ansifmt::color_blue, "Now processing segment ", curSegmentIdx, "/", prevSegments.size(), " (", baseSeqNum, ", ", curSegment->lastAvailSeqNum, ")", ansifmt::reset, "\n");
// new segment
index.clear();
out.clear();