-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
sstables.cc
3132 lines (2732 loc) · 129 KB
/
sstables.cc
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
/*
* Copyright (C) 2015-present ScyllaDB
*/
/*
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
#include "log.hh"
#include <concepts>
#include <vector>
#include <typeinfo>
#include <limits>
#include <seastar/core/future.hh>
#include <seastar/core/future-util.hh>
#include <seastar/core/sstring.hh>
#include <seastar/core/fstream.hh>
#include <seastar/core/shared_ptr.hh>
#include <seastar/core/shared_ptr_incomplete.hh>
#include <seastar/core/do_with.hh>
#include <seastar/core/thread.hh>
#include <seastar/core/byteorder.hh>
#include <seastar/core/aligned_buffer.hh>
#include <seastar/core/metrics.hh>
#include <seastar/core/reactor.hh>
#include <seastar/coroutine/all.hh>
#include <seastar/util/file.hh>
#include <seastar/util/closeable.hh>
#include <seastar/util/short_streams.hh>
#include <iterator>
#include <seastar/core/coroutine.hh>
#include <seastar/coroutine/maybe_yield.hh>
#include <seastar/coroutine/parallel_for_each.hh>
#include <seastar/coroutine/as_future.hh>
#include "data_dictionary/storage_options.hh"
#include "dht/sharder.hh"
#include "writer.hh"
#include "m_format_read_helpers.hh"
#include "open_info.hh"
#include "sstables.hh"
#include "sstable_writer.hh"
#include "sstable_version.hh"
#include "metadata_collector.hh"
#include "progress_monitor.hh"
#include "compress.hh"
#include "unimplemented.hh"
#include "index_reader.hh"
#include "replica/memtable.hh"
#include "downsampling.hh"
#include <boost/algorithm/string.hpp>
#include <boost/range/adaptor/map.hpp>
#include <boost/range/adaptor/transformed.hpp>
#include <boost/range/algorithm_ext/is_sorted.hpp>
#include <boost/range/algorithm/sort.hpp>
#include <boost/regex.hpp>
#include <seastar/core/align.hh>
#include "mutation/range_tombstone_list.hh"
#include "counters.hh"
#include "binary_search.hh"
#include "utils/bloom_filter.hh"
#include "utils/cached_file.hh"
#include "utils/stall_free.hh"
#include "checked-file-impl.hh"
#include "db/extensions.hh"
#include "unimplemented.hh"
#include "vint-serialization.hh"
#include "db/large_data_handler.hh"
#include "db/config.hh"
#include "sstables/random_access_reader.hh"
#include "sstables/sstables_manager.hh"
#include "sstables/partition_index_cache.hh"
#include "utils/UUID_gen.hh"
#include "sstables_manager.hh"
#include <boost/algorithm/string/predicate.hpp>
#include "tracing/traced_file.hh"
#include "kl/reader.hh"
#include "mx/reader.hh"
#include "utils/bit_cast.hh"
#include "utils/cached_file.hh"
#include "tombstone_gc.hh"
#include "reader_concurrency_semaphore.hh"
#include "readers/reversing_v2.hh"
#include "readers/forwardable_v2.hh"
#include "release.hh"
#include "utils/build_id.hh"
thread_local disk_error_signal_type sstable_read_error;
thread_local disk_error_signal_type sstable_write_error;
namespace sstables {
// The below flag governs the mode of index file page caching used by the index
// reader.
//
// If set to true, the reader will read and/or populate a common global cache,
// which shares its capacity with the row cache. If false, the reader will use
// BYPASS CACHE semantics for index caching.
//
// This flag is intended to be a temporary hack. The goal is to eventually
// solve index caching problems via a smart cache replacement policy.
//
thread_local utils::updateable_value<bool> global_cache_index_pages(false);
logging::logger sstlog("sstable");
// Because this is a noop and won't hold any state, it is better to use a global than a
// thread_local. It will be faster, specially on non-x86.
struct noop_write_monitor final : public write_monitor {
virtual void on_write_started(const writer_offset_tracker&) override { };
virtual void on_data_write_completed() override { }
};
static noop_write_monitor default_noop_write_monitor;
write_monitor& default_write_monitor() {
return default_noop_write_monitor;
}
static noop_read_monitor default_noop_read_monitor;
read_monitor& default_read_monitor() {
return default_noop_read_monitor;
}
static no_read_monitoring noop_read_monitor_generator;
read_monitor_generator& default_read_monitor_generator() {
return noop_read_monitor_generator;
}
future<file> sstable::new_sstable_component_file(const io_error_handler& error_handler, component_type type, open_flags flags, file_open_options options) noexcept {
try {
auto f = _storage->open_component(*this, type, flags, options, _manager.config().enable_sstable_data_integrity_check());
if (type != component_type::TOC && type != component_type::TemporaryTOC) {
for (auto * ext : _manager.config().extensions().sstable_file_io_extensions()) {
f = with_file_close_on_failure(std::move(f), [ext, this, type, flags] (file f) {
return ext->wrap_file(*this, type, f, flags).then([f](file nf) mutable {
return nf ? nf : std::move(f);
});
});
}
}
f = with_file_close_on_failure(std::move(f), [&error_handler] (file f) {
return make_checked_file(error_handler, std::move(f));
});
return f.handle_exception([this, type] (auto ep) {
sstlog.error("Could not create SSTable component {}. Found exception: {}", filename(type), ep);
return make_exception_future<file>(ep);
});
} catch (...) {
return current_exception_as_future<file>();
}
}
const std::unordered_map<sstable_version_types, sstring, enum_hash<sstable_version_types>> version_string = {
{ sstable_version_types::ka , "ka" },
{ sstable_version_types::la , "la" },
{ sstable_version_types::mc , "mc" },
{ sstable_version_types::md , "md" },
{ sstable_version_types::me , "me" },
};
const std::unordered_map<sstable_format_types, sstring, enum_hash<sstable_format_types>> format_string = {
{ sstable_format_types::big , "big" }
};
// This assumes that the mappings are small enough, and called unfrequent
// enough. If that changes, it would be adviseable to create a full static
// reverse mapping, even if it is done at runtime.
template <typename Map, std::equality_comparable_with<typename Map::mapped_type> Value>
static typename Map::key_type reverse_map(const Value& v, const Map& map) {
for (auto& [key, value]: map) {
if (value == v) {
return key;
}
}
throw std::out_of_range("unable to reverse map");
}
// This should be used every time we use read_exactly directly.
//
// read_exactly is a lot more convenient of an interface to use, because we'll
// be parsing known quantities.
//
// However, anything other than the size we have asked for, is certainly a bug,
// and we need to do something about it.
static void check_buf_size(temporary_buffer<char>& buf, size_t expected) {
if (buf.size() < expected) {
throw bufsize_mismatch_exception(buf.size(), expected);
}
}
template <typename T>
requires std::is_integral_v<T>
future<> parse(const schema&, sstable_version_types v, random_access_reader& in, T& i) {
return in.read_exactly(sizeof(T)).then([&i] (auto buf) {
check_buf_size(buf, sizeof(T));
i = net::ntoh(read_unaligned<T>(buf.get()));
return make_ready_future<>();
});
}
template <typename T>
requires std::is_enum_v<T>
future<> parse(const schema& s, sstable_version_types v, random_access_reader& in, T& i) {
return in.read_exactly(sizeof(T)).then([&i] (auto buf) {
check_buf_size(buf, sizeof(T));
i = static_cast<T>(net::ntoh(read_unaligned<std::underlying_type_t<T>>(buf.get())));
return make_ready_future<>();
});
}
future<> parse(const schema& s, sstable_version_types v, random_access_reader& in, bool& i) {
return parse(s, v, in, reinterpret_cast<uint8_t&>(i));
}
future<> parse(const schema&, sstable_version_types, random_access_reader& in, double& d) {
return in.read_exactly(sizeof(double)).then([&d] (auto buf) {
check_buf_size(buf, sizeof(double));
unsigned long nr = read_unaligned<unsigned long>(buf.get());
d = std::bit_cast<double>(net::ntoh(nr));
return make_ready_future<>();
});
}
template <typename T>
future<> parse(const schema&, sstable_version_types, random_access_reader& in, T& len, bytes& s) {
return in.read_exactly(len).then([&s, len] (auto buf) {
check_buf_size(buf, len);
// Likely a different type of char. Most bufs are unsigned, whereas the bytes type is signed.
s = bytes(reinterpret_cast<const bytes::value_type *>(buf.get()), len);
});
}
// All composite parsers must come after this
template<typename First, typename... Rest>
future<> parse(const schema& s, sstable_version_types v, random_access_reader& in, First& first, Rest&&... rest) {
return parse(s, v, in, first).then([v, &s, &in, &rest...] {
return parse(s, v, in, std::forward<Rest>(rest)...);
});
}
// Intended to be used for a type that describes itself through describe_type().
template <self_describing T>
future<>
parse(const schema& s, sstable_version_types v, random_access_reader& in, T& t) {
return t.describe_type(v, [v, &s, &in] (auto&&... what) -> future<> {
return parse(s, v, in, what...);
});
}
template <class T>
future<> parse(const schema&, sstable_version_types v, random_access_reader& in, vint<T>& t) {
return read_vint(in, t.value);
}
future<> parse(const schema&, sstable_version_types, random_access_reader& in, utils::UUID& uuid) {
return in.read_exactly(uuid.serialized_size()).then([&uuid] (temporary_buffer<char> buf) {
check_buf_size(buf, utils::UUID::serialized_size());
uuid = utils::UUID_gen::get_UUID(const_cast<int8_t*>(reinterpret_cast<const int8_t*>(buf.get())));
});
}
template <typename Tag>
future<> parse(const schema& s, sstable_version_types v, random_access_reader& in, utils::tagged_uuid<Tag>& id) {
// Read directly into tha tagged_uuid `id` member
// This is ugly, but save an allocation or reimplementation
// of parse(..., utils::UUID&)
utils::UUID& uuid = *const_cast<utils::UUID*>(&id.uuid());
return parse(s, v, in, uuid);
}
// For all types that take a size, we provide a template that takes the type
// alone, and another, separate one, that takes a size parameter as well, of
// type Size. This is because although most of the time the size and the data
// are contiguous, it is not always the case. So we want to have the
// flexibility of parsing them separately.
template <typename Size>
future<> parse(const schema& schema, sstable_version_types v, random_access_reader& in, disk_string<Size>& s) {
auto len = std::make_unique<Size>();
auto f = parse(schema, v, in, *len);
return f.then([v, &schema, &in, &s, len = std::move(len)] {
return parse(schema, v, in, *len, s.value);
});
}
future<> parse(const schema& schema, sstable_version_types v, random_access_reader& in, disk_string_vint_size& s) {
auto len = std::make_unique<uint64_t>();
auto f = read_vint(in, *len);
return f.then([v, &schema, &in, &s, len = std::move(len)] {
return parse(schema, v, in, *len, s.value);
});
}
template <typename Members>
future<> parse(const schema& s, sstable_version_types v, random_access_reader& in, disk_array_vint_size<Members>& arr) {
auto len = std::make_unique<uint64_t>();
auto f = read_vint(in, *len);
return f.then([v, &s, &in, &arr, len = std::move(len)] {
return parse(s, v, in, *len, arr.elements);
});
}
// We cannot simply read the whole array at once, because we don't know its
// full size. We know the number of elements, but if we are talking about
// disk_strings, for instance, we have no idea how much of the stream each
// element will take.
//
// Sometimes we do know the size, like the case of integers. There, all we have
// to do is to convert each member because they are all stored big endian.
// We'll offer a specialization for that case below.
template <typename Size, typename Members>
future<>
parse(const schema& s, sstable_version_types v, random_access_reader& in, Size& len, utils::chunked_vector<Members>& arr) {
for (auto count = len; count; count--) {
arr.emplace_back();
co_await parse(s, v, in, arr.back());
}
}
template <typename Size, std::integral Members>
future<>
parse(const schema&, sstable_version_types, random_access_reader& in, Size& len, utils::chunked_vector<Members>& arr) {
Size now = arr.max_chunk_capacity();
for (auto count = len; count; count -= now) {
if (now > count) {
now = count;
}
auto buf = co_await in.read_exactly(now * sizeof(Members));
check_buf_size(buf, now * sizeof(Members));
for (size_t i = 0; i < now; ++i) {
arr.push_back(net::ntoh(read_unaligned<Members>(buf.get() + i * sizeof(Members))));
}
}
}
template <typename Contents>
future<> parse(const schema& s, sstable_version_types v, random_access_reader& in, std::optional<Contents>& opt) {
bool engaged;
co_await parse(s, v, in, engaged);
if (engaged) {
opt.emplace();
co_await parse(s, v, in, *opt);
} else {
opt.reset();
}
}
// We resize the array here, before we pass it to the integer / non-integer
// specializations
template <typename Size, typename Members>
future<> parse(const schema& s, sstable_version_types v, random_access_reader& in, disk_array<Size, Members>& arr) {
Size len;
co_await parse(s, v, in, len);
arr.elements.reserve(len);
co_await parse(s, v, in, len, arr.elements);
}
template <typename Size, typename Key, typename Value>
future<> parse(const schema& s, sstable_version_types v, random_access_reader& in, Size& len, std::unordered_map<Key, Value>& map) {
for (auto count = len; count; count--) {
Key key;
Value value;
co_await parse(s, v, in, key, value);
map.emplace(key, value);
}
}
template <typename First, typename Second>
future<> parse(const schema& s, sstable_version_types v, random_access_reader& in, std::pair<First, Second>& p) {
return parse(s, v, in, p.first, p.second);
}
template <typename Size, typename Key, typename Value>
future<> parse(const schema& s, sstable_version_types v, random_access_reader& in, disk_hash<Size, Key, Value>& h) {
Size w;
co_await parse(s, v, in, w);
co_await parse(s, v, in, w, h.map);
}
// Abstract parser/sizer/writer for a single tagged member of a tagged union
template <typename DiskSetOfTaggedUnion>
struct single_tagged_union_member_serdes {
using value_type = typename DiskSetOfTaggedUnion::value_type;
virtual ~single_tagged_union_member_serdes() {}
virtual future<> do_parse(const schema& s, sstable_version_types version, random_access_reader& in, value_type& v) const = 0;
virtual uint32_t do_size(sstable_version_types version, const value_type& v) const = 0;
virtual void do_write(sstable_version_types version, file_writer& out, const value_type& v) const = 0;
};
// Concrete parser for a single member of a tagged union; parses type "Member"
template <typename DiskSetOfTaggedUnion, typename Member>
struct single_tagged_union_member_serdes_for final : single_tagged_union_member_serdes<DiskSetOfTaggedUnion> {
using base = single_tagged_union_member_serdes<DiskSetOfTaggedUnion>;
using value_type = typename base::value_type;
virtual future<> do_parse(const schema& s, sstable_version_types version, random_access_reader& in, value_type& v) const override {
v = Member();
return parse(s, version, in, boost::get<Member>(v).value);
}
virtual uint32_t do_size(sstable_version_types version, const value_type& v) const override {
return serialized_size(version, boost::get<Member>(v).value);
}
virtual void do_write(sstable_version_types version, file_writer& out, const value_type& v) const override {
write(version, out, boost::get<Member>(v).value);
}
};
template <typename TagType, typename... Members>
struct disk_set_of_tagged_union<TagType, Members...>::serdes {
using disk_set = disk_set_of_tagged_union<TagType, Members...>;
// We can't use unique_ptr, because we initialize from an std::intializer_list, which is not move compatible.
using serdes_map_type = std::unordered_map<TagType, shared_ptr<single_tagged_union_member_serdes<disk_set>>, typename disk_set::hash_type>;
using value_type = typename disk_set::value_type;
serdes_map_type map = {
{Members::tag(), make_shared<single_tagged_union_member_serdes_for<disk_set, Members>>()}...
};
future<> lookup_and_parse(const schema& schema, sstable_version_types v, random_access_reader& in, TagType tag, uint32_t& size, disk_set& s, value_type& value) const {
auto i = map.find(tag);
if (i == map.end()) {
return in.read_exactly(size).discard_result();
} else {
return i->second->do_parse(schema, v, in, value).then([tag, &s, &value] () mutable {
s.data.emplace(tag, std::move(value));
});
}
}
uint32_t lookup_and_size(sstable_version_types v, TagType tag, const value_type& value) const {
return map.at(tag)->do_size(v, value);
}
void lookup_and_write(sstable_version_types v, file_writer& out, TagType tag, const value_type& value) const {
return map.at(tag)->do_write(v, out, value);
}
};
template <typename TagType, typename... Members>
typename disk_set_of_tagged_union<TagType, Members...>::serdes disk_set_of_tagged_union<TagType, Members...>::s_serdes;
template <typename TagType, typename... Members>
future<>
parse(const schema& schema, sstable_version_types v, random_access_reader& in, disk_set_of_tagged_union<TagType, Members...>& s) {
using disk_set = disk_set_of_tagged_union<TagType, Members...>;
using key_type = typename disk_set::key_type;
using value_type = typename disk_set::value_type;
key_type nr_elements;
co_await parse(schema, v, in, nr_elements);
for ([[maybe_unused]] auto _ : boost::irange<key_type>(0, nr_elements)) {
key_type new_key;
unsigned new_size;
co_await parse(schema, v, in, new_key);
co_await parse(schema, v, in, new_size);
value_type new_value;
co_await disk_set::s_serdes.lookup_and_parse(schema, v, in, TagType(new_key), new_size, s, new_value);
}
}
template <typename TagType, typename... Members>
void write(sstable_version_types v, file_writer& out, const disk_set_of_tagged_union<TagType, Members...>& s) {
using disk_set = disk_set_of_tagged_union<TagType, Members...>;
write(v, out, uint32_t(s.data.size()));
for (auto&& kv : s.data) {
auto&& tag = kv.first;
auto&& value = kv.second;
write(v, out, tag);
write(v, out, uint32_t(disk_set::s_serdes.lookup_and_size(v, tag, value)));
disk_set::s_serdes.lookup_and_write(v, out, tag, value);
}
}
future<> parse(const schema& schema, sstable_version_types v, random_access_reader& in, summary& s) {
using pos_type = typename decltype(summary::positions)::value_type;
co_await parse(schema, v, in, s.header.min_index_interval,
s.header.size,
s.header.memory_size,
s.header.sampling_level,
s.header.size_at_full_sampling);
auto buf = co_await in.read_exactly(s.header.size * sizeof(pos_type));
auto len = s.header.size * sizeof(pos_type);
check_buf_size(buf, len);
// Positions are encoded in little-endian.
auto b = buf.get();
s.positions = utils::chunked_vector<pos_type>();
while (s.positions.size() != s.header.size) {
s.positions.push_back(seastar::read_le<pos_type>(b));
b += sizeof(pos_type);
co_await coroutine::maybe_yield();
}
// Since the keys in the index are not sized, we need to calculate
// the start position of the index i+1 to determine the boundaries
// of index i. The "memory_size" field in the header determines the
// total memory used by the map, so if we push it to the vector, we
// can guarantee that no conditionals are used, and we can always
// query the position of the "next" index.
s.positions.push_back(s.header.memory_size);
co_await in.seek(sizeof(summary::header) + s.header.memory_size);
co_await parse(schema, v, in, s.first_key, s.last_key);
co_await in.seek(s.positions[0] + sizeof(summary::header));
s.entries.reserve(s.header.size);
int idx = 0;
while (s.entries.size() != s.header.size) {
auto pos = s.positions[idx++];
auto next = s.positions[idx];
auto entrysize = next - pos;
auto buf = co_await in.read_exactly(entrysize);
check_buf_size(buf, entrysize);
auto keysize = entrysize - 8;
auto key_data = s.add_summary_data(bytes_view(reinterpret_cast<const int8_t*>(buf.get()), keysize));
buf.trim_front(keysize);
// position is little-endian encoded
auto position = seastar::read_le<uint64_t>(buf.get());
auto token = schema.get_partitioner().get_token(key_view(key_data));
s.entries.push_back(summary_entry{ token, key_data, position });
}
// Delete last element which isn't part of the on-disk format.
s.positions.pop_back();
}
inline void write(sstable_version_types v, file_writer& out, const summary_entry& entry) {
// FIXME: summary entry is supposedly written in memory order, but that
// would prevent portability of summary file between machines of different
// endianness. We can treat it as little endian to preserve portability.
write(v, out, entry.key);
auto p = seastar::cpu_to_le<uint64_t>(entry.position);
out.write(reinterpret_cast<const char*>(&p), sizeof(p));
}
inline void write(sstable_version_types v, file_writer& out, const summary& s) {
// NOTE: positions and entries must be stored in LITTLE-ENDIAN.
write(v, out, s.header.min_index_interval,
s.header.size,
s.header.memory_size,
s.header.sampling_level,
s.header.size_at_full_sampling);
for (auto&& e : s.positions) {
auto p = seastar::cpu_to_le(e);
out.write(reinterpret_cast<const char*>(&p), sizeof(p));
}
write(v, out, s.entries);
write(v, out, s.first_key, s.last_key);
}
future<summary_entry&> sstable::read_summary_entry(size_t i) {
// The last one is the boundary marker
if (i >= (_components->summary.entries.size())) {
return make_exception_future<summary_entry&>(std::out_of_range(format("Invalid Summary index: {:d}", i)));
}
return make_ready_future<summary_entry&>(_components->summary.entries[i]);
}
future<> parse(const schema& s, sstable_version_types v, random_access_reader& in, deletion_time& d) {
return parse(s, v, in, d.local_deletion_time, d.marked_for_delete_at);
}
template <typename Child>
future<> parse(const schema& s, sstable_version_types v, random_access_reader& in, std::unique_ptr<metadata>& p) {
p.reset(new Child);
return parse(s, v, in, *static_cast<Child *>(p.get()));
}
template <typename Child>
inline void write(sstable_version_types v, file_writer& out, const std::unique_ptr<metadata>& p) {
write(v, out, *static_cast<Child *>(p.get()));
}
future<> parse(const schema& schema, sstable_version_types v, random_access_reader& in, statistics& s) {
try {
co_await parse(schema, v, in, s.offsets);
// Old versions of Scylla do not respect the order.
// See https://github.com/scylladb/scylla/issues/3937
boost::sort(s.offsets.elements, [] (auto&& e1, auto&& e2) { return e1.first < e2.first; });
for (auto val : s.offsets.elements) {
auto type = val.first;
co_await in.seek(val.second);
switch (type) {
case metadata_type::Validation:
co_await parse<validation_metadata>(schema, v, in, s.contents[type]);
break;
case metadata_type::Compaction:
co_await parse<compaction_metadata>(schema, v, in, s.contents[type]);
break;
case metadata_type::Stats:
co_await parse<stats_metadata>(schema, v, in, s.contents[type]);
break;
case metadata_type::Serialization:
if (v < sstable_version_types::mc) {
throw malformed_sstable_exception(
"Statistics is malformed: SSTable is in 2.x format but contains serialization header.");
} else {
co_await parse<serialization_header>(schema, v, in, s.contents[type]);
}
break;
default:
throw malformed_sstable_exception(fmt::format("Invalid metadata type at Statistics file: {} ", int(type)));
}
}
} catch (const malformed_sstable_exception&) {
throw;
} catch (...) {
throw malformed_sstable_exception(fmt::format("Statistics file is malformed: {}", std::current_exception()));
}
}
inline void write(sstable_version_types v, file_writer& out, const statistics& s) {
write(v, out, s.offsets);
for (auto&& e : s.offsets.elements) {
s.contents.at(e.first)->write(v, out);
}
}
future<> parse(const schema& s, sstable_version_types v, random_access_reader& in, utils::estimated_histogram& eh) {
auto len = std::make_unique<uint32_t>();
co_await parse(s, v, in, *len);
uint32_t length = *len;
if (length == 0) {
co_await coroutine::return_exception(malformed_sstable_exception("Estimated histogram with zero size found. Can't continue!"));
}
// Arrays are potentially pre-initialized by the estimated_histogram constructor.
eh.bucket_offsets.clear();
eh.buckets.clear();
eh.bucket_offsets.reserve(length - 1);
eh.buckets.reserve(length);
auto type_size = sizeof(uint64_t) * 2;
auto buf = co_await in.read_exactly(length * type_size);
check_buf_size(buf, length * type_size);
size_t j = 0;
while (eh.buckets.size() != length) {
auto offset = net::ntoh(read_unaligned<uint64_t>(buf.get() + (j++) * sizeof(uint64_t)));
auto bucket = net::ntoh(read_unaligned<uint64_t>(buf.get() + (j++) * sizeof(uint64_t)));
if (!eh.buckets.empty()) {
eh.bucket_offsets.push_back(offset);
}
eh.buckets.push_back(bucket);
co_await coroutine::maybe_yield();
}
}
void write(sstable_version_types v, file_writer& out, const utils::estimated_histogram& eh) {
uint32_t len = 0;
check_truncate_and_assign(len, eh.buckets.size());
write(v, out, len);
struct element {
int64_t offsets;
int64_t buckets;
};
std::vector<element> elements;
elements.reserve(eh.buckets.size());
const int64_t* offsets_nr = eh.bucket_offsets.data();
const int64_t* buckets_nr = eh.buckets.data();
for (size_t i = 0; i < eh.buckets.size(); i++) {
auto offsets = net::hton(offsets_nr[i == 0 ? 0 : i - 1]);
auto buckets = net::hton(buckets_nr[i]);
elements.emplace_back(element{offsets, buckets});
if (need_preempt()) {
seastar::thread::yield();
}
}
auto p = reinterpret_cast<const char*>(elements.data());
auto bytes = elements.size() * sizeof(element);
out.write(p, bytes);
}
struct streaming_histogram_element {
using key_type = typename decltype(utils::streaming_histogram::bin)::key_type;
using value_type = typename decltype(utils::streaming_histogram::bin)::mapped_type;
key_type key;
value_type value;
template <typename Describer>
auto describe_type(sstable_version_types v, Describer f) { return f(key, value); }
};
future<> parse(const schema& s, sstable_version_types v, random_access_reader& in, utils::streaming_histogram& sh) {
auto a = disk_array<uint32_t, streaming_histogram_element>();
co_await parse(s, v, in, sh.max_bin_size, a);
auto length = a.elements.size();
if (length > sh.max_bin_size) {
co_await coroutine::return_exception(malformed_sstable_exception("Streaming histogram with more entries than allowed. Can't continue!"));
}
// Find bad histogram which had incorrect elements merged due to use of
// unordered map. The keys will be unordered. Histogram which size is
// less than max allowed will be correct because no entries needed to be
// merged, so we can avoid discarding those.
// look for commit with title 'streaming_histogram: fix update' for more details.
auto possibly_broken_histogram = length == sh.max_bin_size;
auto less_comp = [] (auto& x, auto& y) { return x.key < y.key; };
if (possibly_broken_histogram && !boost::is_sorted(a.elements, less_comp)) {
co_return;
}
auto transform = [] (auto element) -> std::pair<streaming_histogram_element::key_type, streaming_histogram_element::value_type> {
return { element.key, element.value };
};
boost::copy(a.elements | boost::adaptors::transformed(transform), std::inserter(sh.bin, sh.bin.end()));
}
void write(sstable_version_types v, file_writer& out, const utils::streaming_histogram& sh) {
uint32_t max_bin_size;
check_truncate_and_assign(max_bin_size, sh.max_bin_size);
disk_array<uint32_t, streaming_histogram_element> a;
a.elements = boost::copy_range<utils::chunked_vector<streaming_histogram_element>>(sh.bin
| boost::adaptors::transformed([&] (auto& kv) { return streaming_histogram_element{kv.first, kv.second}; }));
write(v, out, max_bin_size, a);
}
future<> parse(const schema& s, sstable_version_types v, random_access_reader& in, commitlog_interval& ci) {
co_await parse(s, v, in, ci.start);
co_await parse(s, v, in, ci.end);
}
void write(sstable_version_types v, file_writer& out, const commitlog_interval& ci) {
write(v, out, ci.start);
write(v, out, ci.end);
}
future<> parse(const schema& s, sstable_version_types v, random_access_reader& in, compression& c) {
uint64_t data_len = 0;
uint32_t chunk_len = 0;
co_await parse(s, v, in, c.name, c.options, chunk_len, data_len);
c.set_uncompressed_chunk_length(chunk_len);
c.set_uncompressed_file_length(data_len);
uint32_t len = 0;
compression::segmented_offsets::writer offsets = c.offsets.get_writer();
co_await parse(s, v, in, len);
auto eoarr = [&c, &len] { return c.offsets.size() == len; };
while (!eoarr()) {
auto now = std::min(len - c.offsets.size(), 100000 / sizeof(uint64_t));
auto buf = co_await in.read_exactly(now * sizeof(uint64_t));
for (size_t i = 0; i < now; ++i) {
uint64_t value = read_unaligned<uint64_t>(buf.get() + i * sizeof(uint64_t));
offsets.push_back(net::ntoh(value));
}
}
}
void write(sstable_version_types v, file_writer& out, const compression& c) {
write(v, out, c.name, c.options, c.uncompressed_chunk_length(), c.uncompressed_file_length());
write(v, out, static_cast<uint32_t>(c.offsets.size()));
std::vector<uint64_t> tmp;
const size_t per_loop = 100000 / sizeof(uint64_t);
tmp.resize(per_loop);
size_t idx = 0;
while (idx != c.offsets.size()) {
auto now = std::min(c.offsets.size() - idx, per_loop);
// copy offsets into tmp converting each entry into big-endian representation.
auto nr = c.offsets.begin() + idx;
for (size_t i = 0; i < now; i++) {
tmp[i] = net::hton(nr[i]);
}
auto p = reinterpret_cast<const char*>(tmp.data());
auto bytes = now * sizeof(uint64_t);
out.write(p, bytes);
idx += now;
}
}
static inline sstring parent_path(const sstring& fname) {
return fs::canonical(fs::path(fname)).parent_path().string();
}
// This is small enough, and well-defined. Easier to just read it all
// at once
future<> sstable::read_toc() noexcept {
if (_recognized_components.size()) {
co_return;
}
try {
co_await do_read_simple(component_type::TOC, [&] (version_types v, file f) -> future<> {
auto bufptr = allocate_aligned_buffer<char>(4096, 4096);
size_t size = co_await f.dma_read(0, bufptr.get(), 4096);
// This file is supposed to be very small. Theoretically we should check its size,
// but if we so much as read a whole page from it, there is definitely something fishy
// going on - and this simplifies the code.
if (size >= 4096) {
throw malformed_sstable_exception("SSTable TOC too big: " + to_sstring(size) + " bytes", filename(component_type::TOC));
}
std::string_view buf(bufptr.get(), size);
std::vector<sstring> comps;
boost::split(comps , buf, boost::is_any_of("\n"));
for (auto& c: comps) {
// accept trailing newlines
if (c == "") {
continue;
}
try {
_recognized_components.insert(reverse_map(c, sstable_version_constants::get_component_map(_version)));
} catch (std::out_of_range& oor) {
_unrecognized_components.push_back(c);
sstlog.info("Unrecognized TOC component was found: {} in sstable {}", c, filename(component_type::TOC));
}
}
if (!_recognized_components.size()) {
throw malformed_sstable_exception("Empty TOC", filename(component_type::TOC));
}
});
} catch (std::system_error& e) {
if (e.code() == std::error_code(ENOENT, std::system_category())) {
throw malformed_sstable_exception(filename(component_type::TOC) + ": file not found");
}
throw;
}
}
void sstable::generate_toc() {
// Creating table of components.
_recognized_components.insert(component_type::TOC);
_recognized_components.insert(component_type::Statistics);
_recognized_components.insert(component_type::Digest);
_recognized_components.insert(component_type::Index);
_recognized_components.insert(component_type::Summary);
_recognized_components.insert(component_type::Data);
if (_schema->bloom_filter_fp_chance() != 1.0) {
_recognized_components.insert(component_type::Filter);
}
if (_schema->get_compressor_params().get_compressor() == nullptr) {
_recognized_components.insert(component_type::CRC);
} else {
_recognized_components.insert(component_type::CompressionInfo);
}
_recognized_components.insert(component_type::Scylla);
}
file_writer::~file_writer() {
if (_closed) {
return;
}
try {
// close() should be called by the owner of the file_writer.
// However it may not be called on exception handling paths
// so auto-close the output_stream so it won't be destructed while open.
_out.close().get();
} catch (...) {
sstlog.warn("Error while auto-closing {}: {}. Ignored.", get_filename(), std::current_exception());
}
}
void file_writer::close() {
// Writing into sstable component output stream should be done with care.
// In particular -- flushing can happen only once right before closing
// the stream. Flushing the stream in between several writes is not going
// to work, because file stream would step on unaligned IO and S3 upload
// stream would send completion message to the server and would lose any
// subsequent write.
assert(!_closed && "file_writer already closed");
std::exception_ptr ex;
try {
_out.flush().get();
} catch (...) {
ex = std::current_exception();
}
try {
_closed = true;
_out.close().get();
} catch (...) {
auto e = std::current_exception();
sstlog.error("Error while closing {}: {}", get_filename(), e);
if (!ex) {
ex = std::move(e);
}
}
if (ex) {
std::rethrow_exception(std::move(ex));
}
}
const char* file_writer::get_filename() const noexcept {
return _filename ? _filename->c_str() : "<anonymous output_stream>";
}
future<file_writer> sstable::make_component_file_writer(component_type c, file_output_stream_options options, open_flags oflags) noexcept {
// Note: file_writer::make closes the file if file_writer creation fails
// so we don't need to use with_file_close_on_failure here.
return futurize_invoke([this, c] { return filename(c); }).then([this, c, options = std::move(options), oflags] (sstring filename) mutable {
return _storage->make_component_sink(*this, c, oflags, std::move(options)).then([filename = std::move(filename)] (data_sink sink) mutable {
return file_writer(output_stream<char>(std::move(sink)), std::move(filename));
});
});
}
void sstable::open_sstable() {
generate_toc();
_storage->open(*this);
}
void sstable::write_toc(file_writer w) {
sstlog.debug("Writing TOC file {} ", toc_filename());
do_write_simple(std::move(w), [&] (version_types v, file_writer& w) {
for (auto&& key : _recognized_components) {
// new line character is appended to the end of each component name.
auto value = sstable_version_constants::get_component_map(v).at(key) + "\n";
bytes b = bytes(reinterpret_cast<const bytes::value_type *>(value.c_str()), value.size());
write(v, w, b);
}
});
}
void sstable::write_crc(const checksum& c) {
unsigned buffer_size = 4096;
do_write_simple(component_type::CRC, [&] (version_types v, file_writer& w) {
write(v, w, c);
}, buffer_size);
}
// Digest file stores the full checksum of data file converted into a string.
void sstable::write_digest(uint32_t full_checksum) {
unsigned buffer_size = 4096;
do_write_simple(component_type::Digest, [&] (version_types v, file_writer& w) {
auto digest = to_sstring<bytes>(full_checksum);
write(v, w, digest);
}, buffer_size);
}
thread_local std::array<std::vector<int>, downsampling::BASE_SAMPLING_LEVEL> downsampling::_sample_pattern_cache;
thread_local std::array<std::vector<int>, downsampling::BASE_SAMPLING_LEVEL> downsampling::_original_index_cache;
future<> sstable::do_read_simple(component_type type,
noncopyable_function<future<> (version_types, file&&, uint64_t sz)> read_component) {
auto file_path = filename(type);
sstlog.debug("Reading {} file {}", sstable_version_constants::get_component_map(_version).at(type), file_path);
try {
file fi = co_await new_sstable_component_file(_read_error_handler, type, open_flags::ro);
uint64_t size = co_await fi.size();
co_await read_component(_version, std::move(fi), size);
_metadata_size_on_disk += size;
} catch (std::system_error& e) {
if (e.code() == std::error_code(ENOENT, std::system_category())) {
throw malformed_sstable_exception(file_path + ": file not found");
}
throw;
} catch (malformed_sstable_exception& e) {
throw malformed_sstable_exception(e.what(), file_path);
}
}
future<> sstable::do_read_simple(component_type type,
noncopyable_function<future<> (version_types, file)> read_component) {
return do_read_simple(type, [read_component = std::move(read_component)] (version_types v, file&& f, uint64_t) -> future<> {
std::exception_ptr ex;
try {
co_await read_component(v, f);
} catch (...) {
ex = std::current_exception();
}
co_await f.close();
maybe_rethrow_exception(std::move(ex));
});
}
template <component_type Type, typename T>
future<> sstable::read_simple(T& component) {
return do_read_simple(Type, [&] (version_types v, file&& f, uint64_t size) -> future<> {
std::exception_ptr ex;
auto r = file_random_access_reader(std::move(f), size, sstable_buffer_size);
try {
co_await parse(*_schema, v, r, component);
} catch (...) {
ex = std::current_exception();
}
co_await r.close();
maybe_rethrow_exception(std::move(ex));
});
}