-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
levels.go
1787 lines (1598 loc) · 52.7 KB
/
levels.go
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 2017 Dgraph Labs, Inc. and Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package badger
import (
"bytes"
"context"
"encoding/hex"
"fmt"
"math"
"math/rand"
"os"
"sort"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/pkg/errors"
otrace "go.opencensus.io/trace"
"github.com/dgraph-io/badger/v4/pb"
"github.com/dgraph-io/badger/v4/table"
"github.com/dgraph-io/badger/v4/y"
"github.com/dgraph-io/ristretto/z"
)
type levelsController struct {
nextFileID atomic.Uint64
l0stallsMs atomic.Int64
// The following are initialized once and const.
levels []*levelHandler
kv *DB
cstatus compactStatus
}
// revertToManifest checks that all necessary table files exist and removes all table files not
// referenced by the manifest. idMap is a set of table file id's that were read from the directory
// listing.
func revertToManifest(kv *DB, mf *Manifest, idMap map[uint64]struct{}) error {
// 1. Check all files in manifest exist.
for id := range mf.Tables {
if _, ok := idMap[id]; !ok {
return fmt.Errorf("file does not exist for table %d", id)
}
}
// 2. Delete files that shouldn't exist.
for id := range idMap {
if _, ok := mf.Tables[id]; !ok {
kv.opt.Debugf("Table file %d not referenced in MANIFEST\n", id)
filename := table.NewFilename(id, kv.opt.Dir)
if err := os.Remove(filename); err != nil {
return y.Wrapf(err, "While removing table %d", id)
}
}
}
return nil
}
func newLevelsController(db *DB, mf *Manifest) (*levelsController, error) {
y.AssertTrue(db.opt.NumLevelZeroTablesStall > db.opt.NumLevelZeroTables)
s := &levelsController{
kv: db,
levels: make([]*levelHandler, db.opt.MaxLevels),
}
s.cstatus.tables = make(map[uint64]struct{})
s.cstatus.levels = make([]*levelCompactStatus, db.opt.MaxLevels)
for i := 0; i < db.opt.MaxLevels; i++ {
s.levels[i] = newLevelHandler(db, i)
s.cstatus.levels[i] = new(levelCompactStatus)
}
if db.opt.InMemory {
return s, nil
}
// Compare manifest against directory, check for existent/non-existent files, and remove.
if err := revertToManifest(db, mf, getIDMap(db.opt.Dir)); err != nil {
return nil, err
}
var mu sync.Mutex
tables := make([][]*table.Table, db.opt.MaxLevels)
var maxFileID uint64
// We found that using 3 goroutines allows disk throughput to be utilized to its max.
// Disk utilization is the main thing we should focus on, while trying to read the data. That's
// the one factor that remains constant between HDD and SSD.
throttle := y.NewThrottle(3)
start := time.Now()
var numOpened atomic.Int32
tick := time.NewTicker(3 * time.Second)
defer tick.Stop()
for fileID, tf := range mf.Tables {
fname := table.NewFilename(fileID, db.opt.Dir)
select {
case <-tick.C:
db.opt.Infof("%d tables out of %d opened in %s\n", numOpened.Load(),
len(mf.Tables), time.Since(start).Round(time.Millisecond))
default:
}
if err := throttle.Do(); err != nil {
closeAllTables(tables)
return nil, err
}
if fileID > maxFileID {
maxFileID = fileID
}
go func(fname string, tf TableManifest) {
var rerr error
defer func() {
throttle.Done(rerr)
numOpened.Add(1)
}()
dk, err := db.registry.DataKey(tf.KeyID)
if err != nil {
rerr = y.Wrapf(err, "Error while reading datakey")
return
}
topt := buildTableOptions(db)
// Explicitly set Compression and DataKey based on how the table was generated.
topt.Compression = tf.Compression
topt.DataKey = dk
mf, err := z.OpenMmapFile(fname, db.opt.getFileFlags(), 0)
if err != nil {
rerr = y.Wrapf(err, "Opening file: %q", fname)
return
}
t, err := table.OpenTable(mf, topt)
if err != nil {
if strings.HasPrefix(err.Error(), "CHECKSUM_MISMATCH:") {
db.opt.Errorf(err.Error())
db.opt.Errorf("Ignoring table %s", mf.Fd.Name())
// Do not set rerr. We will continue without this table.
} else {
rerr = y.Wrapf(err, "Opening table: %q", fname)
}
return
}
mu.Lock()
tables[tf.Level] = append(tables[tf.Level], t)
mu.Unlock()
}(fname, tf)
}
if err := throttle.Finish(); err != nil {
closeAllTables(tables)
return nil, err
}
db.opt.Infof("All %d tables opened in %s\n", numOpened.Load(),
time.Since(start).Round(time.Millisecond))
s.nextFileID.Store(maxFileID + 1)
for i, tbls := range tables {
s.levels[i].initTables(tbls)
}
// Make sure key ranges do not overlap etc.
if err := s.validate(); err != nil {
_ = s.cleanupLevels()
return nil, y.Wrap(err, "Level validation")
}
// Sync directory (because we have at least removed some files, or previously created the
// manifest file).
if err := syncDir(db.opt.Dir); err != nil {
_ = s.close()
return nil, err
}
return s, nil
}
// Closes the tables, for cleanup in newLevelsController. (We Close() instead of using DecrRef()
// because that would delete the underlying files.) We ignore errors, which is OK because tables
// are read-only.
func closeAllTables(tables [][]*table.Table) {
for _, tableSlice := range tables {
for _, table := range tableSlice {
_ = table.Close(-1)
}
}
}
func (s *levelsController) cleanupLevels() error {
var firstErr error
for _, l := range s.levels {
if err := l.close(); err != nil && firstErr == nil {
firstErr = err
}
}
return firstErr
}
// dropTree picks all tables from all levels, creates a manifest changeset,
// applies it, and then decrements the refs of these tables, which would result
// in their deletion.
func (s *levelsController) dropTree() (int, error) {
// First pick all tables, so we can create a manifest changelog.
var all []*table.Table
for _, l := range s.levels {
l.RLock()
all = append(all, l.tables...)
l.RUnlock()
}
if len(all) == 0 {
return 0, nil
}
// Generate the manifest changes.
changes := []*pb.ManifestChange{}
for _, table := range all {
// Add a delete change only if the table is not in memory.
if !table.IsInmemory {
changes = append(changes, newDeleteChange(table.ID()))
}
}
changeSet := pb.ManifestChangeSet{Changes: changes}
if err := s.kv.manifest.addChanges(changeSet.Changes); err != nil {
return 0, err
}
// Now that manifest has been successfully written, we can delete the tables.
for _, l := range s.levels {
l.Lock()
l.totalSize = 0
l.tables = l.tables[:0]
l.Unlock()
}
for _, table := range all {
if err := table.DecrRef(); err != nil {
return 0, err
}
}
return len(all), nil
}
// dropPrefix runs a L0->L1 compaction, and then runs same level compaction on the rest of the
// levels. For L0->L1 compaction, it runs compactions normally, but skips over
// all the keys with the provided prefix.
// For Li->Li compactions, it picks up the tables which would have the prefix. The
// tables who only have keys with this prefix are quickly dropped. The ones which have other keys
// are run through MergeIterator and compacted to create new tables. All the mechanisms of
// compactions apply, i.e. level sizes and MANIFEST are updated as in the normal flow.
func (s *levelsController) dropPrefixes(prefixes [][]byte) error {
opt := s.kv.opt
// Iterate levels in the reverse order because if we were to iterate from
// lower level (say level 0) to a higher level (say level 3) we could have
// a state in which level 0 is compacted and an older version of a key exists in lower level.
// At this point, if someone creates an iterator, they would see an old
// value for a key from lower levels. Iterating in reverse order ensures we
// drop the oldest data first so that lookups never return stale data.
for i := len(s.levels) - 1; i >= 0; i-- {
l := s.levels[i]
l.RLock()
if l.level == 0 {
size := len(l.tables)
l.RUnlock()
if size > 0 {
cp := compactionPriority{
level: 0,
score: 1.74,
// A unique number greater than 1.0 does two things. Helps identify this
// function in logs, and forces a compaction.
dropPrefixes: prefixes,
}
if err := s.doCompact(174, cp); err != nil {
opt.Warningf("While compacting level 0: %v", err)
return nil
}
}
continue
}
// Build a list of compaction tableGroups affecting all the prefixes we
// need to drop. We need to build tableGroups that satisfy the invariant that
// bottom tables are consecutive.
// tableGroup contains groups of consecutive tables.
var tableGroups [][]*table.Table
var tableGroup []*table.Table
finishGroup := func() {
if len(tableGroup) > 0 {
tableGroups = append(tableGroups, tableGroup)
tableGroup = nil
}
}
for _, table := range l.tables {
if containsAnyPrefixes(table, prefixes) {
tableGroup = append(tableGroup, table)
} else {
finishGroup()
}
}
finishGroup()
l.RUnlock()
if len(tableGroups) == 0 {
continue
}
_, span := otrace.StartSpan(context.Background(), "Badger.Compaction")
span.Annotatef(nil, "Compaction level: %v", l.level)
span.Annotatef(nil, "Drop Prefixes: %v", prefixes)
defer span.End()
opt.Infof("Dropping prefix at level %d (%d tableGroups)", l.level, len(tableGroups))
for _, operation := range tableGroups {
cd := compactDef{
span: span,
thisLevel: l,
nextLevel: l,
top: nil,
bot: operation,
dropPrefixes: prefixes,
t: s.levelTargets(),
}
cd.t.baseLevel = l.level
if err := s.runCompactDef(-1, l.level, cd); err != nil {
opt.Warningf("While running compact def: %+v. Error: %v", cd, err)
return err
}
}
}
return nil
}
func (s *levelsController) startCompact(lc *z.Closer) {
n := s.kv.opt.NumCompactors
lc.AddRunning(n - 1)
for i := 0; i < n; i++ {
go s.runCompactor(i, lc)
}
}
type targets struct {
baseLevel int
targetSz []int64
fileSz []int64
}
// levelTargets calculates the targets for levels in the LSM tree. The idea comes from Dynamic Level
// Sizes ( https://rocksdb.org/blog/2015/07/23/dynamic-level.html ) in RocksDB. The sizes of levels
// are calculated based on the size of the lowest level, typically L6. So, if L6 size is 1GB, then
// L5 target size is 100MB, L4 target size is 10MB and so on.
//
// L0 files don't automatically go to L1. Instead, they get compacted to Lbase, where Lbase is
// chosen based on the first level which is non-empty from top (check L1 through L6). For an empty
// DB, that would be L6. So, L0 compactions go to L6, then L5, L4 and so on.
//
// Lbase is advanced to the upper levels when its target size exceeds BaseLevelSize. For
// example, when L6 reaches 1.1GB, then L4 target sizes becomes 11MB, thus exceeding the
// BaseLevelSize of 10MB. L3 would then become the new Lbase, with a target size of 1MB <
// BaseLevelSize.
func (s *levelsController) levelTargets() targets {
adjust := func(sz int64) int64 {
if sz < s.kv.opt.BaseLevelSize {
return s.kv.opt.BaseLevelSize
}
return sz
}
t := targets{
targetSz: make([]int64, len(s.levels)),
fileSz: make([]int64, len(s.levels)),
}
// DB size is the size of the last level.
dbSize := s.lastLevel().getTotalSize()
for i := len(s.levels) - 1; i > 0; i-- {
ltarget := adjust(dbSize)
t.targetSz[i] = ltarget
if t.baseLevel == 0 && ltarget <= s.kv.opt.BaseLevelSize {
t.baseLevel = i
}
dbSize /= int64(s.kv.opt.LevelSizeMultiplier)
}
tsz := s.kv.opt.BaseTableSize
for i := 0; i < len(s.levels); i++ {
if i == 0 {
// Use MemTableSize for Level 0. Because at Level 0, we stop compactions based on the
// number of tables, not the size of the level. So, having a 1:1 size ratio between
// memtable size and the size of L0 files is better than churning out 32 files per
// memtable (assuming 64MB MemTableSize and 2MB BaseTableSize).
t.fileSz[i] = s.kv.opt.MemTableSize
} else if i <= t.baseLevel {
t.fileSz[i] = tsz
} else {
tsz *= int64(s.kv.opt.TableSizeMultiplier)
t.fileSz[i] = tsz
}
}
// Bring the base level down to the last empty level.
for i := t.baseLevel + 1; i < len(s.levels)-1; i++ {
if s.levels[i].getTotalSize() > 0 {
break
}
t.baseLevel = i
}
// If the base level is empty and the next level size is less than the
// target size, pick the next level as the base level.
b := t.baseLevel
lvl := s.levels
if b < len(lvl)-1 && lvl[b].getTotalSize() == 0 && lvl[b+1].getTotalSize() < t.targetSz[b+1] {
t.baseLevel++
}
return t
}
func (s *levelsController) runCompactor(id int, lc *z.Closer) {
defer lc.Done()
randomDelay := time.NewTimer(time.Duration(rand.Int31n(1000)) * time.Millisecond)
select {
case <-randomDelay.C:
case <-lc.HasBeenClosed():
randomDelay.Stop()
return
}
moveL0toFront := func(prios []compactionPriority) []compactionPriority {
idx := -1
for i, p := range prios {
if p.level == 0 {
idx = i
break
}
}
// If idx == -1, we didn't find L0.
// If idx == 0, then we don't need to do anything. L0 is already at the front.
if idx > 0 {
out := append([]compactionPriority{}, prios[idx])
out = append(out, prios[:idx]...)
out = append(out, prios[idx+1:]...)
return out
}
return prios
}
run := func(p compactionPriority) bool {
err := s.doCompact(id, p)
switch err {
case nil:
return true
case errFillTables:
// pass
default:
s.kv.opt.Warningf("While running doCompact: %v\n", err)
}
return false
}
var priosBuffer []compactionPriority
runOnce := func() bool {
prios := s.pickCompactLevels(priosBuffer)
defer func() {
priosBuffer = prios
}()
if id == 0 {
// Worker ID zero prefers to compact L0 always.
prios = moveL0toFront(prios)
}
for _, p := range prios {
if id == 0 && p.level == 0 {
// Allow worker zero to run level 0, irrespective of its adjusted score.
} else if p.adjusted < 1.0 {
break
}
if run(p) {
return true
}
}
return false
}
tryLmaxToLmaxCompaction := func() {
p := compactionPriority{
level: s.lastLevel().level,
t: s.levelTargets(),
}
run(p)
}
count := 0
ticker := time.NewTicker(50 * time.Millisecond)
defer ticker.Stop()
for {
select {
// Can add a done channel or other stuff.
case <-ticker.C:
count++
// Each ticker is 50ms so 50*200=10seconds.
if s.kv.opt.LmaxCompaction && id == 2 && count >= 200 {
tryLmaxToLmaxCompaction()
count = 0
} else {
runOnce()
}
case <-lc.HasBeenClosed():
return
}
}
}
type compactionPriority struct {
level int
score float64
adjusted float64
dropPrefixes [][]byte
t targets
}
func (s *levelsController) lastLevel() *levelHandler {
return s.levels[len(s.levels)-1]
}
// pickCompactLevel determines which level to compact.
// Based on: https://github.com/facebook/rocksdb/wiki/Leveled-Compaction
// It tries to reuse priosBuffer to reduce memory allocation,
// passing nil is acceptable, then new memory will be allocated.
func (s *levelsController) pickCompactLevels(priosBuffer []compactionPriority) (prios []compactionPriority) {
t := s.levelTargets()
addPriority := func(level int, score float64) {
pri := compactionPriority{
level: level,
score: score,
adjusted: score,
t: t,
}
prios = append(prios, pri)
}
// Grow buffer to fit all levels.
if cap(priosBuffer) < len(s.levels) {
priosBuffer = make([]compactionPriority, 0, len(s.levels))
}
prios = priosBuffer[:0]
// Add L0 priority based on the number of tables.
addPriority(0, float64(s.levels[0].numTables())/float64(s.kv.opt.NumLevelZeroTables))
// All other levels use size to calculate priority.
for i := 1; i < len(s.levels); i++ {
// Don't consider those tables that are already being compacted right now.
delSize := s.cstatus.delSize(i)
l := s.levels[i]
sz := l.getTotalSize() - delSize
addPriority(i, float64(sz)/float64(t.targetSz[i]))
}
y.AssertTrue(len(prios) == len(s.levels))
// The following code is borrowed from PebbleDB and results in healthier LSM tree structure.
// If Li-1 has score > 1.0, then we'll divide Li-1 score by Li. If Li score is >= 1.0, then Li-1
// score is reduced, which means we'll prioritize the compaction of lower levels (L5, L4 and so
// on) over the higher levels (L0, L1 and so on). On the other hand, if Li score is < 1.0, then
// we'll increase the priority of Li-1.
// Overall what this means is, if the bottom level is already overflowing, then de-prioritize
// compaction of the above level. If the bottom level is not full, then increase the priority of
// above level.
var prevLevel int
for level := t.baseLevel; level < len(s.levels); level++ {
if prios[prevLevel].adjusted >= 1 {
// Avoid absurdly large scores by placing a floor on the score that we'll
// adjust a level by. The value of 0.01 was chosen somewhat arbitrarily
const minScore = 0.01
if prios[level].score >= minScore {
prios[prevLevel].adjusted /= prios[level].adjusted
} else {
prios[prevLevel].adjusted /= minScore
}
}
prevLevel = level
}
// Pick all the levels whose original score is >= 1.0, irrespective of their adjusted score.
// We'll still sort them by their adjusted score below. Having both these scores allows us to
// make better decisions about compacting L0. If we see a score >= 1.0, we can do L0->L0
// compactions. If the adjusted score >= 1.0, then we can do L0->Lbase compactions.
out := prios[:0]
for _, p := range prios[:len(prios)-1] {
if p.score >= 1.0 {
out = append(out, p)
}
}
prios = out
// Sort by the adjusted score.
sort.Slice(prios, func(i, j int) bool {
return prios[i].adjusted > prios[j].adjusted
})
return prios
}
// checkOverlap checks if the given tables overlap with any level from the given "lev" onwards.
func (s *levelsController) checkOverlap(tables []*table.Table, lev int) bool {
kr := getKeyRange(tables...)
for i, lh := range s.levels {
if i < lev { // Skip upper levels.
continue
}
lh.RLock()
left, right := lh.overlappingTables(levelHandlerRLocked{}, kr)
lh.RUnlock()
if right-left > 0 {
return true
}
}
return false
}
// subcompact runs a single sub-compaction, iterating over the specified key-range only.
//
// We use splits to do a single compaction concurrently. If we have >= 3 tables
// involved in the bottom level during compaction, we choose key ranges to
// split the main compaction up into sub-compactions. Each sub-compaction runs
// concurrently, only iterating over the provided key range, generating tables.
// This speeds up the compaction significantly.
func (s *levelsController) subcompact(it y.Iterator, kr keyRange, cd compactDef,
inflightBuilders *y.Throttle, res chan<- *table.Table) {
// Check overlap of the top level with the levels which are not being
// compacted in this compaction.
hasOverlap := s.checkOverlap(cd.allTables(), cd.nextLevel.level+1)
// Pick a discard ts, so we can discard versions below this ts. We should
// never discard any versions starting from above this timestamp, because
// that would affect the snapshot view guarantee provided by transactions.
discardTs := s.kv.orc.discardAtOrBelow()
// Try to collect stats so that we can inform value log about GC. That would help us find which
// value log file should be GCed.
discardStats := make(map[uint32]int64)
updateStats := func(vs y.ValueStruct) {
// We don't need to store/update discard stats when badger is running in Disk-less mode.
if s.kv.opt.InMemory {
return
}
if vs.Meta&bitValuePointer > 0 {
var vp valuePointer
vp.Decode(vs.Value)
discardStats[vp.Fid] += int64(vp.Len)
}
}
// exceedsAllowedOverlap returns true if the given key range would overlap with more than 10
// tables from level below nextLevel (nextLevel+1). This helps avoid generating tables at Li
// with huge overlaps with Li+1.
exceedsAllowedOverlap := func(kr keyRange) bool {
n2n := cd.nextLevel.level + 1
if n2n <= 1 || n2n >= len(s.levels) {
return false
}
n2nl := s.levels[n2n]
n2nl.RLock()
defer n2nl.RUnlock()
l, r := n2nl.overlappingTables(levelHandlerRLocked{}, kr)
return r-l >= 10
}
var (
lastKey, skipKey []byte
numBuilds, numVersions int
// Denotes if the first key is a series of duplicate keys had
// "DiscardEarlierVersions" set
firstKeyHasDiscardSet bool
)
addKeys := func(builder *table.Builder) {
timeStart := time.Now()
var numKeys, numSkips uint64
var rangeCheck int
var tableKr keyRange
for ; it.Valid(); it.Next() {
// See if we need to skip the prefix.
if len(cd.dropPrefixes) > 0 && hasAnyPrefixes(it.Key(), cd.dropPrefixes) {
numSkips++
updateStats(it.Value())
continue
}
// See if we need to skip this key.
if len(skipKey) > 0 {
if y.SameKey(it.Key(), skipKey) {
numSkips++
updateStats(it.Value())
continue
} else {
skipKey = skipKey[:0]
}
}
if !y.SameKey(it.Key(), lastKey) {
firstKeyHasDiscardSet = false
if len(kr.right) > 0 && y.CompareKeys(it.Key(), kr.right) >= 0 {
break
}
if builder.ReachedCapacity() {
// Only break if we are on a different key, and have reached capacity. We want
// to ensure that all versions of the key are stored in the same sstable, and
// not divided across multiple tables at the same level.
break
}
lastKey = y.SafeCopy(lastKey, it.Key())
numVersions = 0
firstKeyHasDiscardSet = it.Value().Meta&bitDiscardEarlierVersions > 0
if len(tableKr.left) == 0 {
tableKr.left = y.SafeCopy(tableKr.left, it.Key())
}
tableKr.right = lastKey
rangeCheck++
if rangeCheck%5000 == 0 {
// This table's range exceeds the allowed range overlap with the level after
// next. So, we stop writing to this table. If we don't do this, then we end up
// doing very expensive compactions involving too many tables. To amortize the
// cost of this check, we do it only every N keys.
if exceedsAllowedOverlap(tableKr) {
// s.kv.opt.Debugf("L%d -> L%d Breaking due to exceedsAllowedOverlap with
// kr: %s\n", cd.thisLevel.level, cd.nextLevel.level, tableKr)
break
}
}
}
vs := it.Value()
version := y.ParseTs(it.Key())
isExpired := isDeletedOrExpired(vs.Meta, vs.ExpiresAt)
// Do not discard entries inserted by merge operator. These entries will be
// discarded once they're merged
if version <= discardTs && vs.Meta&bitMergeEntry == 0 {
// Keep track of the number of versions encountered for this key. Only consider the
// versions which are below the minReadTs, otherwise, we might end up discarding the
// only valid version for a running transaction.
numVersions++
// Keep the current version and discard all the next versions if
// - The `discardEarlierVersions` bit is set OR
// - We've already processed `NumVersionsToKeep` number of versions
// (including the current item being processed)
lastValidVersion := vs.Meta&bitDiscardEarlierVersions > 0 ||
numVersions == s.kv.opt.NumVersionsToKeep
if isExpired || lastValidVersion {
// If this version of the key is deleted or expired, skip all the rest of the
// versions. Ensure that we're only removing versions below readTs.
skipKey = y.SafeCopy(skipKey, it.Key())
switch {
// Add the key to the table only if it has not expired.
// We don't want to add the deleted/expired keys.
case !isExpired && lastValidVersion:
// Add this key. We have set skipKey, so the following key versions
// would be skipped.
case hasOverlap:
// If this key range has overlap with lower levels, then keep the deletion
// marker with the latest version, discarding the rest. We have set skipKey,
// so the following key versions would be skipped.
default:
// If no overlap, we can skip all the versions, by continuing here.
numSkips++
updateStats(vs)
continue // Skip adding this key.
}
}
}
numKeys++
var vp valuePointer
if vs.Meta&bitValuePointer > 0 {
vp.Decode(vs.Value)
}
switch {
case firstKeyHasDiscardSet:
// This key is same as the last key which had "DiscardEarlierVersions" set. The
// the next compactions will drop this key if its ts >
// discardTs (of the next compaction).
builder.AddStaleKey(it.Key(), vs, vp.Len)
case isExpired:
// If the key is expired, the next compaction will drop it if
// its ts > discardTs (of the next compaction).
builder.AddStaleKey(it.Key(), vs, vp.Len)
default:
builder.Add(it.Key(), vs, vp.Len)
}
}
s.kv.opt.Debugf("[%d] LOG Compact. Added %d keys. Skipped %d keys. Iteration took: %v",
cd.compactorId, numKeys, numSkips, time.Since(timeStart).Round(time.Millisecond))
} // End of function: addKeys
if len(kr.left) > 0 {
it.Seek(kr.left)
} else {
it.Rewind()
}
for it.Valid() {
if len(kr.right) > 0 && y.CompareKeys(it.Key(), kr.right) >= 0 {
break
}
bopts := buildTableOptions(s.kv)
// Set TableSize to the target file size for that level.
bopts.TableSize = uint64(cd.t.fileSz[cd.nextLevel.level])
builder := table.NewTableBuilder(bopts)
// This would do the iteration and add keys to builder.
addKeys(builder)
// It was true that it.Valid() at least once in the loop above, which means we
// called Add() at least once, and builder is not Empty().
if builder.Empty() {
// Cleanup builder resources:
builder.Finish()
builder.Close()
continue
}
numBuilds++
if err := inflightBuilders.Do(); err != nil {
// Can't return from here, until I decrRef all the tables that I built so far.
break
}
go func(builder *table.Builder, fileID uint64) {
var err error
defer inflightBuilders.Done(err)
defer builder.Close()
var tbl *table.Table
if s.kv.opt.InMemory {
tbl, err = table.OpenInMemoryTable(builder.Finish(), fileID, &bopts)
} else {
fname := table.NewFilename(fileID, s.kv.opt.Dir)
tbl, err = table.CreateTable(fname, builder)
}
// If we couldn't build the table, return fast.
if err != nil {
return
}
res <- tbl
}(builder, s.reserveFileID())
}
s.kv.vlog.updateDiscardStats(discardStats)
s.kv.opt.Debugf("Discard stats: %v", discardStats)
}
// compactBuildTables merges topTables and botTables to form a list of new tables.
func (s *levelsController) compactBuildTables(
lev int, cd compactDef) ([]*table.Table, func() error, error) {
topTables := cd.top
botTables := cd.bot
numTables := int64(len(topTables) + len(botTables))
y.NumCompactionTablesAdd(s.kv.opt.MetricsEnabled, numTables)
defer y.NumCompactionTablesAdd(s.kv.opt.MetricsEnabled, -numTables)
cd.span.Annotatef(nil, "Top tables count: %v Bottom tables count: %v",
len(topTables), len(botTables))
keepTable := func(t *table.Table) bool {
for _, prefix := range cd.dropPrefixes {
if bytes.HasPrefix(t.Smallest(), prefix) &&
bytes.HasPrefix(t.Biggest(), prefix) {
// All the keys in this table have the dropPrefix. So, this
// table does not need to be in the iterator and can be
// dropped immediately.
return false
}
}
return true
}
var valid []*table.Table
for _, table := range botTables {
if keepTable(table) {
valid = append(valid, table)
}
}
newIterator := func() []y.Iterator {
// Create iterators across all the tables involved first.
var iters []y.Iterator
switch {
case lev == 0:
iters = appendIteratorsReversed(iters, topTables, table.NOCACHE)
case len(topTables) > 0:
y.AssertTrue(len(topTables) == 1)
iters = []y.Iterator{topTables[0].NewIterator(table.NOCACHE)}
}
// Next level has level>=1 and we can use ConcatIterator as key ranges do not overlap.
return append(iters, table.NewConcatIterator(valid, table.NOCACHE))
}
res := make(chan *table.Table, 3)
inflightBuilders := y.NewThrottle(8 + len(cd.splits))
for _, kr := range cd.splits {
// Initiate Do here so we can register the goroutines for buildTables too.
if err := inflightBuilders.Do(); err != nil {
s.kv.opt.Errorf("cannot start subcompaction: %+v", err)
return nil, nil, err
}
go func(kr keyRange) {
defer inflightBuilders.Done(nil)
it := table.NewMergeIterator(newIterator(), false)
defer it.Close()
s.subcompact(it, kr, cd, inflightBuilders, res)
}(kr)
}
var newTables []*table.Table
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
for t := range res {
newTables = append(newTables, t)
}
}()
// Wait for all table builders to finish and also for newTables accumulator to finish.
err := inflightBuilders.Finish()
close(res)
wg.Wait() // Wait for all tables to be picked up.
if err == nil {
// Ensure created files' directory entries are visible. We don't mind the extra latency
// from not doing this ASAP after all file creation has finished because this is a
// background operation.
err = s.kv.syncDir(s.kv.opt.Dir)
}
if err != nil {
// An error happened. Delete all the newly created table files (by calling DecrRef
// -- we're the only holders of a ref).
_ = decrRefs(newTables)
return nil, nil, y.Wrapf(err, "while running compactions for: %+v", cd)
}
sort.Slice(newTables, func(i, j int) bool {
return y.CompareKeys(newTables[i].Biggest(), newTables[j].Biggest()) < 0
})
return newTables, func() error { return decrRefs(newTables) }, nil
}
func buildChangeSet(cd *compactDef, newTables []*table.Table) pb.ManifestChangeSet {
changes := []*pb.ManifestChange{}
for _, table := range newTables {
changes = append(changes,
newCreateChange(table.ID(), cd.nextLevel.level, table.KeyID(), table.CompressionType()))
}
for _, table := range cd.top {
// Add a delete change only if the table is not in memory.
if !table.IsInmemory {
changes = append(changes, newDeleteChange(table.ID()))
}
}
for _, table := range cd.bot {
changes = append(changes, newDeleteChange(table.ID()))
}
return pb.ManifestChangeSet{Changes: changes}
}
func hasAnyPrefixes(s []byte, listOfPrefixes [][]byte) bool {
for _, prefix := range listOfPrefixes {
if bytes.HasPrefix(s, prefix) {
return true
}
}
return false
}
func containsPrefix(table *table.Table, prefix []byte) bool {
smallValue := table.Smallest()