forked from cockroachdb/pebble
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ingest.go
2528 lines (2370 loc) · 94.2 KB
/
ingest.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 2018 The LevelDB-Go and Pebble Authors. All rights reserved. Use
// of this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
package pebble
import (
"context"
"fmt"
"slices"
"sort"
"time"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/pebble/internal/base"
"github.com/cockroachdb/pebble/internal/invariants"
"github.com/cockroachdb/pebble/internal/manifest"
"github.com/cockroachdb/pebble/internal/overlap"
"github.com/cockroachdb/pebble/internal/sstableinternal"
"github.com/cockroachdb/pebble/objstorage"
"github.com/cockroachdb/pebble/objstorage/remote"
"github.com/cockroachdb/pebble/sstable"
)
func sstableKeyCompare(userCmp Compare, a, b InternalKey) int {
c := userCmp(a.UserKey, b.UserKey)
if c != 0 {
return c
}
if a.IsExclusiveSentinel() {
if !b.IsExclusiveSentinel() {
return -1
}
} else if b.IsExclusiveSentinel() {
return +1
}
return 0
}
// KeyRange encodes a key range in user key space. A KeyRange's Start is
// inclusive while its End is exclusive.
//
// KeyRange is equivalent to base.UserKeyBounds with exclusive end.
type KeyRange struct {
Start, End []byte
}
// Valid returns true if the KeyRange is defined.
func (k *KeyRange) Valid() bool {
return k.Start != nil && k.End != nil
}
// Contains returns whether the specified key exists in the KeyRange.
func (k *KeyRange) Contains(cmp base.Compare, key InternalKey) bool {
v := cmp(key.UserKey, k.End)
return (v < 0 || (v == 0 && key.IsExclusiveSentinel())) && cmp(k.Start, key.UserKey) <= 0
}
// UserKeyBounds returns the KeyRange as UserKeyBounds. Also implements the internal `bounded` interface.
func (k KeyRange) UserKeyBounds() base.UserKeyBounds {
return base.UserKeyBoundsEndExclusive(k.Start, k.End)
}
// OverlapsInternalKeyRange checks if the specified internal key range has an
// overlap with the KeyRange. Note that we aren't checking for full containment
// of smallest-largest within k, rather just that there's some intersection
// between the two ranges.
func (k *KeyRange) OverlapsInternalKeyRange(cmp base.Compare, smallest, largest InternalKey) bool {
ukb := k.UserKeyBounds()
b := base.UserKeyBoundsFromInternal(smallest, largest)
return ukb.Overlaps(cmp, &b)
}
// Overlaps checks if the specified file has an overlap with the KeyRange.
// Note that we aren't checking for full containment of m within k, rather just
// that there's some intersection between m and k's bounds.
func (k *KeyRange) Overlaps(cmp base.Compare, m *fileMetadata) bool {
b := k.UserKeyBounds()
return m.Overlaps(cmp, &b)
}
// OverlapsKeyRange checks if this span overlaps with the provided KeyRange.
// Note that we aren't checking for full containment of either span in the other,
// just that there's a key x that is in both key ranges.
func (k *KeyRange) OverlapsKeyRange(cmp Compare, span KeyRange) bool {
return cmp(k.Start, span.End) < 0 && cmp(k.End, span.Start) > 0
}
func ingestValidateKey(opts *Options, key *InternalKey) error {
if key.Kind() == InternalKeyKindInvalid {
return base.CorruptionErrorf("pebble: external sstable has corrupted key: %s",
key.Pretty(opts.Comparer.FormatKey))
}
if key.SeqNum() != 0 {
return base.CorruptionErrorf("pebble: external sstable has non-zero seqnum: %s",
key.Pretty(opts.Comparer.FormatKey))
}
return nil
}
// ingestSynthesizeShared constructs a fileMetadata for one shared sstable owned
// or shared by another node.
func ingestSynthesizeShared(
opts *Options, sm SharedSSTMeta, fileNum base.FileNum,
) (*fileMetadata, error) {
if sm.Size == 0 {
// Disallow 0 file sizes
return nil, errors.New("pebble: cannot ingest shared file with size 0")
}
// Don't load table stats. Doing a round trip to shared storage, one SST
// at a time is not worth it as it slows down ingestion.
meta := &fileMetadata{
FileNum: fileNum,
CreationTime: time.Now().Unix(),
Virtual: true,
Size: sm.Size,
}
// For simplicity, we use the same number for both the FileNum and the
// DiskFileNum (even though this is a virtual sstable). Pass the underlying
// FileBacking's size to the same size as the virtualized view of the sstable.
// This ensures that we don't over-prioritize this sstable for compaction just
// yet, as we do not have a clear sense of what parts of this sstable are
// referenced by other nodes.
meta.InitProviderBacking(base.DiskFileNum(fileNum), sm.Size)
if sm.LargestPointKey.Valid() && sm.LargestPointKey.UserKey != nil {
// Initialize meta.{HasPointKeys,Smallest,Largest}, etc.
//
// NB: We create new internal keys and pass them into ExtendPointKeyBounds
// so that we can sub a zero sequence number into the bounds. We can set
// the sequence number to anything here; it'll be reset in ingestUpdateSeqNum
// anyway. However, we do need to use the same sequence number across all
// bound keys at this step so that we end up with bounds that are consistent
// across point/range keys.
//
// Because of the sequence number rewriting, we cannot use the Kind of
// sm.SmallestPointKey. For example, the original SST might start with
// a.SET.2 and a.RANGEDEL.1 (with a.SET.2 being the smallest key); after
// rewriting the sequence numbers, these keys become a.SET.100 and
// a.RANGEDEL.100, with a.RANGEDEL.100 being the smallest key. To create a
// correct bound, we just use the maximum key kind (which sorts first).
// Similarly, we use the smallest key kind for the largest key.
smallestPointKey := base.MakeInternalKey(sm.SmallestPointKey.UserKey, 0, base.InternalKeyKindMax)
largestPointKey := base.MakeInternalKey(sm.LargestPointKey.UserKey, 0, 0)
if sm.LargestPointKey.IsExclusiveSentinel() {
largestPointKey = base.MakeRangeDeleteSentinelKey(sm.LargestPointKey.UserKey)
}
if opts.Comparer.Equal(smallestPointKey.UserKey, largestPointKey.UserKey) &&
smallestPointKey.Trailer < largestPointKey.Trailer {
// We get kinds from the sender, however we substitute our own sequence
// numbers. This can result in cases where an sstable [b#5,SET-b#4,DELSIZED]
// becomes [b#0,SET-b#0,DELSIZED] when we synthesize it here, but the
// kinds need to be reversed now because DelSized > Set.
smallestPointKey, largestPointKey = largestPointKey, smallestPointKey
}
meta.ExtendPointKeyBounds(opts.Comparer.Compare, smallestPointKey, largestPointKey)
}
if sm.LargestRangeKey.Valid() && sm.LargestRangeKey.UserKey != nil {
// Initialize meta.{HasRangeKeys,Smallest,Largest}, etc.
//
// See comment above on why we use a zero sequence number and these key
// kinds here.
smallestRangeKey := base.MakeInternalKey(sm.SmallestRangeKey.UserKey, 0, base.InternalKeyKindRangeKeyMax)
largestRangeKey := base.MakeExclusiveSentinelKey(base.InternalKeyKindRangeKeyMin, sm.LargestRangeKey.UserKey)
meta.ExtendRangeKeyBounds(opts.Comparer.Compare, smallestRangeKey, largestRangeKey)
}
if err := meta.Validate(opts.Comparer.Compare, opts.Comparer.FormatKey); err != nil {
return nil, err
}
return meta, nil
}
// ingestLoad1External loads the fileMetadata for one external sstable.
// Sequence number and target level calculation happens during prepare/apply.
func ingestLoad1External(
opts *Options, e ExternalFile, fileNum base.FileNum,
) (*fileMetadata, error) {
if e.Size == 0 {
return nil, errors.New("pebble: cannot ingest external file with size 0")
}
if !e.HasRangeKey && !e.HasPointKey {
return nil, errors.New("pebble: cannot ingest external file with no point or range keys")
}
if opts.Comparer.Compare(e.StartKey, e.EndKey) > 0 {
return nil, errors.Newf("pebble: external file bounds [%q, %q) are invalid", e.StartKey, e.EndKey)
}
if opts.Comparer.Compare(e.StartKey, e.EndKey) == 0 && !e.EndKeyIsInclusive {
return nil, errors.Newf("pebble: external file bounds [%q, %q) are invalid", e.StartKey, e.EndKey)
}
if n := opts.Comparer.Split(e.StartKey); n != len(e.StartKey) {
return nil, errors.Newf("pebble: external file bounds start key %q has suffix", e.StartKey)
}
if n := opts.Comparer.Split(e.EndKey); n != len(e.EndKey) {
return nil, errors.Newf("pebble: external file bounds end key %q has suffix", e.EndKey)
}
// Don't load table stats. Doing a round trip to shared storage, one SST
// at a time is not worth it as it slows down ingestion.
meta := &fileMetadata{
FileNum: fileNum,
CreationTime: time.Now().Unix(),
Virtual: true,
Size: e.Size,
}
// In the name of keeping this ingestion as fast as possible, we avoid
// *all* existence checks and synthesize a file metadata with smallest/largest
// keys that overlap whatever the passed-in span was.
smallestCopy := slices.Clone(e.StartKey)
largestCopy := slices.Clone(e.EndKey)
if e.HasPointKey {
// Sequence numbers are updated later by
// ingestUpdateSeqNum, applying a squence number that
// is applied to all keys in the sstable.
if e.EndKeyIsInclusive {
meta.ExtendPointKeyBounds(
opts.Comparer.Compare,
base.MakeInternalKey(smallestCopy, 0, InternalKeyKindMax),
base.MakeInternalKey(largestCopy, 0, 0))
} else {
meta.ExtendPointKeyBounds(
opts.Comparer.Compare,
base.MakeInternalKey(smallestCopy, 0, InternalKeyKindMax),
base.MakeRangeDeleteSentinelKey(largestCopy))
}
}
if e.HasRangeKey {
meta.ExtendRangeKeyBounds(
opts.Comparer.Compare,
base.MakeInternalKey(smallestCopy, 0, InternalKeyKindRangeKeyMax),
base.MakeExclusiveSentinelKey(InternalKeyKindRangeKeyMin, largestCopy),
)
}
meta.SyntheticPrefix = e.SyntheticPrefix
meta.SyntheticSuffix = e.SyntheticSuffix
return meta, nil
}
// ingestLoad1 creates the FileMetadata for one file. This file will be owned
// by this store.
func ingestLoad1(
ctx context.Context,
opts *Options,
fmv FormatMajorVersion,
readable objstorage.Readable,
cacheID uint64,
fileNum base.FileNum,
) (*fileMetadata, error) {
o := opts.MakeReaderOptions()
o.SetInternalCacheOpts(sstableinternal.CacheOptions{
Cache: opts.Cache,
CacheID: cacheID,
FileNum: base.PhysicalTableDiskFileNum(fileNum),
})
r, err := sstable.NewReader(ctx, readable, o)
if err != nil {
return nil, err
}
defer r.Close()
// Avoid ingesting tables with format versions this DB doesn't support.
tf, err := r.TableFormat()
if err != nil {
return nil, err
}
if tf < fmv.MinTableFormat() || tf > fmv.MaxTableFormat() {
return nil, errors.Newf(
"pebble: table format %s is not within range supported at DB format major version %d, (%s,%s)",
tf, fmv, fmv.MinTableFormat(), fmv.MaxTableFormat(),
)
}
meta := &fileMetadata{}
meta.FileNum = fileNum
meta.Size = uint64(readable.Size())
meta.CreationTime = time.Now().Unix()
meta.InitPhysicalBacking()
// Avoid loading into the table cache for collecting stats if we
// don't need to. If there are no range deletions, we have all the
// information to compute the stats here.
//
// This is helpful in tests for avoiding awkwardness around deletion of
// ingested files from MemFS. MemFS implements the Windows semantics of
// disallowing removal of an open file. Under MemFS, if we don't populate
// meta.Stats here, the file will be loaded into the table cache for
// calculating stats before we can remove the original link.
maybeSetStatsFromProperties(meta.PhysicalMeta(), &r.Properties)
{
iter, err := r.NewIter(sstable.NoTransforms, nil /* lower */, nil /* upper */)
if err != nil {
return nil, err
}
defer iter.Close()
var smallest InternalKey
if kv := iter.First(); kv != nil {
if err := ingestValidateKey(opts, &kv.K); err != nil {
return nil, err
}
smallest = kv.K.Clone()
}
if err := iter.Error(); err != nil {
return nil, err
}
if kv := iter.Last(); kv != nil {
if err := ingestValidateKey(opts, &kv.K); err != nil {
return nil, err
}
meta.ExtendPointKeyBounds(opts.Comparer.Compare, smallest, kv.K.Clone())
}
if err := iter.Error(); err != nil {
return nil, err
}
}
iter, err := r.NewRawRangeDelIter(ctx, sstable.NoFragmentTransforms)
if err != nil {
return nil, err
}
if iter != nil {
defer iter.Close()
var smallest InternalKey
if s, err := iter.First(); err != nil {
return nil, err
} else if s != nil {
key := s.SmallestKey()
if err := ingestValidateKey(opts, &key); err != nil {
return nil, err
}
smallest = key.Clone()
}
if s, err := iter.Last(); err != nil {
return nil, err
} else if s != nil {
k := s.SmallestKey()
if err := ingestValidateKey(opts, &k); err != nil {
return nil, err
}
largest := s.LargestKey().Clone()
meta.ExtendPointKeyBounds(opts.Comparer.Compare, smallest, largest)
}
}
// Update the range-key bounds for the table.
{
iter, err := r.NewRawRangeKeyIter(ctx, sstable.NoFragmentTransforms)
if err != nil {
return nil, err
}
if iter != nil {
defer iter.Close()
var smallest InternalKey
if s, err := iter.First(); err != nil {
return nil, err
} else if s != nil {
key := s.SmallestKey()
if err := ingestValidateKey(opts, &key); err != nil {
return nil, err
}
smallest = key.Clone()
}
if s, err := iter.Last(); err != nil {
return nil, err
} else if s != nil {
k := s.SmallestKey()
if err := ingestValidateKey(opts, &k); err != nil {
return nil, err
}
// As range keys are fragmented, the end key of the last range key in
// the table provides the upper bound for the table.
largest := s.LargestKey().Clone()
meta.ExtendRangeKeyBounds(opts.Comparer.Compare, smallest, largest)
}
}
}
if !meta.HasPointKeys && !meta.HasRangeKeys {
return nil, nil
}
// Sanity check that the various bounds on the file were set consistently.
if err := meta.Validate(opts.Comparer.Compare, opts.Comparer.FormatKey); err != nil {
return nil, err
}
return meta, nil
}
type ingestLoadResult struct {
local []ingestLocalMeta
shared []ingestSharedMeta
external []ingestExternalMeta
externalFilesHaveLevel bool
}
type ingestLocalMeta struct {
*fileMetadata
path string
}
type ingestSharedMeta struct {
*fileMetadata
shared SharedSSTMeta
}
type ingestExternalMeta struct {
*fileMetadata
external ExternalFile
// usedExistingBacking is true if the external file is reusing a backing
// that existed before this ingestion. In this case, we called
// VirtualBackings.Protect() on that backing; we will need to call
// Unprotect() after the ingestion.
usedExistingBacking bool
}
func (r *ingestLoadResult) fileCount() int {
return len(r.local) + len(r.shared) + len(r.external)
}
func ingestLoad(
opts *Options,
fmv FormatMajorVersion,
paths []string,
shared []SharedSSTMeta,
external []ExternalFile,
cacheID uint64,
pending []base.FileNum,
) (ingestLoadResult, error) {
ctx := context.TODO()
localFileNums := pending[:len(paths)]
sharedFileNums := pending[len(paths) : len(paths)+len(shared)]
externalFileNums := pending[len(paths)+len(shared) : len(paths)+len(shared)+len(external)]
var result ingestLoadResult
result.local = make([]ingestLocalMeta, 0, len(paths))
for i := range paths {
f, err := opts.FS.Open(paths[i])
if err != nil {
return ingestLoadResult{}, err
}
readable, err := sstable.NewSimpleReadable(f)
if err != nil {
return ingestLoadResult{}, err
}
m, err := ingestLoad1(ctx, opts, fmv, readable, cacheID, localFileNums[i])
if err != nil {
return ingestLoadResult{}, err
}
if m != nil {
result.local = append(result.local, ingestLocalMeta{
fileMetadata: m,
path: paths[i],
})
}
}
// Sort the shared files according to level.
sort.Sort(sharedByLevel(shared))
result.shared = make([]ingestSharedMeta, 0, len(shared))
for i := range shared {
m, err := ingestSynthesizeShared(opts, shared[i], sharedFileNums[i])
if err != nil {
return ingestLoadResult{}, err
}
if shared[i].Level < sharedLevelsStart {
return ingestLoadResult{}, errors.New("cannot ingest shared file in level below sharedLevelsStart")
}
result.shared = append(result.shared, ingestSharedMeta{
fileMetadata: m,
shared: shared[i],
})
}
result.external = make([]ingestExternalMeta, 0, len(external))
for i := range external {
m, err := ingestLoad1External(opts, external[i], externalFileNums[i])
if err != nil {
return ingestLoadResult{}, err
}
result.external = append(result.external, ingestExternalMeta{
fileMetadata: m,
external: external[i],
})
if external[i].Level > 0 {
if i != 0 && !result.externalFilesHaveLevel {
return ingestLoadResult{}, base.AssertionFailedf("pebble: external sstables must all have level set or unset")
}
result.externalFilesHaveLevel = true
} else if result.externalFilesHaveLevel {
return ingestLoadResult{}, base.AssertionFailedf("pebble: external sstables must all have level set or unset")
}
}
return result, nil
}
func ingestSortAndVerify(cmp Compare, lr ingestLoadResult, exciseSpan KeyRange) error {
// Verify that all the shared files (i.e. files in sharedMeta)
// fit within the exciseSpan.
for _, f := range lr.shared {
if !exciseSpan.Contains(cmp, f.Smallest) || !exciseSpan.Contains(cmp, f.Largest) {
return errors.Newf("pebble: shared file outside of excise span, span [%s-%s), file = %s", exciseSpan.Start, exciseSpan.End, f.String())
}
}
if lr.externalFilesHaveLevel {
for _, f := range lr.external {
if !exciseSpan.Contains(cmp, f.Smallest) || !exciseSpan.Contains(cmp, f.Largest) {
return base.AssertionFailedf("pebble: external file outside of excise span, span [%s-%s), file = %s", exciseSpan.Start, exciseSpan.End, f.String())
}
}
}
if len(lr.external) > 0 {
if len(lr.shared) > 0 {
// If external files are present alongside shared files,
// return an error.
return base.AssertionFailedf("pebble: external files cannot be ingested atomically alongside shared files")
}
// Sort according to the smallest key.
slices.SortFunc(lr.external, func(a, b ingestExternalMeta) int {
return cmp(a.Smallest.UserKey, b.Smallest.UserKey)
})
for i := 1; i < len(lr.external); i++ {
if sstableKeyCompare(cmp, lr.external[i-1].Largest, lr.external[i].Smallest) >= 0 {
return errors.Newf("pebble: external sstables have overlapping ranges")
}
}
return nil
}
if len(lr.local) <= 1 {
return nil
}
// Sort according to the smallest key.
slices.SortFunc(lr.local, func(a, b ingestLocalMeta) int {
return cmp(a.Smallest.UserKey, b.Smallest.UserKey)
})
for i := 1; i < len(lr.local); i++ {
if sstableKeyCompare(cmp, lr.local[i-1].Largest, lr.local[i].Smallest) >= 0 {
return errors.Newf("pebble: local ingestion sstables have overlapping ranges")
}
}
if len(lr.shared) == 0 {
return nil
}
filesInLevel := make([]*fileMetadata, 0, len(lr.shared))
for l := sharedLevelsStart; l < numLevels; l++ {
filesInLevel = filesInLevel[:0]
for i := range lr.shared {
if lr.shared[i].shared.Level == uint8(l) {
filesInLevel = append(filesInLevel, lr.shared[i].fileMetadata)
}
}
for i := range lr.external {
if lr.external[i].external.Level == uint8(l) {
filesInLevel = append(filesInLevel, lr.external[i].fileMetadata)
}
}
slices.SortFunc(filesInLevel, func(a, b *fileMetadata) int {
return cmp(a.Smallest.UserKey, b.Smallest.UserKey)
})
for i := 1; i < len(filesInLevel); i++ {
if sstableKeyCompare(cmp, filesInLevel[i-1].Largest, filesInLevel[i].Smallest) >= 0 {
return base.AssertionFailedf("pebble: external shared sstables have overlapping ranges")
}
}
}
return nil
}
func ingestCleanup(objProvider objstorage.Provider, meta []ingestLocalMeta) error {
var firstErr error
for i := range meta {
if err := objProvider.Remove(fileTypeTable, meta[i].FileBacking.DiskFileNum); err != nil {
firstErr = firstError(firstErr, err)
}
}
return firstErr
}
// ingestLinkLocal creates new objects which are backed by either hardlinks to or
// copies of the ingested files.
func ingestLinkLocal(
jobID JobID, opts *Options, objProvider objstorage.Provider, localMetas []ingestLocalMeta,
) error {
for i := range localMetas {
objMeta, err := objProvider.LinkOrCopyFromLocal(
context.TODO(), opts.FS, localMetas[i].path, fileTypeTable, localMetas[i].FileBacking.DiskFileNum,
objstorage.CreateOptions{PreferSharedStorage: true},
)
if err != nil {
if err2 := ingestCleanup(objProvider, localMetas[:i]); err2 != nil {
opts.Logger.Errorf("ingest cleanup failed: %v", err2)
}
return err
}
if opts.EventListener.TableCreated != nil {
opts.EventListener.TableCreated(TableCreateInfo{
JobID: int(jobID),
Reason: "ingesting",
Path: objProvider.Path(objMeta),
FileNum: base.PhysicalTableDiskFileNum(localMetas[i].FileNum),
})
}
}
return nil
}
// ingestAttachRemote attaches remote objects to the storage provider.
//
// For external objects, we reuse existing FileBackings from the current version
// when possible.
//
// ingestUnprotectExternalBackings() must be called after this function (even in
// error cases).
func (d *DB) ingestAttachRemote(jobID JobID, lr ingestLoadResult) error {
remoteObjs := make([]objstorage.RemoteObjectToAttach, 0, len(lr.shared)+len(lr.external))
for i := range lr.shared {
backing, err := lr.shared[i].shared.Backing.Get()
if err != nil {
return err
}
remoteObjs = append(remoteObjs, objstorage.RemoteObjectToAttach{
FileNum: lr.shared[i].FileBacking.DiskFileNum,
FileType: fileTypeTable,
Backing: backing,
})
}
d.findExistingBackingsForExternalObjects(lr.external)
newFileBackings := make(map[remote.ObjectKey]*fileBacking, len(lr.external))
for i := range lr.external {
meta := lr.external[i].fileMetadata
if meta.FileBacking != nil {
// The backing was filled in by findExistingBackingsForExternalObjects().
continue
}
key := remote.MakeObjectKey(lr.external[i].external.Locator, lr.external[i].external.ObjName)
if backing, ok := newFileBackings[key]; ok {
// We already created the same backing in this loop.
meta.FileBacking = backing
continue
}
providerBacking, err := d.objProvider.CreateExternalObjectBacking(key.Locator, key.ObjectName)
if err != nil {
return err
}
// We have to attach the remote object (and assign it a DiskFileNum). For
// simplicity, we use the same number for both the FileNum and the
// DiskFileNum (even though this is a virtual sstable).
meta.InitProviderBacking(base.DiskFileNum(meta.FileNum), lr.external[i].external.Size)
// Set the underlying FileBacking's size to the same size as the virtualized
// view of the sstable. This ensures that we don't over-prioritize this
// sstable for compaction just yet, as we do not have a clear sense of
// what parts of this sstable are referenced by other nodes.
meta.FileBacking.Size = lr.external[i].external.Size
newFileBackings[key] = meta.FileBacking
remoteObjs = append(remoteObjs, objstorage.RemoteObjectToAttach{
FileNum: meta.FileBacking.DiskFileNum,
FileType: fileTypeTable,
Backing: providerBacking,
})
}
for i := range lr.external {
if err := lr.external[i].Validate(d.opts.Comparer.Compare, d.opts.Comparer.FormatKey); err != nil {
return err
}
}
remoteObjMetas, err := d.objProvider.AttachRemoteObjects(remoteObjs)
if err != nil {
return err
}
for i := range lr.shared {
// One corner case around file sizes we need to be mindful of, is that
// if one of the shareObjs was initially created by us (and has boomeranged
// back from another node), we'll need to update the FileBacking's size
// to be the true underlying size. Otherwise, we could hit errors when we
// open the db again after a crash/restart (see checkConsistency in open.go),
// plus it more accurately allows us to prioritize compactions of files
// that were originally created by us.
if remoteObjMetas[i].IsShared() && !d.objProvider.IsSharedForeign(remoteObjMetas[i]) {
size, err := d.objProvider.Size(remoteObjMetas[i])
if err != nil {
return err
}
lr.shared[i].FileBacking.Size = uint64(size)
}
}
if d.opts.EventListener.TableCreated != nil {
for i := range remoteObjMetas {
d.opts.EventListener.TableCreated(TableCreateInfo{
JobID: int(jobID),
Reason: "ingesting",
Path: d.objProvider.Path(remoteObjMetas[i]),
FileNum: remoteObjMetas[i].DiskFileNum,
})
}
}
return nil
}
// findExistingBackingsForExternalObjects populates the FileBacking for external
// files which are already in use by the current version.
//
// We take a Ref and LatestRef on populated backings.
func (d *DB) findExistingBackingsForExternalObjects(metas []ingestExternalMeta) {
d.mu.Lock()
defer d.mu.Unlock()
for i := range metas {
diskFileNums := d.objProvider.GetExternalObjects(metas[i].external.Locator, metas[i].external.ObjName)
// We cross-check against fileBackings in the current version because it is
// possible that the external object is referenced by an sstable which only
// exists in a previous version. In that case, that object could be removed
// at any time so we cannot reuse it.
for _, n := range diskFileNums {
if backing, ok := d.mu.versions.virtualBackings.Get(n); ok {
// Protect this backing from being removed from the latest version. We
// will unprotect in ingestUnprotectExternalBackings.
d.mu.versions.virtualBackings.Protect(n)
metas[i].usedExistingBacking = true
metas[i].FileBacking = backing
break
}
}
}
}
// ingestUnprotectExternalBackings unprotects the file backings that were reused
// for external objects when the ingestion fails.
func (d *DB) ingestUnprotectExternalBackings(lr ingestLoadResult) {
d.mu.Lock()
defer d.mu.Unlock()
for _, meta := range lr.external {
if meta.usedExistingBacking {
// If the backing is not use anywhere else and the ingest failed (or the
// ingested tables were already compacted away), this call will cause in
// the next version update to remove the backing.
d.mu.versions.virtualBackings.Unprotect(meta.FileBacking.DiskFileNum)
}
}
}
func setSeqNumInMetadata(
m *fileMetadata, seqNum base.SeqNum, cmp Compare, format base.FormatKey,
) error {
setSeqFn := func(k base.InternalKey) base.InternalKey {
return base.MakeInternalKey(k.UserKey, seqNum, k.Kind())
}
// NB: we set the fields directly here, rather than via their Extend*
// methods, as we are updating sequence numbers.
if m.HasPointKeys {
m.SmallestPointKey = setSeqFn(m.SmallestPointKey)
}
if m.HasRangeKeys {
m.SmallestRangeKey = setSeqFn(m.SmallestRangeKey)
}
m.Smallest = setSeqFn(m.Smallest)
// Only update the seqnum for the largest key if that key is not an
// "exclusive sentinel" (i.e. a range deletion sentinel or a range key
// boundary), as doing so effectively drops the exclusive sentinel (by
// lowering the seqnum from the max value), and extends the bounds of the
// table.
// NB: as the largest range key is always an exclusive sentinel, it is never
// updated.
if m.HasPointKeys && !m.LargestPointKey.IsExclusiveSentinel() {
m.LargestPointKey = setSeqFn(m.LargestPointKey)
}
if !m.Largest.IsExclusiveSentinel() {
m.Largest = setSeqFn(m.Largest)
}
// Setting smallestSeqNum == largestSeqNum triggers the setting of
// Properties.GlobalSeqNum when an sstable is loaded.
m.SmallestSeqNum = seqNum
m.LargestSeqNum = seqNum
m.LargestSeqNumAbsolute = seqNum
// Ensure the new bounds are consistent.
if err := m.Validate(cmp, format); err != nil {
return err
}
return nil
}
func ingestUpdateSeqNum(
cmp Compare, format base.FormatKey, seqNum base.SeqNum, loadResult ingestLoadResult,
) error {
// Shared sstables are required to be sorted by level ascending. We then
// iterate the shared sstables in reverse, assigning the lower sequence
// numbers to the shared sstables that will be ingested into the lower
// (larger numbered) levels first. This ensures sequence number shadowing is
// correct.
for i := len(loadResult.shared) - 1; i >= 0; i-- {
if i-1 >= 0 && loadResult.shared[i-1].shared.Level > loadResult.shared[i].shared.Level {
panic(errors.AssertionFailedf("shared files %s, %s out of order", loadResult.shared[i-1], loadResult.shared[i]))
}
if err := setSeqNumInMetadata(loadResult.shared[i].fileMetadata, seqNum, cmp, format); err != nil {
return err
}
seqNum++
}
for i := range loadResult.external {
if err := setSeqNumInMetadata(loadResult.external[i].fileMetadata, seqNum, cmp, format); err != nil {
return err
}
seqNum++
}
for i := range loadResult.local {
if err := setSeqNumInMetadata(loadResult.local[i].fileMetadata, seqNum, cmp, format); err != nil {
return err
}
seqNum++
}
return nil
}
// ingestTargetLevel returns the target level for a file being ingested.
// If suggestSplit is true, it accounts for ingest-time splitting as part of
// its target level calculation, and if a split candidate is found, that file
// is returned as the splitFile.
func ingestTargetLevel(
ctx context.Context,
cmp base.Compare,
lsmOverlap overlap.WithLSM,
baseLevel int,
compactions map[*compaction]struct{},
meta *fileMetadata,
suggestSplit bool,
) (targetLevel int, splitFile *fileMetadata, err error) {
// Find the lowest level which does not have any files which overlap meta. We
// search from L0 to L6 looking for whether there are any files in the level
// which overlap meta. We want the "lowest" level (where lower means
// increasing level number) in order to reduce write amplification.
//
// There are 2 kinds of overlap we need to check for: file boundary overlap
// and data overlap. Data overlap implies file boundary overlap. Note that it
// is always possible to ingest into L0.
//
// To place meta at level i where i > 0:
// - there must not be any data overlap with levels <= i, since that will
// violate the sequence number invariant.
// - no file boundary overlap with level i, since that will violate the
// invariant that files do not overlap in levels i > 0.
// - if there is only a file overlap at a given level, and no data overlap,
// we can still slot a file at that level. We return the fileMetadata with
// which we have file boundary overlap (must be only one file, as sstable
// bounds are usually tight on user keys) and the caller is expected to split
// that sstable into two virtual sstables, allowing this file to go into that
// level. Note that if we have file boundary overlap with two files, which
// should only happen on rare occasions, we treat it as data overlap and
// don't use this optimization.
//
// The file boundary overlap check is simpler to conceptualize. Consider the
// following example, in which the ingested file lies completely before or
// after the file being considered.
//
// |--| |--| ingested file: [a,b] or [f,g]
// |-----| existing file: [c,e]
// _____________________
// a b c d e f g
//
// In both cases the ingested file can move to considering the next level.
//
// File boundary overlap does not necessarily imply data overlap. The check
// for data overlap is a little more nuanced. Consider the following examples:
//
// 1. No data overlap:
//
// |-| |--| ingested file: [cc-d] or [ee-ff]
// |*--*--*----*------*| existing file: [a-g], points: [a, b, c, dd, g]
// _____________________
// a b c d e f g
//
// In this case the ingested files can "fall through" this level. The checks
// continue at the next level.
//
// 2. Data overlap:
//
// |--| ingested file: [d-e]
// |*--*--*----*------*| existing file: [a-g], points: [a, b, c, dd, g]
// _____________________
// a b c d e f g
//
// In this case the file cannot be ingested into this level as the point 'dd'
// is in the way.
//
// It is worth noting that the check for data overlap is only approximate. In
// the previous example, the ingested table [d-e] could contain only the
// points 'd' and 'e', in which case the table would be eligible for
// considering lower levels. However, such a fine-grained check would need to
// be exhaustive (comparing points and ranges in both the ingested existing
// tables) and such a check is prohibitively expensive. Thus Pebble treats any
// existing point that falls within the ingested table bounds as being "data
// overlap".
if lsmOverlap[0].Result == overlap.Data {
return 0, nil, nil
}
targetLevel = 0
splitFile = nil
for level := baseLevel; level < numLevels; level++ {
var candidateSplitFile *fileMetadata
switch lsmOverlap[level].Result {
case overlap.Data:
// We cannot ingest into or under this level; return the best target level
// so far.
return targetLevel, splitFile, nil
case overlap.OnlyBoundary:
if !suggestSplit || lsmOverlap[level].SplitFile == nil {
// We can ingest under this level, but not into this level.
continue
}
// We can ingest into this level if we split this file.
candidateSplitFile = lsmOverlap[level].SplitFile
case overlap.None:
// We can ingest into this level.
default:
return 0, nil, base.AssertionFailedf("unexpected WithLevel.Result: %v", lsmOverlap[level].Result)
}
// Check boundary overlap with any ongoing compactions. We consider an
// overlapping compaction that's writing files to an output level as
// equivalent to boundary overlap with files in that output level.
//
// We cannot check for data overlap with the new SSTs compaction will produce
// since compaction hasn't been done yet. However, there's no need to check
// since all keys in them will be from levels in [c.startLevel,
// c.outputLevel], and all those levels have already had their data overlap
// tested negative (else we'd have returned earlier).
//
// An alternative approach would be to cancel these compactions and proceed
// with an ingest-time split on this level if necessary. However, compaction
// cancellation can result in significant wasted effort and is best avoided
// unless necessary.
overlaps := false
for c := range compactions {
if c.outputLevel == nil || level != c.outputLevel.level {
continue
}
if cmp(meta.Smallest.UserKey, c.largest.UserKey) <= 0 &&
cmp(meta.Largest.UserKey, c.smallest.UserKey) >= 0 {
overlaps = true
break
}
}
if !overlaps {
targetLevel = level
splitFile = candidateSplitFile
}
}
return targetLevel, splitFile, nil
}
// Ingest ingests a set of sstables into the DB. Ingestion of the files is
// atomic and semantically equivalent to creating a single batch containing all
// of the mutations in the sstables. Ingestion may require the memtable to be
// flushed. The ingested sstable files are moved into the DB and must reside on
// the same filesystem as the DB. Sstables can be created for ingestion using
// sstable.Writer. On success, Ingest removes the input paths.
//
// Two types of sstables are accepted for ingestion(s): one is sstables present
// in the instance's vfs.FS and can be referenced locally. The other is sstables
// present in remote.Storage, referred to as shared or foreign sstables. These
// shared sstables can be linked through objstorageprovider.Provider, and do not
// need to already be present on the local vfs.FS. Foreign sstables must all fit
// in an excise span, and are destined for a level specified in SharedSSTMeta.
//
// All sstables *must* be Sync()'d by the caller after all bytes are written
// and before its file handle is closed; failure to do so could violate
// durability or lead to corrupted on-disk state. This method cannot, in a
// platform-and-FS-agnostic way, ensure that all sstables in the input are
// properly synced to disk. Opening new file handles and Sync()-ing them
// does not always guarantee durability; see the discussion here on that:
// https://github.com/cockroachdb/pebble/pull/835#issuecomment-663075379
//
// Ingestion loads each sstable into the lowest level of the LSM which it
// doesn't overlap (see ingestTargetLevel). If an sstable overlaps a memtable,
// ingestion forces the memtable to flush, and then waits for the flush to
// occur. In some cases, such as with no foreign sstables and no excise span,
// ingestion that gets blocked on a memtable can join the flushable queue and