-
Notifications
You must be signed in to change notification settings - Fork 0
/
ingest.go
2381 lines (2252 loc) · 86.8 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 estore
import (
"context"
"sort"
"time"
"github.com/cockroachdb/errors"
"github.com/edgelesssys/estore/internal/base"
"github.com/edgelesssys/estore/internal/invariants"
"github.com/edgelesssys/estore/internal/keyspan"
"github.com/edgelesssys/estore/internal/manifest"
"github.com/edgelesssys/estore/internal/private"
"github.com/edgelesssys/estore/objstorage"
"github.com/edgelesssys/estore/objstorage/remote"
"github.com/edgelesssys/estore/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.
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
}
// 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 {
v := cmp(k.Start, largest.UserKey)
return v <= 0 && !(largest.IsExclusiveSentinel() && v == 0) &&
cmp(k.End, smallest.UserKey) > 0
}
// 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 {
return k.OverlapsInternalKeyRange(cmp, m.Smallest, m.Largest)
}
// 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.DiskFileNum,
) (*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.FileNum(),
CreationTime: time.Now().Unix(),
Virtual: true,
Size: sm.Size,
}
meta.InitProviderBacking(fileNum)
// 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 = sm.Size
if sm.LargestRangeKey.Valid() && sm.LargestRangeKey.UserKey != nil {
// Initialize meta.{HasRangeKeys,Smallest,Largest}, etc.
//
// NB: We create new internal keys and pass them into ExternalRangeKeyBounds
// 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.
smallestRangeKey := base.MakeInternalKey(sm.SmallestRangeKey.UserKey, 0, sm.SmallestRangeKey.Kind())
largestRangeKey := base.MakeExclusiveSentinelKey(sm.LargestRangeKey.Kind(), sm.LargestRangeKey.UserKey)
meta.ExtendRangeKeyBounds(opts.Comparer.Compare, smallestRangeKey, largestRangeKey)
}
if sm.LargestPointKey.Valid() && sm.LargestPointKey.UserKey != nil {
// Initialize meta.{HasPointKeys,Smallest,Largest}, etc.
//
// See point above in the ExtendRangeKeyBounds call on why we use a zero
// sequence number here.
smallestPointKey := base.MakeInternalKey(sm.SmallestPointKey.UserKey, 0, sm.SmallestPointKey.Kind())
largestPointKey := base.MakeInternalKey(sm.LargestPointKey.UserKey, 0, sm.LargestPointKey.Kind())
if sm.LargestPointKey.IsExclusiveSentinel() {
largestPointKey = base.MakeRangeDeleteSentinelKey(sm.LargestPointKey.UserKey)
}
meta.ExtendPointKeyBounds(opts.Comparer.Compare, smallestPointKey, largestPointKey)
}
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.DiskFileNum,
objprovider objstorage.Provider,
jobID int,
) (*fileMetadata, error) {
if e.Size == 0 {
// Disallow 0 file sizes
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")
}
// 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{}
meta.FileNum = fileNum.FileNum()
meta.CreationTime = time.Now().Unix()
meta.Virtual = true
meta.Size = e.Size
meta.InitProviderBacking(fileNum)
// Try to resolve a reference to the external file.
backing, err := objprovider.CreateExternalObjectBacking(e.Locator, e.ObjName)
if err != nil {
return nil, err
}
metas, err := objprovider.AttachRemoteObjects([]objstorage.RemoteObjectToAttach{{
FileNum: fileNum,
FileType: fileTypeTable,
Backing: backing,
}})
if err != nil {
return nil, err
}
if opts.EventListener.TableCreated != nil {
opts.EventListener.TableCreated(TableCreateInfo{
JobID: jobID,
Reason: "ingesting",
Path: objprovider.Path(metas[0]),
FileNum: fileNum.FileNum(),
})
}
// 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 := make([]byte, len(e.SmallestUserKey))
copy(smallestCopy, e.SmallestUserKey)
largestCopy := make([]byte, len(e.LargestUserKey))
copy(largestCopy, e.LargestUserKey)
if e.HasPointKey {
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, InternalKeyKindRangeKeySet),
base.MakeExclusiveSentinelKey(InternalKeyKindRangeKeyDelete, largestCopy))
}
// 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 = e.Size
if err := meta.Validate(opts.Comparer.Compare, opts.Comparer.FormatKey); err != nil {
return nil, err
}
return meta, nil
}
// ingestLoad1 creates the FileMetadata for one file. This file will be owned
// by this store.
func ingestLoad1(
opts *Options,
fmv FormatMajorVersion,
readable objstorage.Readable,
cacheID uint64,
fileNum base.DiskFileNum,
) (*fileMetadata, error) {
cacheOpts := private.SSTableCacheOpts(cacheID, fileNum).(sstable.ReaderOption)
r, err := sstable.NewReader(readable, opts.MakeReaderOptions(), cacheOpts)
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.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(nil /* lower */, nil /* upper */)
if err != nil {
return nil, err
}
defer iter.Close()
var smallest InternalKey
if key, _ := iter.First(); key != nil {
if err := ingestValidateKey(opts, key); err != nil {
return nil, err
}
smallest = (*key).Clone()
}
if err := iter.Error(); err != nil {
return nil, err
}
if key, _ := iter.Last(); key != nil {
if err := ingestValidateKey(opts, key); err != nil {
return nil, err
}
meta.ExtendPointKeyBounds(opts.Comparer.Compare, smallest, key.Clone())
}
if err := iter.Error(); err != nil {
return nil, err
}
}
iter, err := r.NewRawRangeDelIter()
if err != nil {
return nil, err
}
if iter != nil {
defer iter.Close()
var smallest InternalKey
if s := iter.First(); s != nil {
key := s.SmallestKey()
if err := ingestValidateKey(opts, &key); err != nil {
return nil, err
}
smallest = key.Clone()
}
if err := iter.Error(); err != nil {
return nil, err
}
if s := iter.Last(); 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()
if err != nil {
return nil, err
}
if iter != nil {
defer iter.Close()
var smallest InternalKey
if s := iter.First(); s != nil {
key := s.SmallestKey()
if err := ingestValidateKey(opts, &key); err != nil {
return nil, err
}
smallest = key.Clone()
}
if err := iter.Error(); err != nil {
return nil, err
}
if s := iter.Last(); 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 err := iter.Error(); err != nil {
return nil, err
}
}
}
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 {
localMeta, sharedMeta []*fileMetadata
externalMeta []*fileMetadata
localPaths []string
sharedLevels []uint8
fileCount int
}
func ingestLoad(
opts *Options,
fmv FormatMajorVersion,
paths []string,
shared []SharedSSTMeta,
external []ExternalFile,
cacheID uint64,
pending []base.DiskFileNum,
objProvider objstorage.Provider,
jobID int,
) (ingestLoadResult, error) {
meta := make([]*fileMetadata, 0, len(paths))
newPaths := make([]string, 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(opts, fmv, readable, cacheID, pending[i])
if err != nil {
return ingestLoadResult{}, err
}
if m != nil {
meta = append(meta, m)
newPaths = append(newPaths, paths[i])
}
}
if len(shared) == 0 && len(external) == 0 {
return ingestLoadResult{localMeta: meta, localPaths: newPaths, fileCount: len(meta)}, nil
}
// Sort the shared files according to level.
sort.Sort(sharedByLevel(shared))
sharedMeta := make([]*fileMetadata, 0, len(shared))
levels := make([]uint8, 0, len(shared))
for i := range shared {
m, err := ingestSynthesizeShared(opts, shared[i], pending[len(paths)+i])
if err != nil {
return ingestLoadResult{}, err
}
if shared[i].Level < sharedLevelsStart {
return ingestLoadResult{}, errors.New("cannot ingest shared file in level below sharedLevelsStart")
}
sharedMeta = append(sharedMeta, m)
levels = append(levels, shared[i].Level)
}
externalMeta := make([]*fileMetadata, 0, len(external))
for i := range external {
m, err := ingestLoad1External(opts, external[i], pending[len(paths)+len(shared)+i], objProvider, jobID)
if err != nil {
return ingestLoadResult{}, err
}
externalMeta = append(externalMeta, m)
}
result := ingestLoadResult{
localMeta: meta,
sharedMeta: sharedMeta,
externalMeta: externalMeta,
localPaths: newPaths,
sharedLevels: levels,
fileCount: len(meta) + len(sharedMeta) + len(externalMeta),
}
return result, nil
}
// Struct for sorting metadatas by smallest user keys, while ensuring the
// matching path also gets swapped to the same index. For use in
// ingestSortAndVerify.
type metaAndPaths struct {
meta []*fileMetadata
paths []string
cmp Compare
}
func (m metaAndPaths) Len() int {
return len(m.meta)
}
func (m metaAndPaths) Less(i, j int) bool {
return m.cmp(m.meta[i].Smallest.UserKey, m.meta[j].Smallest.UserKey) < 0
}
func (m metaAndPaths) Swap(i, j int) {
m.meta[i], m.meta[j] = m.meta[j], m.meta[i]
if m.paths != nil {
m.paths[i], m.paths[j] = m.paths[j], m.paths[i]
}
}
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 i := range lr.sharedMeta {
f := lr.sharedMeta[i]
if !exciseSpan.Contains(cmp, f.Smallest) || !exciseSpan.Contains(cmp, f.Largest) {
return errors.AssertionFailedf("pebble: shared file outside of excise span, span [%s-%s), file = %s", exciseSpan.Start, exciseSpan.End, f.String())
}
}
if len(lr.externalMeta) > 0 {
if len(lr.localMeta) > 0 || len(lr.sharedMeta) > 0 {
// Currently we only support external ingests on their own. If external
// files are present alongside local/shared files, return an error.
return errors.AssertionFailedf("pebble: external files cannot be ingested atomically alongside other types of files")
}
sort.Sort(&metaAndPaths{
meta: lr.externalMeta,
cmp: cmp,
})
for i := 1; i < len(lr.externalMeta); i++ {
if sstableKeyCompare(cmp, lr.externalMeta[i-1].Largest, lr.externalMeta[i].Smallest) >= 0 {
return errors.AssertionFailedf("pebble: external sstables have overlapping ranges")
}
}
return nil
}
if len(lr.localMeta) <= 1 || len(lr.localPaths) <= 1 {
return nil
}
sort.Sort(&metaAndPaths{
meta: lr.localMeta,
paths: lr.localPaths,
cmp: cmp,
})
for i := 1; i < len(lr.localPaths); i++ {
if sstableKeyCompare(cmp, lr.localMeta[i-1].Largest, lr.localMeta[i].Smallest) >= 0 {
return errors.AssertionFailedf("pebble: local ingestion sstables have overlapping ranges")
}
}
if len(lr.sharedMeta) == 0 {
return nil
}
filesInLevel := make([]*fileMetadata, 0, len(lr.sharedMeta))
for l := sharedLevelsStart; l < numLevels; l++ {
filesInLevel = filesInLevel[:0]
for i := range lr.sharedMeta {
if lr.sharedLevels[i] == uint8(l) {
filesInLevel = append(filesInLevel, lr.sharedMeta[i])
}
}
sort.Slice(filesInLevel, func(i, j int) bool {
return cmp(filesInLevel[i].Smallest.UserKey, filesInLevel[j].Smallest.UserKey) < 0
})
for i := 1; i < len(filesInLevel); i++ {
if sstableKeyCompare(cmp, filesInLevel[i-1].Largest, filesInLevel[i].Smallest) >= 0 {
return errors.AssertionFailedf("pebble: external shared sstables have overlapping ranges")
}
}
}
return nil
}
func ingestCleanup(objProvider objstorage.Provider, meta []*fileMetadata) 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
}
// ingestLink creates new objects which are backed by either hardlinks to or
// copies of the ingested files. It also attaches shared objects to the provider.
func ingestLink(
jobID int,
opts *Options,
objProvider objstorage.Provider,
lr ingestLoadResult,
shared []SharedSSTMeta,
) error {
for i := range lr.localPaths {
objMeta, err := objProvider.LinkOrCopyFromLocal(
context.TODO(), opts.FS, lr.localPaths[i], fileTypeTable, lr.localMeta[i].FileBacking.DiskFileNum,
objstorage.CreateOptions{PreferSharedStorage: true},
)
if err != nil {
if err2 := ingestCleanup(objProvider, lr.localMeta[:i]); err2 != nil {
opts.Logger.Infof("ingest cleanup failed: %v", err2)
}
return err
}
if opts.EventListener.TableCreated != nil {
opts.EventListener.TableCreated(TableCreateInfo{
JobID: jobID,
Reason: "ingesting",
Path: objProvider.Path(objMeta),
FileNum: lr.localMeta[i].FileNum,
})
}
}
sharedObjs := make([]objstorage.RemoteObjectToAttach, 0, len(shared))
for i := range shared {
backing, err := shared[i].Backing.Get()
if err != nil {
return err
}
sharedObjs = append(sharedObjs, objstorage.RemoteObjectToAttach{
FileNum: lr.sharedMeta[i].FileBacking.DiskFileNum,
FileType: fileTypeTable,
Backing: backing,
})
}
sharedObjMetas, err := objProvider.AttachRemoteObjects(sharedObjs)
if err != nil {
return err
}
for i := range sharedObjMetas {
// 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 sharedObjMetas[i].IsShared() && !objProvider.IsSharedForeign(sharedObjMetas[i]) {
size, err := objProvider.Size(sharedObjMetas[i])
if err != nil {
return err
}
lr.sharedMeta[i].FileBacking.Size = uint64(size)
}
if opts.EventListener.TableCreated != nil {
opts.EventListener.TableCreated(TableCreateInfo{
JobID: jobID,
Reason: "ingesting",
Path: objProvider.Path(sharedObjMetas[i]),
FileNum: lr.sharedMeta[i].FileNum,
})
}
}
// We do not need to do anything about lr.externalMetas. Those were already
// linked in ingestLoad.
return nil
}
func ingestMemtableOverlaps(cmp Compare, mem flushable, keyRanges []internalKeyRange) bool {
iter := mem.newIter(nil)
rangeDelIter := mem.newRangeDelIter(nil)
rkeyIter := mem.newRangeKeyIter(nil)
closeIters := func() error {
err := iter.Close()
if rangeDelIter != nil {
err = firstError(err, rangeDelIter.Close())
}
if rkeyIter != nil {
err = firstError(err, rkeyIter.Close())
}
return err
}
for _, kr := range keyRanges {
if overlapWithIterator(iter, &rangeDelIter, rkeyIter, kr, cmp) {
closeIters()
return true
}
}
// Assume overlap if any iterator errored out.
return closeIters() != nil
}
func ingestUpdateSeqNum(
cmp Compare, format base.FormatKey, seqNum uint64, loadResult ingestLoadResult,
) error {
setSeqFn := func(k base.InternalKey) base.InternalKey {
return base.MakeInternalKey(k.UserKey, seqNum, k.Kind())
}
updateMetadata := func(m *fileMetadata) error {
// 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
// Ensure the new bounds are consistent.
if err := m.Validate(cmp, format); err != nil {
return err
}
seqNum++
return nil
}
// 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.sharedMeta) - 1; i >= 0; i-- {
if i-1 >= 0 && loadResult.sharedLevels[i-1] > loadResult.sharedLevels[i] {
panic(errors.AssertionFailedf("shared files %s, %s out of order", loadResult.sharedMeta[i-1], loadResult.sharedMeta[i]))
}
if err := updateMetadata(loadResult.sharedMeta[i]); err != nil {
return err
}
}
for i := range loadResult.localMeta {
if err := updateMetadata(loadResult.localMeta[i]); err != nil {
return err
}
}
for i := range loadResult.externalMeta {
if err := updateMetadata(loadResult.externalMeta[i]); err != nil {
return err
}
}
return nil
}
// Denotes an internal key range. Smallest and largest are both inclusive.
type internalKeyRange struct {
smallest, largest InternalKey
}
func overlapWithIterator(
iter internalIterator,
rangeDelIter *keyspan.FragmentIterator,
rkeyIter keyspan.FragmentIterator,
keyRange internalKeyRange,
cmp Compare,
) bool {
// Check overlap with point operations.
//
// When using levelIter, it seeks to the SST whose boundaries
// contain keyRange.smallest.UserKey(S).
// It then tries to find a point in that SST that is >= S.
// If there's no such point it means the SST ends in a tombstone in which case
// levelIter.SeekGE generates a boundary range del sentinel.
// The comparison of this boundary with keyRange.largest(L) below
// is subtle but maintains correctness.
// 1) boundary < L,
// since boundary is also > S (initial seek),
// whatever the boundary's start key may be, we're always overlapping.
// 2) boundary > L,
// overlap with boundary cannot be determined since we don't know boundary's start key.
// We require checking for overlap with rangeDelIter.
// 3) boundary == L and L is not sentinel,
// means boundary < L and hence is similar to 1).
// 4) boundary == L and L is sentinel,
// we'll always overlap since for any values of i,j ranges [i, k) and [j, k) always overlap.
key, _ := iter.SeekGE(keyRange.smallest.UserKey, base.SeekGEFlagsNone)
if key != nil {
c := sstableKeyCompare(cmp, *key, keyRange.largest)
if c <= 0 {
return true
}
}
// Assume overlap if iterator errored.
if err := iter.Error(); err != nil {
return true
}
computeOverlapWithSpans := func(rIter keyspan.FragmentIterator) bool {
// NB: The spans surfaced by the fragment iterator are non-overlapping.
span := rIter.SeekLT(keyRange.smallest.UserKey)
if span == nil {
span = rIter.Next()
}
for ; span != nil; span = rIter.Next() {
if span.Empty() {
continue
}
key := span.SmallestKey()
c := sstableKeyCompare(cmp, key, keyRange.largest)
if c > 0 {
// The start of the span is after the largest key in the
// ingested table.
return false
}
if cmp(span.End, keyRange.smallest.UserKey) > 0 {
// The end of the span is greater than the smallest in the
// table. Note that the span end key is exclusive, thus ">0"
// instead of ">=0".
return true
}
}
// Assume overlap if iterator errored.
if err := rIter.Error(); err != nil {
return true
}
return false
}
// rkeyIter is either a range key level iter, or a range key iterator
// over a single file.
if rkeyIter != nil {
if computeOverlapWithSpans(rkeyIter) {
return true
}
}
// Check overlap with range deletions.
if rangeDelIter == nil || *rangeDelIter == nil {
return false
}
return computeOverlapWithSpans(*rangeDelIter)
}
// 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(
newIters tableNewIters,
newRangeKeyIter keyspan.TableNewSpanIter,
iterOps IterOptions,
comparer *Comparer,
v *version,
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".
// This assertion implicitly checks that we have the current version of
// the metadata.
if v.L0Sublevels == nil {
return 0, nil, errors.AssertionFailedf("could not read L0 sublevels")
}
// Check for overlap over the keys of L0 by iterating over the sublevels.
for subLevel := 0; subLevel < len(v.L0SublevelFiles); subLevel++ {
iter := newLevelIter(iterOps, comparer, newIters,
v.L0Sublevels.Levels[subLevel].Iter(), manifest.Level(0), internalIterOpts{})
var rangeDelIter keyspan.FragmentIterator
// Pass in a non-nil pointer to rangeDelIter so that levelIter.findFileGE
// sets it up for the target file.
iter.initRangeDel(&rangeDelIter)
levelIter := keyspan.LevelIter{}
levelIter.Init(
keyspan.SpanIterOptions{}, comparer.Compare, newRangeKeyIter,
v.L0Sublevels.Levels[subLevel].Iter(), manifest.Level(0), manifest.KeyTypeRange,
)
kr := internalKeyRange{
smallest: meta.Smallest,
largest: meta.Largest,
}
overlap := overlapWithIterator(iter, &rangeDelIter, &levelIter, kr, comparer.Compare)
err := iter.Close() // Closes range del iter as well.
err = firstError(err, levelIter.Close())
if err != nil {
return 0, nil, err
}
if overlap {
return targetLevel, nil, nil
}
}
level := baseLevel
for ; level < numLevels; level++ {
levelIter := newLevelIter(iterOps, comparer, newIters,
v.Levels[level].Iter(), manifest.Level(level), internalIterOpts{})
var rangeDelIter keyspan.FragmentIterator
// Pass in a non-nil pointer to rangeDelIter so that levelIter.findFileGE
// sets it up for the target file.
levelIter.initRangeDel(&rangeDelIter)
rkeyLevelIter := &keyspan.LevelIter{}
rkeyLevelIter.Init(
keyspan.SpanIterOptions{}, comparer.Compare, newRangeKeyIter,
v.Levels[level].Iter(), manifest.Level(level), manifest.KeyTypeRange,
)
kr := internalKeyRange{
smallest: meta.Smallest,
largest: meta.Largest,
}
overlap := overlapWithIterator(levelIter, &rangeDelIter, rkeyLevelIter, kr, comparer.Compare)
err := levelIter.Close() // Closes range del iter as well.
err = firstError(err, rkeyLevelIter.Close())
if err != nil {
return 0, nil, err
}
if overlap {
return targetLevel, splitFile, nil
}
// Check boundary overlap.
var candidateSplitFile *fileMetadata
boundaryOverlaps := v.Overlaps(level, comparer.Compare, meta.Smallest.UserKey,
meta.Largest.UserKey, meta.Largest.IsExclusiveSentinel())
if !boundaryOverlaps.Empty() {
// We are already guaranteed to not have any data overlaps with files
// in boundaryOverlaps, otherwise we'd have returned in the above if
// statements. Use this, plus boundaryOverlaps.Len() == 1 to detect for
// the case where we can slot this file into the current level despite
// a boundary overlap, by splitting one existing file into two virtual
// sstables.
if suggestSplit && boundaryOverlaps.Len() == 1 {
iter := boundaryOverlaps.Iter()
candidateSplitFile = iter.First()
} else {
// We either don't want to suggest ingest-time splits (i.e.
// !suggestSplit), or we boundary-overlapped with more than one file.
continue
}
}
// 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 comparer.Compare(meta.Smallest.UserKey, c.largest.UserKey) <= 0 &&
comparer.Compare(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