-
Notifications
You must be signed in to change notification settings - Fork 213
Expand file tree
/
Copy pathcompaction_picker.cc
More file actions
2912 lines (2714 loc) · 107 KB
/
Copy pathcompaction_picker.cc
File metadata and controls
2912 lines (2714 loc) · 107 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
// Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
// This source code is licensed under both the GPLv2 (found in the
// COPYING file in the root directory) and Apache 2.0 License
// (found in the LICENSE.Apache file in the root directory).
//
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#include "db/compaction_picker.h"
#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
#endif
#include <inttypes.h>
#include <limits>
#include <string>
#include <utility>
#include <vector>
#include "db/column_family.h"
#include "db/map_builder.h"
#include "rocksdb/terark_namespace.h"
#include "util/c_style_callback.h"
#include "util/chash_set.h"
#include "util/filename.h"
#include "util/log_buffer.h"
#include "util/random.h"
#include "util/string_util.h"
#include "util/sync_point.h"
#include "utilities/util/function.hpp"
namespace TERARKDB_NAMESPACE {
namespace {
inline double MixOverlapRatioAndDeletionRatio(double overlap_ratio,
double deletion_ratio) {
return overlap_ratio + deletion_ratio * 64;
}
struct LevelMapRangeSrc {
LevelMapRangeSrc(const MapSstElement& e, double _estimate_entry_num,
double _estimate_del_num, Arena* arena)
: start(ArenaPinSlice(e.smallest_key, arena)),
limit(ArenaPinSlice(e.largest_key, arena)),
estimate_size(e.EstimateSize()),
estimate_entry_num(_estimate_entry_num),
estimate_del_num(_estimate_del_num) {}
Slice start, limit;
uint64_t estimate_size;
double estimate_entry_num;
double estimate_del_num;
size_t start_index, limit_index;
};
struct LevelMapRangeDst {
LevelMapRangeDst(const MapSstElement& e, Arena* arena)
: start(ArenaPinSlice(e.smallest_key, arena)),
limit(ArenaPinSlice(e.largest_key, arena)),
estimate_size(e.EstimateSize()),
accumulate_estimate_size(0) {}
Slice start, limit;
uint64_t estimate_size;
uint64_t accumulate_estimate_size;
};
struct LevelMapSection {
ptrdiff_t start_index, limit_index;
double weight;
};
struct GarbageFileInfo {
FileMetaData* f;
double score;
uint64_t estimate_size;
GarbageFileInfo(FileMetaData* _f) : f(_f), score(0.0), estimate_size(0) {
if (f == nullptr) return;
score = std::min(
1.0, f->num_antiquation / std::max<double>(1, f->prop.num_entries));
estimate_size = static_cast<uint64_t>(f->fd.file_size * (1 - score));
}
};
struct FileUseInfo {
uint64_t size;
uint64_t used;
};
struct PickerCompositeHeapItem {
Slice k;
double s;
operator double() const noexcept { return s; }
};
uint64_t TotalCompensatedFileSize(const std::vector<FileMetaData*>& files) {
uint64_t sum = 0;
for (size_t i = 0; i < files.size() && files[i]; i++) {
sum += files[i]->compensated_file_size;
}
return sum;
}
/*
* Find the optimal path to place a file
* Given a level, finds the path where levels up to it will fit in levels
* up to and including this path
*/
uint32_t GetPathId(const ImmutableCFOptions& ioptions,
const MutableCFOptions& mutable_cf_options, int level) {
uint32_t p = 0;
assert(!ioptions.cf_paths.empty());
// size remaining in the most recent path
uint64_t current_path_size = ioptions.cf_paths[0].target_size;
uint64_t level_size;
int cur_level = 0;
// max_bytes_for_level_base denotes L1 size.
// We estimate L0 size to be the same as L1.
level_size = mutable_cf_options.max_bytes_for_level_base;
// Last path is the fallback
while (p < ioptions.cf_paths.size() - 1) {
if (level_size <= current_path_size) {
if (cur_level == level) {
// Does desired level fit in this path?
return p;
} else {
current_path_size -= level_size;
if (cur_level > 0) {
if (ioptions.level_compaction_dynamic_level_bytes) {
// Currently, level_compaction_dynamic_level_bytes is ignored when
// multiple db paths are specified. https://github.com/facebook/
// rocksdb/blob/master/db/column_family.cc.
// Still, adding this check to avoid accidentally using
// max_bytes_for_level_multiplier_additional
level_size = static_cast<uint64_t>(
level_size * mutable_cf_options.max_bytes_for_level_multiplier);
} else {
level_size = static_cast<uint64_t>(
level_size * mutable_cf_options.max_bytes_for_level_multiplier *
mutable_cf_options.MaxBytesMultiplerAdditional(cur_level));
}
}
cur_level++;
continue;
}
}
p++;
current_path_size = ioptions.cf_paths[p].target_size;
}
return p;
}
void AssignUserKey(std::string& key, const Slice& ikey) {
Slice ukey = ExtractUserKey(ikey);
key.assign(ukey.data(), ukey.size());
};
} // anonymous namespace
bool FindIntraL0Compaction(const std::vector<FileMetaData*>& level_files,
size_t min_files_to_compact,
uint64_t max_compact_bytes_per_del_file,
CompactionInputFiles* comp_inputs) {
size_t compact_bytes = static_cast<size_t>(level_files[0]->fd.file_size);
size_t compact_bytes_per_del_file = port::kMaxSizet;
// compaction range will be [0, span_len).
size_t span_len;
// pull in files until the amount of compaction work per deleted file begins
// increasing.
size_t new_compact_bytes_per_del_file = 0;
for (span_len = 1; span_len < level_files.size(); ++span_len) {
compact_bytes += static_cast<size_t>(level_files[span_len]->fd.file_size);
new_compact_bytes_per_del_file = compact_bytes / span_len;
if (level_files[span_len]->being_compacted ||
new_compact_bytes_per_del_file > compact_bytes_per_del_file) {
break;
}
compact_bytes_per_del_file = new_compact_bytes_per_del_file;
}
if (span_len >= min_files_to_compact &&
compact_bytes_per_del_file < max_compact_bytes_per_del_file) {
assert(comp_inputs != nullptr);
comp_inputs->level = 0;
for (size_t i = 0; i < span_len; ++i) {
comp_inputs->files.push_back(level_files[i]);
}
return true;
}
return false;
}
// Determine compression type, based on user options, level of the output
// file and whether compression is disabled.
// If enable_compression is false, then compression is always disabled no
// matter what the values of the other two parameters are.
// Otherwise, the compression type is determined based on options and level.
CompressionType GetCompressionType(const ImmutableCFOptions& ioptions,
const VersionStorageInfo* vstorage,
const MutableCFOptions& mutable_cf_options,
int level, int base_level,
const bool enable_compression) {
if (!enable_compression) {
// disable compression
return kNoCompression;
}
// If bottommost_compression is set and we are compacting to the
// bottommost level then we should use it.
if (ioptions.bottommost_compression != kDisableCompressionOption &&
level >= (vstorage->num_non_empty_levels() - 1)) {
return ioptions.bottommost_compression;
}
// If the user has specified a different compression level for each level,
// then pick the compression for that level.
if (!ioptions.compression_per_level.empty()) {
assert(level == 0 || level >= base_level);
int idx = (level == 0) ? 0 : level - base_level + 1;
const int n = static_cast<int>(ioptions.compression_per_level.size()) - 1;
// It is possible for level_ to be -1; in that case, we use level
// 0's compression. This occurs mostly in backwards compatibility
// situations when the builder doesn't know what level the file
// belongs to. Likewise, if level is beyond the end of the
// specified compression levels, use the last value.
return ioptions.compression_per_level[std::max(0, std::min(idx, n))];
} else {
return mutable_cf_options.compression;
}
}
CompressionOptions GetCompressionOptions(const ImmutableCFOptions& ioptions,
const VersionStorageInfo* vstorage,
int level,
const bool enable_compression) {
if (!enable_compression) {
return ioptions.compression_opts;
}
// If bottommost_compression is set and we are compacting to the
// bottommost level then we should use the specified compression options
// for the bottmomost_compression.
if (ioptions.bottommost_compression != kDisableCompressionOption &&
level >= (vstorage->num_non_empty_levels() - 1) &&
ioptions.bottommost_compression_opts.enabled) {
return ioptions.bottommost_compression_opts;
}
return ioptions.compression_opts;
}
CompactionPicker::CompactionPicker(TableCache* table_cache,
const EnvOptions& env_options,
const ImmutableCFOptions& ioptions,
const InternalKeyComparator* icmp)
: table_cache_(table_cache),
env_options_(env_options),
ioptions_(ioptions),
icmp_(icmp) {}
CompactionPicker::~CompactionPicker() {}
double CompactionPicker::GetQ(std::vector<double>::const_iterator b,
std::vector<double>::const_iterator e, size_t g) {
double S = std::accumulate(b, e, 0.0);
// sum of [q, q^2, q^3, ... , q^n]
auto F = [](double q, size_t n) {
return (std::pow(q, n + 1) - q) / (q - 1);
};
// let S = ∑q^i, i in <1..n>, seek q
double q = std::pow(S, 1.0 / g);
if (S <= g + 1) {
q = 1;
} else {
// Newton-Raphson method
for (size_t c = 0; c < 8; ++c) {
double Fp = q, q_k = q;
for (size_t k = 2; k <= g; ++k) {
Fp += k * (q_k *= q);
}
q -= (F(q, g) - S) / Fp;
}
}
return q;
}
bool CompactionPicker::ReadMapElement(MapSstElement& map_element,
InternalIterator* iter,
LogBuffer* log_buffer,
const std::string& cf_name) {
LazyBuffer value = iter->value();
auto s = value.fetch();
if (!s.ok()) {
ROCKS_LOG_BUFFER(log_buffer,
"[%s] CompactionPicker LazyBuffer decode fail: %s\n",
cf_name.c_str(), s.ToString().c_str());
return false;
}
if (!map_element.Decode(iter->key(), value.slice())) {
ROCKS_LOG_BUFFER(log_buffer,
"[%s] CompactionPicker MapSstElement Decode fail\n",
cf_name.c_str());
return false;
}
return true;
}
bool CompactionPicker::FixInputRange(std::vector<SelectedRange>& input_range,
const InternalKeyComparator& icmp,
bool sort, bool merge) {
auto uc = icmp.user_comparator();
auto range_cmp = [uc](const SelectedRange& a, const SelectedRange& b) {
int r = uc->Compare(a.limit, b.limit);
if (r == 0) {
r = int(a.include_limit) - int(b.include_limit);
}
if (r == 0) {
r = uc->Compare(a.start, b.start);
}
if (r == 0) {
r = int(b.include_start) - int(a.include_start);
}
return r < 0;
};
if (sort) {
std::sort(input_range.begin(), input_range.end(), range_cmp);
} else {
assert(std::is_sorted(input_range.begin(), input_range.end(), range_cmp));
}
if (merge && input_range.size() > 1) {
size_t c = 0, n = input_range.size();
auto it = input_range.begin();
for (size_t i = 1; i < n; ++i) {
if (uc->Compare(it[c].limit, it[i].start) >= 0) {
if (uc->Compare(it[c].limit, it[i].limit) < 0) {
it[c].limit = std::move(it[i].limit);
it[c].include_limit = it[i].include_limit;
}
} else if (++c != i) {
it[c] = std::move(it[i]);
}
}
input_range.resize(c + 1);
}
// remove empty ranges
if (input_range.size() > 1) {
for (auto it = input_range.begin() + 1; it != input_range.end();) {
if (uc->Compare(it->start, it[-1].start) == 0 ||
uc->Compare(it->limit, it[-1].limit) == 0) {
it[-1].limit = std::move(it->limit);
it[-1].include_limit = it->include_limit;
it = input_range.erase(it);
} else {
++it;
}
}
}
if (!input_range.empty()) {
for (auto it = input_range.begin(); it != input_range.end();) {
if (uc->Compare(it->start, it->limit) == 0 &&
(!it->include_start || !it->include_limit)) {
it = input_range.erase(it);
} else {
++it;
}
}
}
assert(std::is_sorted(input_range.begin(), input_range.end(),
TERARK_FIELD(start) < *uc));
assert(std::is_sorted(input_range.begin(), input_range.end(),
TERARK_FIELD(limit) < *uc));
assert(std::find_if(input_range.begin(), input_range.end(),
[uc](const RangeStorage& r) {
return uc->Compare(r.start, r.limit) > 0;
}) == input_range.end());
return !input_range.empty();
}
// Delete this compaction from the list of running compactions.
void CompactionPicker::ReleaseCompactionFiles(Compaction* c, Status status) {
UnregisterCompaction(c);
if (!status.ok()) {
c->ResetNextCompactionIndex();
}
}
void CompactionPicker::GetRange(const CompactionInputFiles& inputs,
InternalKey* smallest,
InternalKey* largest) const {
const int level = inputs.level;
assert(!inputs.empty());
smallest->Clear();
largest->Clear();
if (level == 0) {
for (size_t i = 0; i < inputs.size(); i++) {
FileMetaData* f = inputs[i];
if (i == 0) {
*smallest = f->smallest;
*largest = f->largest;
} else {
if (icmp_->Compare(f->smallest, *smallest) < 0) {
*smallest = f->smallest;
}
if (icmp_->Compare(f->largest, *largest) > 0) {
*largest = f->largest;
}
}
}
} else {
*smallest = inputs[0]->smallest;
*largest = inputs[inputs.size() - 1]->largest;
}
}
void CompactionPicker::GetRange(const CompactionInputFiles& inputs1,
const CompactionInputFiles& inputs2,
InternalKey* smallest,
InternalKey* largest) const {
assert(!inputs1.empty() || !inputs2.empty());
if (inputs1.empty()) {
GetRange(inputs2, smallest, largest);
} else if (inputs2.empty()) {
GetRange(inputs1, smallest, largest);
} else {
InternalKey smallest1, smallest2, largest1, largest2;
GetRange(inputs1, &smallest1, &largest1);
GetRange(inputs2, &smallest2, &largest2);
*smallest =
icmp_->Compare(smallest1, smallest2) < 0 ? smallest1 : smallest2;
*largest = icmp_->Compare(largest1, largest2) < 0 ? largest2 : largest1;
}
}
void CompactionPicker::GetRange(const std::vector<CompactionInputFiles>& inputs,
InternalKey* smallest,
InternalKey* largest) const {
InternalKey current_smallest;
InternalKey current_largest;
bool initialized = false;
for (const auto& in : inputs) {
if (in.empty()) {
continue;
}
GetRange(in, ¤t_smallest, ¤t_largest);
if (!initialized) {
*smallest = current_smallest;
*largest = current_largest;
initialized = true;
} else {
if (icmp_->Compare(current_smallest, *smallest) < 0) {
*smallest = current_smallest;
}
if (icmp_->Compare(current_largest, *largest) > 0) {
*largest = current_largest;
}
}
}
assert(initialized);
}
bool CompactionPicker::ExpandInputsToCleanCut(const std::string& /*cf_name*/,
VersionStorageInfo* vstorage,
CompactionInputFiles* inputs,
InternalKey** next_smallest) {
// This isn't good compaction
assert(!inputs->empty());
const int level = inputs->level;
// GetOverlappingInputs will always do the right thing for level-0.
// So we don't need to do any expansion if level == 0.
if (level == 0) {
return true;
}
InternalKey smallest, largest;
// Keep expanding inputs until we are sure that there is a "clean cut"
// boundary between the files in input and the surrounding files.
// This will ensure that no parts of a key are lost during compaction.
int hint_index = -1;
size_t old_size;
do {
old_size = inputs->size();
GetRange(*inputs, &smallest, &largest);
inputs->clear();
vstorage->GetOverlappingInputs(level, &smallest, &largest, &inputs->files,
hint_index, &hint_index, true,
next_smallest);
} while (inputs->size() > old_size);
// we started off with inputs non-empty and the previous loop only grew
// inputs. thus, inputs should be non-empty here
assert(!inputs->empty());
// If, after the expansion, there are files that are already under
// compaction, then we must drop/cancel this compaction.
if (AreFilesInCompaction(inputs->files)) {
return false;
}
return true;
}
bool CompactionPicker::RangeOverlapWithCompaction(
const Slice& smallest_user_key, const Slice& largest_user_key,
int level) const {
const Comparator* ucmp = icmp_->user_comparator();
for (Compaction* c : compactions_in_progress_) {
if (c->output_level() == level &&
ucmp->Compare(smallest_user_key, c->GetLargestUserKey()) <= 0 &&
ucmp->Compare(largest_user_key, c->GetSmallestUserKey()) >= 0) {
// Overlap
return true;
}
}
// Did not overlap with any running compaction in level `level`
return false;
}
bool CompactionPicker::FilesRangeOverlapWithCompaction(
const std::vector<CompactionInputFiles>& inputs, int level) const {
bool is_empty = true;
for (auto& in : inputs) {
if (!in.empty()) {
is_empty = false;
break;
}
}
if (is_empty) {
// No files in inputs
return false;
}
InternalKey smallest, largest;
GetRange(inputs, &smallest, &largest);
return RangeOverlapWithCompaction(smallest.user_key(), largest.user_key(),
level);
}
// Returns true if any one of specified files are being compacted
bool CompactionPicker::AreFilesInCompaction(
const std::vector<FileMetaData*>& files) {
for (size_t i = 0; i < files.size(); i++) {
if (files[i]->being_compacted) {
return true;
}
}
return false;
}
Compaction* CompactionPicker::CompactFiles(
const CompactionOptions& compact_options,
const std::vector<CompactionInputFiles>& input_files, int output_level,
VersionStorageInfo* vstorage, const MutableCFOptions& mutable_cf_options,
uint32_t output_path_id) {
assert(input_files.size());
// This compaction output should not overlap with a running compaction as
// `SanitizeCompactionInputFiles` should've checked earlier and db mutex
// shouldn't have been released since.
assert(output_level == 0 || !FilesRangeOverlapWithCompaction(input_files, output_level));
CompressionType compression_type;
if (compact_options.compression == kDisableCompressionOption) {
int base_level;
if (ioptions_.compaction_style == kCompactionStyleLevel) {
base_level = vstorage->base_level();
} else {
base_level = 1;
}
compression_type = GetCompressionType(
ioptions_, vstorage, mutable_cf_options, output_level, base_level);
} else {
// TODO(ajkr): `CompactionOptions` offers configurable `CompressionType`
// without configurable `CompressionOptions`, which is inconsistent.
compression_type = compact_options.compression;
}
CompactionParams params(vstorage, ioptions_, mutable_cf_options);
params.inputs = std::move(input_files);
params.output_level = output_level;
params.target_file_size =
output_level == 0 ? 0 : compact_options.output_file_size_limit;
params.max_compaction_bytes = mutable_cf_options.max_compaction_bytes;
params.output_path_id = output_path_id;
params.compression = compression_type;
params.separation_type = compact_options.separation_type;
params.compression_opts =
GetCompressionOptions(ioptions_, vstorage, output_level);
params.max_subcompactions = compact_options.max_subcompactions;
params.manual_compaction = true;
return RegisterCompaction(new Compaction(std::move(params)));
}
Status CompactionPicker::GetCompactionInputsFromFileNumbers(
std::vector<CompactionInputFiles>* input_files,
std::unordered_set<uint64_t>* input_set, const VersionStorageInfo* vstorage,
const CompactionOptions& /*compact_options*/) const {
if (input_set->size() == 0U) {
return Status::InvalidArgument(
"Compaction must include at least one file.");
}
assert(input_files);
std::vector<CompactionInputFiles> matched_input_files;
matched_input_files.resize(vstorage->num_levels());
int first_non_empty_level = -1;
int last_non_empty_level = -1;
// TODO(yhchiang): use a lazy-initialized mapping from
// file_number to FileMetaData in Version.
for (int level = 0; level < vstorage->num_levels(); ++level) {
for (auto file : vstorage->LevelFiles(level)) {
auto iter = input_set->find(file->fd.GetNumber());
if (iter != input_set->end()) {
matched_input_files[level].files.push_back(file);
input_set->erase(iter);
last_non_empty_level = level;
if (first_non_empty_level == -1) {
first_non_empty_level = level;
}
}
}
}
if (!input_set->empty()) {
std::string message(
"Cannot find matched SST files for the following file numbers:");
for (auto fn : *input_set) {
message += " ";
message += ToString(fn);
}
return Status::InvalidArgument(message);
}
for (int level = first_non_empty_level; level <= last_non_empty_level;
++level) {
matched_input_files[level].level = level;
input_files->emplace_back(std::move(matched_input_files[level]));
}
return Status::OK();
}
// Returns true if any one of the parent files are being compacted
bool CompactionPicker::IsRangeInCompaction(VersionStorageInfo* vstorage,
const InternalKey* smallest,
const InternalKey* largest,
int level, int* level_index) {
std::vector<FileMetaData*> inputs;
assert(level < NumberLevels());
vstorage->GetOverlappingInputs(level, smallest, largest, &inputs,
level_index ? *level_index : 0, level_index);
return AreFilesInCompaction(inputs);
}
// Populates the set of inputs of all other levels that overlap with the
// start level.
// Now we assume all levels except start level and output level are empty.
// Will also attempt to expand "start level" if that doesn't expand
// "output level" or cause "level" to include a file for compaction that has an
// overlapping user-key with another file.
// REQUIRES: input_level and output_level are different
// REQUIRES: inputs->empty() == false
// Returns false if files on parent level are currently in compaction, which
// means that we can't compact them
bool CompactionPicker::SetupOtherInputs(
const std::string& cf_name, const MutableCFOptions& mutable_cf_options,
VersionStorageInfo* vstorage, CompactionInputFiles* inputs,
CompactionInputFiles* output_level_inputs, int* parent_index,
int base_index) {
assert(!inputs->empty());
assert(output_level_inputs->empty());
const int input_level = inputs->level;
const int output_level = output_level_inputs->level;
if (input_level == output_level) {
// no possibility of conflict
return true;
}
// For now, we only support merging two levels, start level and output level.
// We need to assert other levels are empty.
for (int l = input_level + 1; l < output_level; l++) {
assert(vstorage->NumLevelFiles(l) == 0);
}
InternalKey smallest, largest;
// Get the range one last time.
GetRange(*inputs, &smallest, &largest);
// Populate the set of next-level files (inputs_GetOutputLevelInputs()) to
// include in compaction
vstorage->GetOverlappingInputs(output_level, &smallest, &largest,
&output_level_inputs->files, *parent_index,
parent_index);
if (AreFilesInCompaction(output_level_inputs->files)) {
return false;
}
if (!output_level_inputs->empty()) {
if (!ExpandInputsToCleanCut(cf_name, vstorage, output_level_inputs)) {
return false;
}
}
// See if we can further grow the number of inputs in "level" without
// changing the number of "level+1" files we pick up. We also choose NOT
// to expand if this would cause "level" to include some entries for some
// user key, while excluding other entries for the same user key. This
// can happen when one user key spans multiple files.
if (!output_level_inputs->empty()) {
const uint64_t limit = mutable_cf_options.max_compaction_bytes;
const uint64_t output_level_inputs_size =
TotalCompensatedFileSize(output_level_inputs->files);
const uint64_t inputs_size = TotalCompensatedFileSize(inputs->files);
bool expand_inputs = false;
CompactionInputFiles expanded_inputs;
expanded_inputs.level = input_level;
// Get closed interval of output level
InternalKey all_start, all_limit;
GetRange(*inputs, *output_level_inputs, &all_start, &all_limit);
bool try_overlapping_inputs = true;
vstorage->GetOverlappingInputs(input_level, &all_start, &all_limit,
&expanded_inputs.files, base_index, nullptr);
uint64_t expanded_inputs_size =
TotalCompensatedFileSize(expanded_inputs.files);
if (!ExpandInputsToCleanCut(cf_name, vstorage, &expanded_inputs)) {
try_overlapping_inputs = false;
}
if (try_overlapping_inputs && expanded_inputs.size() > inputs->size() &&
output_level_inputs_size + expanded_inputs_size < limit &&
!AreFilesInCompaction(expanded_inputs.files)) {
InternalKey new_start, new_limit;
GetRange(expanded_inputs, &new_start, &new_limit);
CompactionInputFiles expanded_output_level_inputs;
expanded_output_level_inputs.level = output_level;
vstorage->GetOverlappingInputs(output_level, &new_start, &new_limit,
&expanded_output_level_inputs.files,
*parent_index, parent_index);
assert(!expanded_output_level_inputs.empty());
if (!AreFilesInCompaction(expanded_output_level_inputs.files) &&
ExpandInputsToCleanCut(cf_name, vstorage,
&expanded_output_level_inputs) &&
expanded_output_level_inputs.size() == output_level_inputs->size()) {
expand_inputs = true;
}
}
if (!expand_inputs) {
vstorage->GetCleanInputsWithinInterval(input_level, &all_start,
&all_limit, &expanded_inputs.files,
base_index, nullptr);
expanded_inputs_size = TotalCompensatedFileSize(expanded_inputs.files);
if (expanded_inputs.size() > inputs->size() &&
output_level_inputs_size + expanded_inputs_size < limit &&
!AreFilesInCompaction(expanded_inputs.files)) {
expand_inputs = true;
}
}
if (expand_inputs) {
ROCKS_LOG_INFO(ioptions_.info_log,
"[%s] Expanding@%d %" ROCKSDB_PRIszt "+%" ROCKSDB_PRIszt
"(%" PRIu64 "+%" PRIu64 " bytes) to %" ROCKSDB_PRIszt
"+%" ROCKSDB_PRIszt " (%" PRIu64 "+%" PRIu64 " bytes)\n",
cf_name.c_str(), input_level, inputs->size(),
output_level_inputs->size(), inputs_size,
output_level_inputs_size, expanded_inputs.size(),
output_level_inputs->size(), expanded_inputs_size,
output_level_inputs_size);
inputs->files = expanded_inputs.files;
}
}
return true;
}
void CompactionPicker::GetGrandparents(
VersionStorageInfo* vstorage, const CompactionInputFiles& inputs,
const CompactionInputFiles& output_level_inputs,
std::vector<FileMetaData*>* grandparents) {
InternalKey start, limit;
GetRange(inputs, output_level_inputs, &start, &limit);
// Compute the set of grandparent files that overlap this compaction
// (parent == level+1; grandparent == level+2)
if (output_level_inputs.level + 1 < NumberLevels()) {
vstorage->GetOverlappingInputs(output_level_inputs.level + 1, &start,
&limit, grandparents);
}
}
// Try to perform garbage collection from certain column family.
// Resulting as a pointer of compaction, nullptr as nothing to do.
// GC picker's principle:
// 1. pick the largest score blob, which must more than gc ratio
// 2. fragment should be take away by the way
// 3. it marked for compaction
Compaction* CompactionPicker::PickGarbageCollection(
const std::string& /*cf_name*/, const MutableCFOptions& mutable_cf_options,
VersionStorageInfo* vstorage, LogBuffer* /*log_buffer*/) {
// Setting fragment_size as one eighth target_blob_file_size prevents
// selecting massive files to single compaction which would pin down the
// maximum deletable file number for a long time resulting possible storage
// leakage.
size_t target_blob_file_size = MaxBlobSize(
mutable_cf_options, ioptions_.num_levels, ioptions_.compaction_style);
size_t fragment_size = mutable_cf_options.blob_file_defragment_size;
if (fragment_size == 0) {
fragment_size = target_blob_file_size / 8;
}
auto& hidden_files = vstorage->LevelFiles(-1);
uint64_t idx = 0;
// Find largest score blob
GarbageFileInfo dirtiest_blob{nullptr};
for (; idx < hidden_files.size() && !hidden_files[idx]->is_gc_forbidden();
++idx) {
FileMetaData* f = hidden_files[idx];
if (!f->is_gc_permitted() || f->being_compacted) {
continue;
}
GarbageFileInfo info{f};
if (info.score > dirtiest_blob.score) {
dirtiest_blob = info;
}
}
if (dirtiest_blob.f == nullptr ||
(!dirtiest_blob.f->marked_for_compaction &&
dirtiest_blob.score < mutable_cf_options.blob_gc_ratio)) {
return nullptr;
}
// Set up inputs for garbage collection.
std::vector<CompactionInputFiles> inputs(1);
auto& input = inputs.front();
input.level = -1;
input.files.push_back(dirtiest_blob.f);
dirtiest_blob.f->set_gc_candidate();
uint64_t total_estimate_size = dirtiest_blob.estimate_size;
uint64_t num_antiquation = dirtiest_blob.f->num_antiquation;
// expand with neighbor blob
std::vector<GarbageFileInfo> candidate_blob_vec;
auto target = dirtiest_blob.f;
auto ucmp = ioptions_.user_comparator;
std::vector<FileMetaData*> smallest_adjoining, largest_adjoining, overlapping;
uint64_t blob_end_idx = idx;
for (idx = 0; idx < blob_end_idx; ++idx) {
auto f = hidden_files[idx];
if (f == target) {
continue;
}
if (ucmp->Compare(f->largest.user_key(), target->smallest.user_key()) < 0) {
int c = 0;
if (!smallest_adjoining.empty()) {
c = ucmp->Compare(f->largest.user_key(),
smallest_adjoining.front()->largest.user_key());
if (c > 0) {
smallest_adjoining.clear();
}
}
if (c >= 0) {
smallest_adjoining.emplace_back(f);
}
} else if (ucmp->Compare(f->smallest.user_key(),
target->largest.user_key()) > 0) {
int c = 0;
if (!largest_adjoining.empty()) {
c = ucmp->Compare(f->smallest.user_key(),
largest_adjoining.front()->smallest.user_key());
if (c < 0) {
largest_adjoining.clear();
}
}
if (c <= 0) {
largest_adjoining.emplace_back(f);
}
} else {
overlapping.emplace_back(f);
}
}
auto push_candidate = [&](FileMetaData* f) {
if (f->is_gc_permitted() && !f->being_compacted) {
GarbageFileInfo gc_blob(f);
if (gc_blob.estimate_size <= fragment_size ||
gc_blob.score >= mutable_cf_options.blob_gc_ratio ||
gc_blob.f->marked_for_compaction) {
candidate_blob_vec.emplace_back(gc_blob);
}
}
};
std::for_each(smallest_adjoining.begin(), smallest_adjoining.end(),
push_candidate);
std::for_each(largest_adjoining.begin(), largest_adjoining.end(),
push_candidate);
std::for_each(overlapping.begin(), overlapping.end(), push_candidate);
// Pick Top 8(<=) score blob
auto candidate_cmp = [](const GarbageFileInfo& l, const GarbageFileInfo& r) {
return l.score < r.score;
};
std::make_heap(candidate_blob_vec.begin(), candidate_blob_vec.end(),
candidate_cmp);
while (!candidate_blob_vec.empty() && input.files.size() < 8) {
auto f = candidate_blob_vec.front().f;
uint64_t estimate_size = candidate_blob_vec.front().estimate_size;
if (total_estimate_size + estimate_size < target_blob_file_size) {
total_estimate_size += estimate_size;
num_antiquation += f->num_antiquation;
f->set_gc_candidate();
input.files.push_back(f);
}
std::pop_heap(candidate_blob_vec.begin(), candidate_blob_vec.end(),
candidate_cmp);
candidate_blob_vec.pop_back();
}
int bottommost_level = vstorage->num_levels() - 1;
// Set compaction params.
CompactionParams params(vstorage, ioptions_, mutable_cf_options);
params.inputs = std::move(inputs);
params.output_level = -1;
params.num_antiquation = num_antiquation;
params.max_compaction_bytes = LLONG_MAX;
params.output_path_id = GetPathId(ioptions_, mutable_cf_options, 1);
params.compression = GetCompressionType(
ioptions_, vstorage, mutable_cf_options, bottommost_level, 1, true);
params.compression_opts =
GetCompressionOptions(ioptions_, vstorage, bottommost_level, true);
params.max_subcompactions = 1;
params.score = vstorage->total_garbage_ratio();
params.compaction_type = kGarbageCollection;
params.compaction_reason = CompactionReason::kGarbageCollection;
Compaction* c = RegisterCompaction(new Compaction(std::move(params)));
vstorage->ComputeCompactionScore(ioptions_, mutable_cf_options);
return c;
}
void CompactionPicker::InitFilesBeingCompact(
const MutableCFOptions& mutable_cf_options, VersionStorageInfo* vstorage,
const InternalKey* begin, const InternalKey* end,
chash_set<uint64_t>* files_being_compact) {
if (!ioptions_.enable_lazy_compaction) {
return;
}
ReadOptions options;
MapSstElement element;
auto create_iter = [&](const FileMetaData* file_metadata,
const DependenceMap& depend_map, Arena* arena,
TableReader** table_reader_ptr) {
return table_cache_->NewIterator(
options, env_options_, *icmp_, *file_metadata, depend_map, nullptr,
mutable_cf_options.prefix_extractor.get(), table_reader_ptr, nullptr,
false, arena, true, -1);
};
for (int level = 0; level < vstorage->num_levels(); ++level) {
auto& level_files = vstorage->LevelFiles(level);
if (level_files.empty()) {
continue;
}
Arena arena;
ScopedArenaIterator iter(NewMapElementIterator(
level_files.data(), level_files.size(), icmp_, &create_iter,
c_style_callback(create_iter), &arena));
for (level == 0 || begin == nullptr ? iter->SeekToFirst()
: iter->Seek(begin->Encode());
iter->Valid(); iter->Next()) {
LazyBuffer value = iter->value();
if (!value.fetch().ok() || !element.Decode(iter->key(), value.slice())) {
// TODO: log error ?
break;
}
if (begin != nullptr &&
icmp_->Compare(element.largest_key, begin->Encode()) < 0) {
assert(level == 0);
continue;
}
if (end != nullptr &&
icmp_->Compare(element.smallest_key, end->Encode()) > 0) {
if (level == 0) {
continue;
} else {
break;
}
}
auto& dependence_map = vstorage->dependence_map();
for (auto& link : element.link) {
files_being_compact->emplace(link.file_number);
auto find = dependence_map.find(link.file_number);
if (find == dependence_map.end()) {
// TODO: log error
continue;
}
auto f = find->second;
if (!f->prop.is_map_sst()) {
continue;
}
for (auto& dependence : f->prop.dependence) {
files_being_compact->emplace(dependence.file_number);