Line data Source code
1 : // Copyright 2018 The LevelDB-Go and Pebble Authors. All rights reserved. Use
2 : // of this source code is governed by a BSD-style license that can be found in
3 : // the LICENSE file.
4 :
5 : package pebble
6 :
7 : import (
8 : "context"
9 : "fmt"
10 : "slices"
11 : "sort"
12 : "time"
13 :
14 : "github.com/cockroachdb/errors"
15 : "github.com/cockroachdb/pebble/internal/base"
16 : "github.com/cockroachdb/pebble/internal/cache"
17 : "github.com/cockroachdb/pebble/internal/invariants"
18 : "github.com/cockroachdb/pebble/internal/manifest"
19 : "github.com/cockroachdb/pebble/internal/overlap"
20 : "github.com/cockroachdb/pebble/internal/sstableinternal"
21 : "github.com/cockroachdb/pebble/objstorage"
22 : "github.com/cockroachdb/pebble/objstorage/remote"
23 : "github.com/cockroachdb/pebble/sstable"
24 : )
25 :
26 2 : func sstableKeyCompare(userCmp Compare, a, b InternalKey) int {
27 2 : c := userCmp(a.UserKey, b.UserKey)
28 2 : if c != 0 {
29 2 : return c
30 2 : }
31 2 : if a.IsExclusiveSentinel() {
32 2 : if !b.IsExclusiveSentinel() {
33 2 : return -1
34 2 : }
35 2 : } else if b.IsExclusiveSentinel() {
36 2 : return +1
37 2 : }
38 2 : return 0
39 : }
40 :
41 : // KeyRange encodes a key range in user key space. A KeyRange's Start is
42 : // inclusive while its End is exclusive.
43 : //
44 : // KeyRange is equivalent to base.UserKeyBounds with exclusive end.
45 : type KeyRange struct {
46 : Start, End []byte
47 : }
48 :
49 : // Valid returns true if the KeyRange is defined.
50 2 : func (k *KeyRange) Valid() bool {
51 2 : return k.Start != nil && k.End != nil
52 2 : }
53 :
54 : // Contains returns whether the specified key exists in the KeyRange.
55 2 : func (k *KeyRange) Contains(cmp base.Compare, key InternalKey) bool {
56 2 : v := cmp(key.UserKey, k.End)
57 2 : return (v < 0 || (v == 0 && key.IsExclusiveSentinel())) && cmp(k.Start, key.UserKey) <= 0
58 2 : }
59 :
60 : // UserKeyBounds returns the KeyRange as UserKeyBounds. Also implements the internal `bounded` interface.
61 2 : func (k KeyRange) UserKeyBounds() base.UserKeyBounds {
62 2 : return base.UserKeyBoundsEndExclusive(k.Start, k.End)
63 2 : }
64 :
65 : // OverlapsInternalKeyRange checks if the specified internal key range has an
66 : // overlap with the KeyRange. Note that we aren't checking for full containment
67 : // of smallest-largest within k, rather just that there's some intersection
68 : // between the two ranges.
69 2 : func (k *KeyRange) OverlapsInternalKeyRange(cmp base.Compare, smallest, largest InternalKey) bool {
70 2 : ukb := k.UserKeyBounds()
71 2 : b := base.UserKeyBoundsFromInternal(smallest, largest)
72 2 : return ukb.Overlaps(cmp, &b)
73 2 : }
74 :
75 : // Overlaps checks if the specified file has an overlap with the KeyRange.
76 : // Note that we aren't checking for full containment of m within k, rather just
77 : // that there's some intersection between m and k's bounds.
78 1 : func (k *KeyRange) Overlaps(cmp base.Compare, m *fileMetadata) bool {
79 1 : b := k.UserKeyBounds()
80 1 : return m.Overlaps(cmp, &b)
81 1 : }
82 :
83 : // OverlapsKeyRange checks if this span overlaps with the provided KeyRange.
84 : // Note that we aren't checking for full containment of either span in the other,
85 : // just that there's a key x that is in both key ranges.
86 2 : func (k *KeyRange) OverlapsKeyRange(cmp Compare, span KeyRange) bool {
87 2 : return cmp(k.Start, span.End) < 0 && cmp(k.End, span.Start) > 0
88 2 : }
89 :
90 2 : func ingestValidateKey(opts *Options, key *InternalKey) error {
91 2 : if key.Kind() == InternalKeyKindInvalid {
92 1 : return base.CorruptionErrorf("pebble: external sstable has corrupted key: %s",
93 1 : key.Pretty(opts.Comparer.FormatKey))
94 1 : }
95 2 : if key.SeqNum() != 0 {
96 1 : return base.CorruptionErrorf("pebble: external sstable has non-zero seqnum: %s",
97 1 : key.Pretty(opts.Comparer.FormatKey))
98 1 : }
99 2 : return nil
100 : }
101 :
102 : // ingestSynthesizeShared constructs a fileMetadata for one shared sstable owned
103 : // or shared by another node.
104 : func ingestSynthesizeShared(
105 : opts *Options, sm SharedSSTMeta, fileNum base.FileNum,
106 2 : ) (*fileMetadata, error) {
107 2 : if sm.Size == 0 {
108 0 : // Disallow 0 file sizes
109 0 : return nil, errors.New("pebble: cannot ingest shared file with size 0")
110 0 : }
111 : // Don't load table stats. Doing a round trip to shared storage, one SST
112 : // at a time is not worth it as it slows down ingestion.
113 2 : meta := &fileMetadata{
114 2 : FileNum: fileNum,
115 2 : CreationTime: time.Now().Unix(),
116 2 : Virtual: true,
117 2 : Size: sm.Size,
118 2 : }
119 2 : // For simplicity, we use the same number for both the FileNum and the
120 2 : // DiskFileNum (even though this is a virtual sstable). Pass the underlying
121 2 : // FileBacking's size to the same size as the virtualized view of the sstable.
122 2 : // This ensures that we don't over-prioritize this sstable for compaction just
123 2 : // yet, as we do not have a clear sense of what parts of this sstable are
124 2 : // referenced by other nodes.
125 2 : meta.InitProviderBacking(base.DiskFileNum(fileNum), sm.Size)
126 2 :
127 2 : if sm.LargestPointKey.Valid() && sm.LargestPointKey.UserKey != nil {
128 2 : // Initialize meta.{HasPointKeys,Smallest,Largest}, etc.
129 2 : //
130 2 : // NB: We create new internal keys and pass them into ExtendPointKeyBounds
131 2 : // so that we can sub a zero sequence number into the bounds. We can set
132 2 : // the sequence number to anything here; it'll be reset in ingestUpdateSeqNum
133 2 : // anyway. However, we do need to use the same sequence number across all
134 2 : // bound keys at this step so that we end up with bounds that are consistent
135 2 : // across point/range keys.
136 2 : //
137 2 : // Because of the sequence number rewriting, we cannot use the Kind of
138 2 : // sm.SmallestPointKey. For example, the original SST might start with
139 2 : // a.SET.2 and a.RANGEDEL.1 (with a.SET.2 being the smallest key); after
140 2 : // rewriting the sequence numbers, these keys become a.SET.100 and
141 2 : // a.RANGEDEL.100, with a.RANGEDEL.100 being the smallest key. To create a
142 2 : // correct bound, we just use the maximum key kind (which sorts first).
143 2 : // Similarly, we use the smallest key kind for the largest key.
144 2 : smallestPointKey := base.MakeInternalKey(sm.SmallestPointKey.UserKey, 0, base.InternalKeyKindMaxForSSTable)
145 2 : largestPointKey := base.MakeInternalKey(sm.LargestPointKey.UserKey, 0, 0)
146 2 : if sm.LargestPointKey.IsExclusiveSentinel() {
147 2 : largestPointKey = base.MakeRangeDeleteSentinelKey(sm.LargestPointKey.UserKey)
148 2 : }
149 2 : if opts.Comparer.Equal(smallestPointKey.UserKey, largestPointKey.UserKey) &&
150 2 : smallestPointKey.Trailer < largestPointKey.Trailer {
151 0 : // We get kinds from the sender, however we substitute our own sequence
152 0 : // numbers. This can result in cases where an sstable [b#5,SET-b#4,DELSIZED]
153 0 : // becomes [b#0,SET-b#0,DELSIZED] when we synthesize it here, but the
154 0 : // kinds need to be reversed now because DelSized > Set.
155 0 : smallestPointKey, largestPointKey = largestPointKey, smallestPointKey
156 0 : }
157 2 : meta.ExtendPointKeyBounds(opts.Comparer.Compare, smallestPointKey, largestPointKey)
158 : }
159 2 : if sm.LargestRangeKey.Valid() && sm.LargestRangeKey.UserKey != nil {
160 2 : // Initialize meta.{HasRangeKeys,Smallest,Largest}, etc.
161 2 : //
162 2 : // See comment above on why we use a zero sequence number and these key
163 2 : // kinds here.
164 2 : smallestRangeKey := base.MakeInternalKey(sm.SmallestRangeKey.UserKey, 0, base.InternalKeyKindRangeKeyMax)
165 2 : largestRangeKey := base.MakeExclusiveSentinelKey(base.InternalKeyKindRangeKeyMin, sm.LargestRangeKey.UserKey)
166 2 : meta.ExtendRangeKeyBounds(opts.Comparer.Compare, smallestRangeKey, largestRangeKey)
167 2 : }
168 2 : if err := meta.Validate(opts.Comparer.Compare, opts.Comparer.FormatKey); err != nil {
169 0 : return nil, err
170 0 : }
171 2 : return meta, nil
172 : }
173 :
174 : // ingestLoad1External loads the fileMetadata for one external sstable.
175 : // Sequence number and target level calculation happens during prepare/apply.
176 : func ingestLoad1External(
177 : opts *Options, e ExternalFile, fileNum base.FileNum,
178 2 : ) (*fileMetadata, error) {
179 2 : if e.Size == 0 {
180 0 : return nil, errors.New("pebble: cannot ingest external file with size 0")
181 0 : }
182 2 : if !e.HasRangeKey && !e.HasPointKey {
183 0 : return nil, errors.New("pebble: cannot ingest external file with no point or range keys")
184 0 : }
185 :
186 2 : if opts.Comparer.Compare(e.StartKey, e.EndKey) > 0 {
187 1 : return nil, errors.Newf("pebble: external file bounds [%q, %q) are invalid", e.StartKey, e.EndKey)
188 1 : }
189 2 : if opts.Comparer.Compare(e.StartKey, e.EndKey) == 0 && !e.EndKeyIsInclusive {
190 0 : return nil, errors.Newf("pebble: external file bounds [%q, %q) are invalid", e.StartKey, e.EndKey)
191 0 : }
192 2 : if n := opts.Comparer.Split(e.StartKey); n != len(e.StartKey) {
193 1 : return nil, errors.Newf("pebble: external file bounds start key %q has suffix", e.StartKey)
194 1 : }
195 2 : if n := opts.Comparer.Split(e.EndKey); n != len(e.EndKey) {
196 1 : return nil, errors.Newf("pebble: external file bounds end key %q has suffix", e.EndKey)
197 1 : }
198 :
199 : // Don't load table stats. Doing a round trip to shared storage, one SST
200 : // at a time is not worth it as it slows down ingestion.
201 2 : meta := &fileMetadata{
202 2 : FileNum: fileNum,
203 2 : CreationTime: time.Now().Unix(),
204 2 : Virtual: true,
205 2 : Size: e.Size,
206 2 : }
207 2 :
208 2 : // In the name of keeping this ingestion as fast as possible, we avoid
209 2 : // *all* existence checks and synthesize a file metadata with smallest/largest
210 2 : // keys that overlap whatever the passed-in span was.
211 2 : smallestCopy := slices.Clone(e.StartKey)
212 2 : largestCopy := slices.Clone(e.EndKey)
213 2 : if e.HasPointKey {
214 2 : // Sequence numbers are updated later by
215 2 : // ingestUpdateSeqNum, applying a squence number that
216 2 : // is applied to all keys in the sstable.
217 2 : if e.EndKeyIsInclusive {
218 1 : meta.ExtendPointKeyBounds(
219 1 : opts.Comparer.Compare,
220 1 : base.MakeInternalKey(smallestCopy, 0, base.InternalKeyKindMaxForSSTable),
221 1 : base.MakeInternalKey(largestCopy, 0, 0))
222 2 : } else {
223 2 : meta.ExtendPointKeyBounds(
224 2 : opts.Comparer.Compare,
225 2 : base.MakeInternalKey(smallestCopy, 0, base.InternalKeyKindMaxForSSTable),
226 2 : base.MakeRangeDeleteSentinelKey(largestCopy))
227 2 : }
228 : }
229 2 : if e.HasRangeKey {
230 2 : meta.ExtendRangeKeyBounds(
231 2 : opts.Comparer.Compare,
232 2 : base.MakeInternalKey(smallestCopy, 0, InternalKeyKindRangeKeyMax),
233 2 : base.MakeExclusiveSentinelKey(InternalKeyKindRangeKeyMin, largestCopy),
234 2 : )
235 2 : }
236 :
237 2 : meta.SyntheticPrefix = e.SyntheticPrefix
238 2 : meta.SyntheticSuffix = e.SyntheticSuffix
239 2 :
240 2 : return meta, nil
241 : }
242 :
243 : // ingestLoad1 creates the FileMetadata for one file. This file will be owned
244 : // by this store.
245 : func ingestLoad1(
246 : ctx context.Context,
247 : opts *Options,
248 : fmv FormatMajorVersion,
249 : readable objstorage.Readable,
250 : cacheID cache.ID,
251 : fileNum base.FileNum,
252 2 : ) (*fileMetadata, error) {
253 2 : o := opts.MakeReaderOptions()
254 2 : o.SetInternalCacheOpts(sstableinternal.CacheOptions{
255 2 : Cache: opts.Cache,
256 2 : CacheID: cacheID,
257 2 : FileNum: base.PhysicalTableDiskFileNum(fileNum),
258 2 : })
259 2 : r, err := sstable.NewReader(ctx, readable, o)
260 2 : if err != nil {
261 1 : return nil, err
262 1 : }
263 2 : defer r.Close()
264 2 :
265 2 : // Avoid ingesting tables with format versions this DB doesn't support.
266 2 : tf, err := r.TableFormat()
267 2 : if err != nil {
268 0 : return nil, err
269 0 : }
270 2 : if tf < fmv.MinTableFormat() || tf > fmv.MaxTableFormat() {
271 1 : return nil, errors.Newf(
272 1 : "pebble: table format %s is not within range supported at DB format major version %d, (%s,%s)",
273 1 : tf, fmv, fmv.MinTableFormat(), fmv.MaxTableFormat(),
274 1 : )
275 1 : }
276 :
277 2 : meta := &fileMetadata{}
278 2 : meta.FileNum = fileNum
279 2 : meta.Size = uint64(readable.Size())
280 2 : meta.CreationTime = time.Now().Unix()
281 2 : meta.InitPhysicalBacking()
282 2 :
283 2 : // Avoid loading into the table cache for collecting stats if we
284 2 : // don't need to. If there are no range deletions, we have all the
285 2 : // information to compute the stats here.
286 2 : //
287 2 : // This is helpful in tests for avoiding awkwardness around deletion of
288 2 : // ingested files from MemFS. MemFS implements the Windows semantics of
289 2 : // disallowing removal of an open file. Under MemFS, if we don't populate
290 2 : // meta.Stats here, the file will be loaded into the table cache for
291 2 : // calculating stats before we can remove the original link.
292 2 : maybeSetStatsFromProperties(meta.PhysicalMeta(), &r.Properties)
293 2 :
294 2 : {
295 2 : iter, err := r.NewIter(sstable.NoTransforms, nil /* lower */, nil /* upper */)
296 2 : if err != nil {
297 1 : return nil, err
298 1 : }
299 2 : defer iter.Close()
300 2 : var smallest InternalKey
301 2 : if kv := iter.First(); kv != nil {
302 2 : if err := ingestValidateKey(opts, &kv.K); err != nil {
303 1 : return nil, err
304 1 : }
305 2 : smallest = kv.K.Clone()
306 : }
307 2 : if err := iter.Error(); err != nil {
308 1 : return nil, err
309 1 : }
310 2 : if kv := iter.Last(); kv != nil {
311 2 : if err := ingestValidateKey(opts, &kv.K); err != nil {
312 0 : return nil, err
313 0 : }
314 2 : meta.ExtendPointKeyBounds(opts.Comparer.Compare, smallest, kv.K.Clone())
315 : }
316 2 : if err := iter.Error(); err != nil {
317 1 : return nil, err
318 1 : }
319 : }
320 :
321 2 : iter, err := r.NewRawRangeDelIter(ctx, sstable.NoFragmentTransforms)
322 2 : if err != nil {
323 0 : return nil, err
324 0 : }
325 2 : if iter != nil {
326 2 : defer iter.Close()
327 2 : var smallest InternalKey
328 2 : if s, err := iter.First(); err != nil {
329 0 : return nil, err
330 2 : } else if s != nil {
331 2 : key := s.SmallestKey()
332 2 : if err := ingestValidateKey(opts, &key); err != nil {
333 0 : return nil, err
334 0 : }
335 2 : smallest = key.Clone()
336 : }
337 2 : if s, err := iter.Last(); err != nil {
338 0 : return nil, err
339 2 : } else if s != nil {
340 2 : k := s.SmallestKey()
341 2 : if err := ingestValidateKey(opts, &k); err != nil {
342 0 : return nil, err
343 0 : }
344 2 : largest := s.LargestKey().Clone()
345 2 : meta.ExtendPointKeyBounds(opts.Comparer.Compare, smallest, largest)
346 : }
347 : }
348 :
349 : // Update the range-key bounds for the table.
350 2 : {
351 2 : iter, err := r.NewRawRangeKeyIter(ctx, sstable.NoFragmentTransforms)
352 2 : if err != nil {
353 0 : return nil, err
354 0 : }
355 2 : if iter != nil {
356 2 : defer iter.Close()
357 2 : var smallest InternalKey
358 2 : if s, err := iter.First(); err != nil {
359 0 : return nil, err
360 2 : } else if s != nil {
361 2 : key := s.SmallestKey()
362 2 : if err := ingestValidateKey(opts, &key); err != nil {
363 0 : return nil, err
364 0 : }
365 2 : smallest = key.Clone()
366 : }
367 2 : if s, err := iter.Last(); err != nil {
368 0 : return nil, err
369 2 : } else if s != nil {
370 2 : k := s.SmallestKey()
371 2 : if err := ingestValidateKey(opts, &k); err != nil {
372 0 : return nil, err
373 0 : }
374 : // As range keys are fragmented, the end key of the last range key in
375 : // the table provides the upper bound for the table.
376 2 : largest := s.LargestKey().Clone()
377 2 : meta.ExtendRangeKeyBounds(opts.Comparer.Compare, smallest, largest)
378 : }
379 : }
380 : }
381 :
382 2 : if !meta.HasPointKeys && !meta.HasRangeKeys {
383 2 : return nil, nil
384 2 : }
385 :
386 : // Sanity check that the various bounds on the file were set consistently.
387 2 : if err := meta.Validate(opts.Comparer.Compare, opts.Comparer.FormatKey); err != nil {
388 0 : return nil, err
389 0 : }
390 :
391 2 : return meta, nil
392 : }
393 :
394 : type ingestLoadResult struct {
395 : local []ingestLocalMeta
396 : shared []ingestSharedMeta
397 : external []ingestExternalMeta
398 :
399 : externalFilesHaveLevel bool
400 : }
401 :
402 : type ingestLocalMeta struct {
403 : *fileMetadata
404 : path string
405 : }
406 :
407 : type ingestSharedMeta struct {
408 : *fileMetadata
409 : shared SharedSSTMeta
410 : }
411 :
412 : type ingestExternalMeta struct {
413 : *fileMetadata
414 : external ExternalFile
415 : // usedExistingBacking is true if the external file is reusing a backing
416 : // that existed before this ingestion. In this case, we called
417 : // VirtualBackings.Protect() on that backing; we will need to call
418 : // Unprotect() after the ingestion.
419 : usedExistingBacking bool
420 : }
421 :
422 2 : func (r *ingestLoadResult) fileCount() int {
423 2 : return len(r.local) + len(r.shared) + len(r.external)
424 2 : }
425 :
426 : func ingestLoad(
427 : ctx context.Context,
428 : opts *Options,
429 : fmv FormatMajorVersion,
430 : paths []string,
431 : shared []SharedSSTMeta,
432 : external []ExternalFile,
433 : cacheID cache.ID,
434 : pending []base.FileNum,
435 2 : ) (ingestLoadResult, error) {
436 2 : localFileNums := pending[:len(paths)]
437 2 : sharedFileNums := pending[len(paths) : len(paths)+len(shared)]
438 2 : externalFileNums := pending[len(paths)+len(shared) : len(paths)+len(shared)+len(external)]
439 2 :
440 2 : var result ingestLoadResult
441 2 : result.local = make([]ingestLocalMeta, 0, len(paths))
442 2 : for i := range paths {
443 2 : f, err := opts.FS.Open(paths[i])
444 2 : if err != nil {
445 1 : return ingestLoadResult{}, err
446 1 : }
447 :
448 2 : readable, err := sstable.NewSimpleReadable(f)
449 2 : if err != nil {
450 1 : return ingestLoadResult{}, err
451 1 : }
452 2 : m, err := ingestLoad1(ctx, opts, fmv, readable, cacheID, localFileNums[i])
453 2 : if err != nil {
454 1 : return ingestLoadResult{}, err
455 1 : }
456 2 : if m != nil {
457 2 : result.local = append(result.local, ingestLocalMeta{
458 2 : fileMetadata: m,
459 2 : path: paths[i],
460 2 : })
461 2 : }
462 : }
463 :
464 : // Sort the shared files according to level.
465 2 : sort.Sort(sharedByLevel(shared))
466 2 :
467 2 : result.shared = make([]ingestSharedMeta, 0, len(shared))
468 2 : for i := range shared {
469 2 : m, err := ingestSynthesizeShared(opts, shared[i], sharedFileNums[i])
470 2 : if err != nil {
471 0 : return ingestLoadResult{}, err
472 0 : }
473 2 : if shared[i].Level < sharedLevelsStart {
474 0 : return ingestLoadResult{}, errors.New("cannot ingest shared file in level below sharedLevelsStart")
475 0 : }
476 2 : result.shared = append(result.shared, ingestSharedMeta{
477 2 : fileMetadata: m,
478 2 : shared: shared[i],
479 2 : })
480 : }
481 2 : result.external = make([]ingestExternalMeta, 0, len(external))
482 2 : for i := range external {
483 2 : m, err := ingestLoad1External(opts, external[i], externalFileNums[i])
484 2 : if err != nil {
485 1 : return ingestLoadResult{}, err
486 1 : }
487 2 : result.external = append(result.external, ingestExternalMeta{
488 2 : fileMetadata: m,
489 2 : external: external[i],
490 2 : })
491 2 : if external[i].Level > 0 {
492 1 : if i != 0 && !result.externalFilesHaveLevel {
493 0 : return ingestLoadResult{}, base.AssertionFailedf("pebble: external sstables must all have level set or unset")
494 0 : }
495 1 : result.externalFilesHaveLevel = true
496 2 : } else if result.externalFilesHaveLevel {
497 0 : return ingestLoadResult{}, base.AssertionFailedf("pebble: external sstables must all have level set or unset")
498 0 : }
499 : }
500 2 : return result, nil
501 : }
502 :
503 2 : func ingestSortAndVerify(cmp Compare, lr ingestLoadResult, exciseSpan KeyRange) error {
504 2 : // Verify that all the shared files (i.e. files in sharedMeta)
505 2 : // fit within the exciseSpan.
506 2 : for _, f := range lr.shared {
507 2 : if !exciseSpan.Contains(cmp, f.Smallest) || !exciseSpan.Contains(cmp, f.Largest) {
508 0 : return errors.Newf("pebble: shared file outside of excise span, span [%s-%s), file = %s", exciseSpan.Start, exciseSpan.End, f.String())
509 0 : }
510 : }
511 :
512 2 : if lr.externalFilesHaveLevel {
513 1 : for _, f := range lr.external {
514 1 : if !exciseSpan.Contains(cmp, f.Smallest) || !exciseSpan.Contains(cmp, f.Largest) {
515 0 : return base.AssertionFailedf("pebble: external file outside of excise span, span [%s-%s), file = %s", exciseSpan.Start, exciseSpan.End, f.String())
516 0 : }
517 : }
518 : }
519 :
520 2 : if len(lr.external) > 0 {
521 2 : if len(lr.shared) > 0 {
522 0 : // If external files are present alongside shared files,
523 0 : // return an error.
524 0 : return base.AssertionFailedf("pebble: external files cannot be ingested atomically alongside shared files")
525 0 : }
526 :
527 : // Sort according to the smallest key.
528 2 : slices.SortFunc(lr.external, func(a, b ingestExternalMeta) int {
529 2 : return cmp(a.Smallest.UserKey, b.Smallest.UserKey)
530 2 : })
531 2 : for i := 1; i < len(lr.external); i++ {
532 2 : if sstableKeyCompare(cmp, lr.external[i-1].Largest, lr.external[i].Smallest) >= 0 {
533 1 : return errors.Newf("pebble: external sstables have overlapping ranges")
534 1 : }
535 : }
536 2 : return nil
537 : }
538 2 : if len(lr.local) <= 1 {
539 2 : return nil
540 2 : }
541 :
542 : // Sort according to the smallest key.
543 2 : slices.SortFunc(lr.local, func(a, b ingestLocalMeta) int {
544 2 : return cmp(a.Smallest.UserKey, b.Smallest.UserKey)
545 2 : })
546 :
547 2 : for i := 1; i < len(lr.local); i++ {
548 2 : if sstableKeyCompare(cmp, lr.local[i-1].Largest, lr.local[i].Smallest) >= 0 {
549 2 : return errors.Newf("pebble: local ingestion sstables have overlapping ranges")
550 2 : }
551 : }
552 2 : if len(lr.shared) == 0 {
553 2 : return nil
554 2 : }
555 0 : filesInLevel := make([]*fileMetadata, 0, len(lr.shared))
556 0 : for l := sharedLevelsStart; l < numLevels; l++ {
557 0 : filesInLevel = filesInLevel[:0]
558 0 : for i := range lr.shared {
559 0 : if lr.shared[i].shared.Level == uint8(l) {
560 0 : filesInLevel = append(filesInLevel, lr.shared[i].fileMetadata)
561 0 : }
562 : }
563 0 : for i := range lr.external {
564 0 : if lr.external[i].external.Level == uint8(l) {
565 0 : filesInLevel = append(filesInLevel, lr.external[i].fileMetadata)
566 0 : }
567 : }
568 0 : slices.SortFunc(filesInLevel, func(a, b *fileMetadata) int {
569 0 : return cmp(a.Smallest.UserKey, b.Smallest.UserKey)
570 0 : })
571 0 : for i := 1; i < len(filesInLevel); i++ {
572 0 : if sstableKeyCompare(cmp, filesInLevel[i-1].Largest, filesInLevel[i].Smallest) >= 0 {
573 0 : return base.AssertionFailedf("pebble: external shared sstables have overlapping ranges")
574 0 : }
575 : }
576 : }
577 0 : return nil
578 : }
579 :
580 1 : func ingestCleanup(objProvider objstorage.Provider, meta []ingestLocalMeta) error {
581 1 : var firstErr error
582 1 : for i := range meta {
583 1 : if err := objProvider.Remove(fileTypeTable, meta[i].FileBacking.DiskFileNum); err != nil {
584 1 : firstErr = firstError(firstErr, err)
585 1 : }
586 : }
587 1 : return firstErr
588 : }
589 :
590 : // ingestLinkLocal creates new objects which are backed by either hardlinks to or
591 : // copies of the ingested files.
592 : func ingestLinkLocal(
593 : ctx context.Context,
594 : jobID JobID,
595 : opts *Options,
596 : objProvider objstorage.Provider,
597 : localMetas []ingestLocalMeta,
598 2 : ) error {
599 2 : for i := range localMetas {
600 2 : objMeta, err := objProvider.LinkOrCopyFromLocal(
601 2 : ctx, opts.FS, localMetas[i].path, fileTypeTable, localMetas[i].FileBacking.DiskFileNum,
602 2 : objstorage.CreateOptions{PreferSharedStorage: true},
603 2 : )
604 2 : if err != nil {
605 1 : if err2 := ingestCleanup(objProvider, localMetas[:i]); err2 != nil {
606 0 : opts.Logger.Errorf("ingest cleanup failed: %v", err2)
607 0 : }
608 1 : return err
609 : }
610 2 : if opts.EventListener.TableCreated != nil {
611 2 : opts.EventListener.TableCreated(TableCreateInfo{
612 2 : JobID: int(jobID),
613 2 : Reason: "ingesting",
614 2 : Path: objProvider.Path(objMeta),
615 2 : FileNum: base.PhysicalTableDiskFileNum(localMetas[i].FileNum),
616 2 : })
617 2 : }
618 : }
619 2 : return nil
620 : }
621 :
622 : // ingestAttachRemote attaches remote objects to the storage provider.
623 : //
624 : // For external objects, we reuse existing FileBackings from the current version
625 : // when possible.
626 : //
627 : // ingestUnprotectExternalBackings() must be called after this function (even in
628 : // error cases).
629 2 : func (d *DB) ingestAttachRemote(jobID JobID, lr ingestLoadResult) error {
630 2 : remoteObjs := make([]objstorage.RemoteObjectToAttach, 0, len(lr.shared)+len(lr.external))
631 2 : for i := range lr.shared {
632 2 : backing, err := lr.shared[i].shared.Backing.Get()
633 2 : if err != nil {
634 0 : return err
635 0 : }
636 2 : remoteObjs = append(remoteObjs, objstorage.RemoteObjectToAttach{
637 2 : FileNum: lr.shared[i].FileBacking.DiskFileNum,
638 2 : FileType: fileTypeTable,
639 2 : Backing: backing,
640 2 : })
641 : }
642 :
643 2 : d.findExistingBackingsForExternalObjects(lr.external)
644 2 :
645 2 : newFileBackings := make(map[remote.ObjectKey]*fileBacking, len(lr.external))
646 2 : for i := range lr.external {
647 2 : meta := lr.external[i].fileMetadata
648 2 : if meta.FileBacking != nil {
649 2 : // The backing was filled in by findExistingBackingsForExternalObjects().
650 2 : continue
651 : }
652 2 : key := remote.MakeObjectKey(lr.external[i].external.Locator, lr.external[i].external.ObjName)
653 2 : if backing, ok := newFileBackings[key]; ok {
654 2 : // We already created the same backing in this loop.
655 2 : meta.FileBacking = backing
656 2 : continue
657 : }
658 2 : providerBacking, err := d.objProvider.CreateExternalObjectBacking(key.Locator, key.ObjectName)
659 2 : if err != nil {
660 0 : return err
661 0 : }
662 : // We have to attach the remote object (and assign it a DiskFileNum). For
663 : // simplicity, we use the same number for both the FileNum and the
664 : // DiskFileNum (even though this is a virtual sstable).
665 2 : meta.InitProviderBacking(base.DiskFileNum(meta.FileNum), lr.external[i].external.Size)
666 2 :
667 2 : // Set the underlying FileBacking's size to the same size as the virtualized
668 2 : // view of the sstable. This ensures that we don't over-prioritize this
669 2 : // sstable for compaction just yet, as we do not have a clear sense of
670 2 : // what parts of this sstable are referenced by other nodes.
671 2 : meta.FileBacking.Size = lr.external[i].external.Size
672 2 : newFileBackings[key] = meta.FileBacking
673 2 :
674 2 : remoteObjs = append(remoteObjs, objstorage.RemoteObjectToAttach{
675 2 : FileNum: meta.FileBacking.DiskFileNum,
676 2 : FileType: fileTypeTable,
677 2 : Backing: providerBacking,
678 2 : })
679 : }
680 :
681 2 : for i := range lr.external {
682 2 : if err := lr.external[i].Validate(d.opts.Comparer.Compare, d.opts.Comparer.FormatKey); err != nil {
683 0 : return err
684 0 : }
685 : }
686 :
687 2 : remoteObjMetas, err := d.objProvider.AttachRemoteObjects(remoteObjs)
688 2 : if err != nil {
689 0 : return err
690 0 : }
691 :
692 2 : for i := range lr.shared {
693 2 : // One corner case around file sizes we need to be mindful of, is that
694 2 : // if one of the shareObjs was initially created by us (and has boomeranged
695 2 : // back from another node), we'll need to update the FileBacking's size
696 2 : // to be the true underlying size. Otherwise, we could hit errors when we
697 2 : // open the db again after a crash/restart (see checkConsistency in open.go),
698 2 : // plus it more accurately allows us to prioritize compactions of files
699 2 : // that were originally created by us.
700 2 : if remoteObjMetas[i].IsShared() && !d.objProvider.IsSharedForeign(remoteObjMetas[i]) {
701 2 : size, err := d.objProvider.Size(remoteObjMetas[i])
702 2 : if err != nil {
703 0 : return err
704 0 : }
705 2 : lr.shared[i].FileBacking.Size = uint64(size)
706 : }
707 : }
708 :
709 2 : if d.opts.EventListener.TableCreated != nil {
710 2 : for i := range remoteObjMetas {
711 2 : d.opts.EventListener.TableCreated(TableCreateInfo{
712 2 : JobID: int(jobID),
713 2 : Reason: "ingesting",
714 2 : Path: d.objProvider.Path(remoteObjMetas[i]),
715 2 : FileNum: remoteObjMetas[i].DiskFileNum,
716 2 : })
717 2 : }
718 : }
719 :
720 2 : return nil
721 : }
722 :
723 : // findExistingBackingsForExternalObjects populates the FileBacking for external
724 : // files which are already in use by the current version.
725 : //
726 : // We take a Ref and LatestRef on populated backings.
727 2 : func (d *DB) findExistingBackingsForExternalObjects(metas []ingestExternalMeta) {
728 2 : d.mu.Lock()
729 2 : defer d.mu.Unlock()
730 2 :
731 2 : for i := range metas {
732 2 : diskFileNums := d.objProvider.GetExternalObjects(metas[i].external.Locator, metas[i].external.ObjName)
733 2 : // We cross-check against fileBackings in the current version because it is
734 2 : // possible that the external object is referenced by an sstable which only
735 2 : // exists in a previous version. In that case, that object could be removed
736 2 : // at any time so we cannot reuse it.
737 2 : for _, n := range diskFileNums {
738 2 : if backing, ok := d.mu.versions.virtualBackings.Get(n); ok {
739 2 : // Protect this backing from being removed from the latest version. We
740 2 : // will unprotect in ingestUnprotectExternalBackings.
741 2 : d.mu.versions.virtualBackings.Protect(n)
742 2 : metas[i].usedExistingBacking = true
743 2 : metas[i].FileBacking = backing
744 2 : break
745 : }
746 : }
747 : }
748 : }
749 :
750 : // ingestUnprotectExternalBackings unprotects the file backings that were reused
751 : // for external objects when the ingestion fails.
752 2 : func (d *DB) ingestUnprotectExternalBackings(lr ingestLoadResult) {
753 2 : d.mu.Lock()
754 2 : defer d.mu.Unlock()
755 2 :
756 2 : for _, meta := range lr.external {
757 2 : if meta.usedExistingBacking {
758 2 : // If the backing is not use anywhere else and the ingest failed (or the
759 2 : // ingested tables were already compacted away), this call will cause in
760 2 : // the next version update to remove the backing.
761 2 : d.mu.versions.virtualBackings.Unprotect(meta.FileBacking.DiskFileNum)
762 2 : }
763 : }
764 : }
765 :
766 : func setSeqNumInMetadata(
767 : m *fileMetadata, seqNum base.SeqNum, cmp Compare, format base.FormatKey,
768 2 : ) error {
769 2 : setSeqFn := func(k base.InternalKey) base.InternalKey {
770 2 : return base.MakeInternalKey(k.UserKey, seqNum, k.Kind())
771 2 : }
772 : // NB: we set the fields directly here, rather than via their Extend*
773 : // methods, as we are updating sequence numbers.
774 2 : if m.HasPointKeys {
775 2 : m.SmallestPointKey = setSeqFn(m.SmallestPointKey)
776 2 : }
777 2 : if m.HasRangeKeys {
778 2 : m.SmallestRangeKey = setSeqFn(m.SmallestRangeKey)
779 2 : }
780 2 : m.Smallest = setSeqFn(m.Smallest)
781 2 : // Only update the seqnum for the largest key if that key is not an
782 2 : // "exclusive sentinel" (i.e. a range deletion sentinel or a range key
783 2 : // boundary), as doing so effectively drops the exclusive sentinel (by
784 2 : // lowering the seqnum from the max value), and extends the bounds of the
785 2 : // table.
786 2 : // NB: as the largest range key is always an exclusive sentinel, it is never
787 2 : // updated.
788 2 : if m.HasPointKeys && !m.LargestPointKey.IsExclusiveSentinel() {
789 2 : m.LargestPointKey = setSeqFn(m.LargestPointKey)
790 2 : }
791 2 : if !m.Largest.IsExclusiveSentinel() {
792 2 : m.Largest = setSeqFn(m.Largest)
793 2 : }
794 : // Setting smallestSeqNum == largestSeqNum triggers the setting of
795 : // Properties.GlobalSeqNum when an sstable is loaded.
796 2 : m.SmallestSeqNum = seqNum
797 2 : m.LargestSeqNum = seqNum
798 2 : m.LargestSeqNumAbsolute = seqNum
799 2 : // Ensure the new bounds are consistent.
800 2 : if err := m.Validate(cmp, format); err != nil {
801 0 : return err
802 0 : }
803 2 : return nil
804 : }
805 :
806 : func ingestUpdateSeqNum(
807 : cmp Compare, format base.FormatKey, seqNum base.SeqNum, loadResult ingestLoadResult,
808 2 : ) error {
809 2 : // Shared sstables are required to be sorted by level ascending. We then
810 2 : // iterate the shared sstables in reverse, assigning the lower sequence
811 2 : // numbers to the shared sstables that will be ingested into the lower
812 2 : // (larger numbered) levels first. This ensures sequence number shadowing is
813 2 : // correct.
814 2 : for i := len(loadResult.shared) - 1; i >= 0; i-- {
815 2 : if i-1 >= 0 && loadResult.shared[i-1].shared.Level > loadResult.shared[i].shared.Level {
816 0 : panic(errors.AssertionFailedf("shared files %s, %s out of order", loadResult.shared[i-1], loadResult.shared[i]))
817 : }
818 2 : if err := setSeqNumInMetadata(loadResult.shared[i].fileMetadata, seqNum, cmp, format); err != nil {
819 0 : return err
820 0 : }
821 2 : seqNum++
822 : }
823 2 : for i := range loadResult.external {
824 2 : if err := setSeqNumInMetadata(loadResult.external[i].fileMetadata, seqNum, cmp, format); err != nil {
825 0 : return err
826 0 : }
827 2 : seqNum++
828 : }
829 2 : for i := range loadResult.local {
830 2 : if err := setSeqNumInMetadata(loadResult.local[i].fileMetadata, seqNum, cmp, format); err != nil {
831 0 : return err
832 0 : }
833 2 : seqNum++
834 : }
835 2 : return nil
836 : }
837 :
838 : // ingestTargetLevel returns the target level for a file being ingested.
839 : // If suggestSplit is true, it accounts for ingest-time splitting as part of
840 : // its target level calculation, and if a split candidate is found, that file
841 : // is returned as the splitFile.
842 : func ingestTargetLevel(
843 : ctx context.Context,
844 : cmp base.Compare,
845 : lsmOverlap overlap.WithLSM,
846 : baseLevel int,
847 : compactions map[*compaction]struct{},
848 : meta *fileMetadata,
849 : suggestSplit bool,
850 2 : ) (targetLevel int, splitFile *fileMetadata, err error) {
851 2 : // Find the lowest level which does not have any files which overlap meta. We
852 2 : // search from L0 to L6 looking for whether there are any files in the level
853 2 : // which overlap meta. We want the "lowest" level (where lower means
854 2 : // increasing level number) in order to reduce write amplification.
855 2 : //
856 2 : // There are 2 kinds of overlap we need to check for: file boundary overlap
857 2 : // and data overlap. Data overlap implies file boundary overlap. Note that it
858 2 : // is always possible to ingest into L0.
859 2 : //
860 2 : // To place meta at level i where i > 0:
861 2 : // - there must not be any data overlap with levels <= i, since that will
862 2 : // violate the sequence number invariant.
863 2 : // - no file boundary overlap with level i, since that will violate the
864 2 : // invariant that files do not overlap in levels i > 0.
865 2 : // - if there is only a file overlap at a given level, and no data overlap,
866 2 : // we can still slot a file at that level. We return the fileMetadata with
867 2 : // which we have file boundary overlap (must be only one file, as sstable
868 2 : // bounds are usually tight on user keys) and the caller is expected to split
869 2 : // that sstable into two virtual sstables, allowing this file to go into that
870 2 : // level. Note that if we have file boundary overlap with two files, which
871 2 : // should only happen on rare occasions, we treat it as data overlap and
872 2 : // don't use this optimization.
873 2 : //
874 2 : // The file boundary overlap check is simpler to conceptualize. Consider the
875 2 : // following example, in which the ingested file lies completely before or
876 2 : // after the file being considered.
877 2 : //
878 2 : // |--| |--| ingested file: [a,b] or [f,g]
879 2 : // |-----| existing file: [c,e]
880 2 : // _____________________
881 2 : // a b c d e f g
882 2 : //
883 2 : // In both cases the ingested file can move to considering the next level.
884 2 : //
885 2 : // File boundary overlap does not necessarily imply data overlap. The check
886 2 : // for data overlap is a little more nuanced. Consider the following examples:
887 2 : //
888 2 : // 1. No data overlap:
889 2 : //
890 2 : // |-| |--| ingested file: [cc-d] or [ee-ff]
891 2 : // |*--*--*----*------*| existing file: [a-g], points: [a, b, c, dd, g]
892 2 : // _____________________
893 2 : // a b c d e f g
894 2 : //
895 2 : // In this case the ingested files can "fall through" this level. The checks
896 2 : // continue at the next level.
897 2 : //
898 2 : // 2. Data overlap:
899 2 : //
900 2 : // |--| ingested file: [d-e]
901 2 : // |*--*--*----*------*| existing file: [a-g], points: [a, b, c, dd, g]
902 2 : // _____________________
903 2 : // a b c d e f g
904 2 : //
905 2 : // In this case the file cannot be ingested into this level as the point 'dd'
906 2 : // is in the way.
907 2 : //
908 2 : // It is worth noting that the check for data overlap is only approximate. In
909 2 : // the previous example, the ingested table [d-e] could contain only the
910 2 : // points 'd' and 'e', in which case the table would be eligible for
911 2 : // considering lower levels. However, such a fine-grained check would need to
912 2 : // be exhaustive (comparing points and ranges in both the ingested existing
913 2 : // tables) and such a check is prohibitively expensive. Thus Pebble treats any
914 2 : // existing point that falls within the ingested table bounds as being "data
915 2 : // overlap".
916 2 :
917 2 : if lsmOverlap[0].Result == overlap.Data {
918 2 : return 0, nil, nil
919 2 : }
920 2 : targetLevel = 0
921 2 : splitFile = nil
922 2 : for level := baseLevel; level < numLevels; level++ {
923 2 : var candidateSplitFile *fileMetadata
924 2 : switch lsmOverlap[level].Result {
925 2 : case overlap.Data:
926 2 : // We cannot ingest into or under this level; return the best target level
927 2 : // so far.
928 2 : return targetLevel, splitFile, nil
929 :
930 2 : case overlap.OnlyBoundary:
931 2 : if !suggestSplit || lsmOverlap[level].SplitFile == nil {
932 2 : // We can ingest under this level, but not into this level.
933 2 : continue
934 : }
935 : // We can ingest into this level if we split this file.
936 2 : candidateSplitFile = lsmOverlap[level].SplitFile
937 :
938 2 : case overlap.None:
939 : // We can ingest into this level.
940 :
941 0 : default:
942 0 : return 0, nil, base.AssertionFailedf("unexpected WithLevel.Result: %v", lsmOverlap[level].Result)
943 : }
944 :
945 : // Check boundary overlap with any ongoing compactions. We consider an
946 : // overlapping compaction that's writing files to an output level as
947 : // equivalent to boundary overlap with files in that output level.
948 : //
949 : // We cannot check for data overlap with the new SSTs compaction will produce
950 : // since compaction hasn't been done yet. However, there's no need to check
951 : // since all keys in them will be from levels in [c.startLevel,
952 : // c.outputLevel], and all those levels have already had their data overlap
953 : // tested negative (else we'd have returned earlier).
954 : //
955 : // An alternative approach would be to cancel these compactions and proceed
956 : // with an ingest-time split on this level if necessary. However, compaction
957 : // cancellation can result in significant wasted effort and is best avoided
958 : // unless necessary.
959 2 : overlaps := false
960 2 : for c := range compactions {
961 2 : if c.outputLevel == nil || level != c.outputLevel.level {
962 2 : continue
963 : }
964 2 : if cmp(meta.Smallest.UserKey, c.largest.UserKey) <= 0 &&
965 2 : cmp(meta.Largest.UserKey, c.smallest.UserKey) >= 0 {
966 2 : overlaps = true
967 2 : break
968 : }
969 : }
970 2 : if !overlaps {
971 2 : targetLevel = level
972 2 : splitFile = candidateSplitFile
973 2 : }
974 : }
975 2 : return targetLevel, splitFile, nil
976 : }
977 :
978 : // Ingest ingests a set of sstables into the DB. Ingestion of the files is
979 : // atomic and semantically equivalent to creating a single batch containing all
980 : // of the mutations in the sstables. Ingestion may require the memtable to be
981 : // flushed. The ingested sstable files are moved into the DB and must reside on
982 : // the same filesystem as the DB. Sstables can be created for ingestion using
983 : // sstable.Writer. On success, Ingest removes the input paths.
984 : //
985 : // Two types of sstables are accepted for ingestion(s): one is sstables present
986 : // in the instance's vfs.FS and can be referenced locally. The other is sstables
987 : // present in remote.Storage, referred to as shared or foreign sstables. These
988 : // shared sstables can be linked through objstorageprovider.Provider, and do not
989 : // need to already be present on the local vfs.FS. Foreign sstables must all fit
990 : // in an excise span, and are destined for a level specified in SharedSSTMeta.
991 : //
992 : // All sstables *must* be Sync()'d by the caller after all bytes are written
993 : // and before its file handle is closed; failure to do so could violate
994 : // durability or lead to corrupted on-disk state. This method cannot, in a
995 : // platform-and-FS-agnostic way, ensure that all sstables in the input are
996 : // properly synced to disk. Opening new file handles and Sync()-ing them
997 : // does not always guarantee durability; see the discussion here on that:
998 : // https://github.com/cockroachdb/pebble/pull/835#issuecomment-663075379
999 : //
1000 : // Ingestion loads each sstable into the lowest level of the LSM which it
1001 : // doesn't overlap (see ingestTargetLevel). If an sstable overlaps a memtable,
1002 : // ingestion forces the memtable to flush, and then waits for the flush to
1003 : // occur. In some cases, such as with no foreign sstables and no excise span,
1004 : // ingestion that gets blocked on a memtable can join the flushable queue and
1005 : // finish even before the memtable has been flushed.
1006 : //
1007 : // The steps for ingestion are:
1008 : //
1009 : // 1. Allocate file numbers for every sstable being ingested.
1010 : // 2. Load the metadata for all sstables being ingested.
1011 : // 3. Sort the sstables by smallest key, verifying non overlap (for local
1012 : // sstables).
1013 : // 4. Hard link (or copy) the local sstables into the DB directory.
1014 : // 5. Allocate a sequence number to use for all of the entries in the
1015 : // local sstables. This is the step where overlap with memtables is
1016 : // determined. If there is overlap, we remember the most recent memtable
1017 : // that overlaps.
1018 : // 6. Update the sequence number in the ingested local sstables. (Remote
1019 : // sstables get fixed sequence numbers that were determined at load time.)
1020 : // 7. Wait for the most recent memtable that overlaps to flush (if any).
1021 : // 8. Add the ingested sstables to the version (DB.ingestApply).
1022 : // 8.1. If an excise span was specified, figure out what sstables in the
1023 : // current version overlap with the excise span, and create new virtual
1024 : // sstables out of those sstables that exclude the excised span (DB.excise).
1025 : // 9. Publish the ingestion sequence number.
1026 : //
1027 : // Note that if the mutable memtable overlaps with ingestion, a flush of the
1028 : // memtable is forced equivalent to DB.Flush. Additionally, subsequent
1029 : // mutations that get sequence numbers larger than the ingestion sequence
1030 : // number get queued up behind the ingestion waiting for it to complete. This
1031 : // can produce a noticeable hiccup in performance. See
1032 : // https://github.com/cockroachdb/pebble/issues/25 for an idea for how to fix
1033 : // this hiccup.
1034 2 : func (d *DB) Ingest(ctx context.Context, paths []string) error {
1035 2 : if err := d.closed.Load(); err != nil {
1036 1 : panic(err)
1037 : }
1038 2 : if d.opts.ReadOnly {
1039 1 : return ErrReadOnly
1040 1 : }
1041 2 : _, err := d.ingest(ctx, paths, nil /* shared */, KeyRange{}, nil /* external */)
1042 2 : return err
1043 : }
1044 :
1045 : // IngestOperationStats provides some information about where in the LSM the
1046 : // bytes were ingested.
1047 : type IngestOperationStats struct {
1048 : // Bytes is the total bytes in the ingested sstables.
1049 : Bytes uint64
1050 : // ApproxIngestedIntoL0Bytes is the approximate number of bytes ingested
1051 : // into L0. This value is approximate when flushable ingests are active and
1052 : // an ingest overlaps an entry in the flushable queue. Currently, this
1053 : // approximation is very rough, only including tables that overlapped the
1054 : // memtable. This estimate may be improved with #2112.
1055 : ApproxIngestedIntoL0Bytes uint64
1056 : // MemtableOverlappingFiles is the count of ingested sstables
1057 : // that overlapped keys in the memtables.
1058 : MemtableOverlappingFiles int
1059 : }
1060 :
1061 : // ExternalFile are external sstables that can be referenced through
1062 : // objprovider and ingested as remote files that will not be refcounted or
1063 : // cleaned up. For use with online restore. Note that the underlying sstable
1064 : // could contain keys outside the [Smallest,Largest) bounds; however Pebble
1065 : // is expected to only read the keys within those bounds.
1066 : type ExternalFile struct {
1067 : // Locator is the shared.Locator that can be used with objProvider to
1068 : // resolve a reference to this external sstable.
1069 : Locator remote.Locator
1070 :
1071 : // ObjName is the unique name of this sstable on Locator.
1072 : ObjName string
1073 :
1074 : // Size of the referenced proportion of the virtualized sstable. An estimate
1075 : // is acceptable in lieu of the backing file size.
1076 : Size uint64
1077 :
1078 : // StartKey and EndKey define the bounds of the sstable; the ingestion
1079 : // of this file will only result in keys within [StartKey, EndKey) if
1080 : // EndKeyIsInclusive is false or [StartKey, EndKey] if it is true.
1081 : // These bounds are loose i.e. it's possible for keys to not span the
1082 : // entirety of this range.
1083 : //
1084 : // StartKey and EndKey user keys must not have suffixes.
1085 : //
1086 : // Multiple ExternalFiles in one ingestion must all have non-overlapping
1087 : // bounds.
1088 : StartKey, EndKey []byte
1089 :
1090 : // EndKeyIsInclusive is true if EndKey should be treated as inclusive.
1091 : EndKeyIsInclusive bool
1092 :
1093 : // HasPointKey and HasRangeKey denote whether this file contains point keys
1094 : // or range keys. If both structs are false, an error is returned during
1095 : // ingestion.
1096 : HasPointKey, HasRangeKey bool
1097 :
1098 : // SyntheticPrefix will prepend this suffix to all keys in the file during
1099 : // iteration. Note that the backing file itself is not modified.
1100 : //
1101 : // SyntheticPrefix must be a prefix of both Bounds.Start and Bounds.End.
1102 : SyntheticPrefix []byte
1103 :
1104 : // SyntheticSuffix will replace the suffix of every key in the file during
1105 : // iteration. Note that the file itself is not modified, rather, every key
1106 : // returned by an iterator will have the synthetic suffix.
1107 : //
1108 : // SyntheticSuffix can only be used under the following conditions:
1109 : // - the synthetic suffix must sort before any non-empty suffixes in the
1110 : // backing sst (the entire sst, not just the part restricted to Bounds).
1111 : // - the backing sst must not contain multiple keys with the same prefix.
1112 : SyntheticSuffix []byte
1113 :
1114 : // Level denotes the level at which this file was present at read time
1115 : // if the external file was returned by a scan of an existing Pebble
1116 : // instance. If Level is 0, this field is ignored.
1117 : Level uint8
1118 : }
1119 :
1120 : // IngestWithStats does the same as Ingest, and additionally returns
1121 : // IngestOperationStats.
1122 1 : func (d *DB) IngestWithStats(ctx context.Context, paths []string) (IngestOperationStats, error) {
1123 1 : if err := d.closed.Load(); err != nil {
1124 0 : panic(err)
1125 : }
1126 1 : if d.opts.ReadOnly {
1127 0 : return IngestOperationStats{}, ErrReadOnly
1128 0 : }
1129 1 : return d.ingest(ctx, paths, nil, KeyRange{}, nil)
1130 : }
1131 :
1132 : // IngestExternalFiles does the same as IngestWithStats, and additionally
1133 : // accepts external files (with locator info that can be resolved using
1134 : // d.opts.SharedStorage). These files must also be non-overlapping with
1135 : // each other, and must be resolvable through d.objProvider.
1136 : func (d *DB) IngestExternalFiles(
1137 : ctx context.Context, external []ExternalFile,
1138 2 : ) (IngestOperationStats, error) {
1139 2 : if err := d.closed.Load(); err != nil {
1140 0 : panic(err)
1141 : }
1142 :
1143 2 : if d.opts.ReadOnly {
1144 0 : return IngestOperationStats{}, ErrReadOnly
1145 0 : }
1146 2 : if d.opts.Experimental.RemoteStorage == nil {
1147 0 : return IngestOperationStats{}, errors.New("pebble: cannot ingest external files without shared storage configured")
1148 0 : }
1149 2 : return d.ingest(ctx, nil, nil, KeyRange{}, external)
1150 : }
1151 :
1152 : // IngestAndExcise does the same as IngestWithStats, and additionally accepts a
1153 : // list of shared files to ingest that can be read from a remote.Storage through
1154 : // a Provider. All the shared files must live within exciseSpan, and any existing
1155 : // keys in exciseSpan are deleted by turning existing sstables into virtual
1156 : // sstables (if not virtual already) and shrinking their spans to exclude
1157 : // exciseSpan. See the comment at Ingest for a more complete picture of the
1158 : // ingestion process.
1159 : //
1160 : // Panics if this DB instance was not instantiated with a remote.Storage and
1161 : // shared sstables are present.
1162 : func (d *DB) IngestAndExcise(
1163 : ctx context.Context,
1164 : paths []string,
1165 : shared []SharedSSTMeta,
1166 : external []ExternalFile,
1167 : exciseSpan KeyRange,
1168 2 : ) (IngestOperationStats, error) {
1169 2 : if err := d.closed.Load(); err != nil {
1170 0 : panic(err)
1171 : }
1172 2 : if d.opts.ReadOnly {
1173 0 : return IngestOperationStats{}, ErrReadOnly
1174 0 : }
1175 2 : if invariants.Enabled {
1176 2 : // Excise is only supported on prefix keys.
1177 2 : if d.opts.Comparer.Split(exciseSpan.Start) != len(exciseSpan.Start) {
1178 0 : panic("IngestAndExcise called with suffixed start key")
1179 : }
1180 2 : if d.opts.Comparer.Split(exciseSpan.End) != len(exciseSpan.End) {
1181 0 : panic("IngestAndExcise called with suffixed end key")
1182 : }
1183 : }
1184 2 : if v := d.FormatMajorVersion(); v < FormatMinForSharedObjects {
1185 0 : return IngestOperationStats{}, errors.Errorf(
1186 0 : "store has format major version %d; IngestAndExcise requires at least %d",
1187 0 : v, FormatMinForSharedObjects,
1188 0 : )
1189 0 : }
1190 2 : return d.ingest(ctx, paths, shared, exciseSpan, external)
1191 : }
1192 :
1193 : // Both DB.mu and commitPipeline.mu must be held while this is called.
1194 : func (d *DB) newIngestedFlushableEntry(
1195 : meta []*fileMetadata, seqNum base.SeqNum, logNum base.DiskFileNum, exciseSpan KeyRange,
1196 2 : ) (*flushableEntry, error) {
1197 2 : // If there's an excise being done atomically with the same ingest, we
1198 2 : // assign the lowest sequence number in the set of sequence numbers for this
1199 2 : // ingestion to the excise. Note that we've already allocated fileCount+1
1200 2 : // sequence numbers in this case.
1201 2 : //
1202 2 : // This mimics the behaviour in the non-flushable ingest case (see the callsite
1203 2 : // for ingestUpdateSeqNum).
1204 2 : fileSeqNumStart := seqNum
1205 2 : if exciseSpan.Valid() {
1206 2 : fileSeqNumStart = seqNum + 1 // the first seqNum is reserved for the excise.
1207 2 : }
1208 : // Update the sequence number for all of the sstables in the
1209 : // metadata. Writing the metadata to the manifest when the
1210 : // version edit is applied is the mechanism that persists the
1211 : // sequence number. The sstables themselves are left unmodified.
1212 : // In this case, a version edit will only be written to the manifest
1213 : // when the flushable is eventually flushed. If Pebble restarts in that
1214 : // time, then we'll lose the ingest sequence number information. But this
1215 : // information will also be reconstructed on node restart.
1216 2 : for i, m := range meta {
1217 2 : if err := setSeqNumInMetadata(m, fileSeqNumStart+base.SeqNum(i), d.cmp, d.opts.Comparer.FormatKey); err != nil {
1218 0 : return nil, err
1219 0 : }
1220 : }
1221 :
1222 2 : f := newIngestedFlushable(meta, d.opts.Comparer, d.newIters, d.tableNewRangeKeyIter, exciseSpan, seqNum)
1223 2 :
1224 2 : // NB: The logNum/seqNum are the WAL number which we're writing this entry
1225 2 : // to and the sequence number within the WAL which we'll write this entry
1226 2 : // to.
1227 2 : entry := d.newFlushableEntry(f, logNum, seqNum)
1228 2 : // The flushable entry starts off with a single reader ref, so increment
1229 2 : // the FileMetadata.Refs.
1230 2 : for _, file := range f.files {
1231 2 : file.FileBacking.Ref()
1232 2 : }
1233 2 : entry.unrefFiles = func() []*fileBacking {
1234 2 : var obsolete []*fileBacking
1235 2 : for _, file := range f.files {
1236 2 : if file.FileBacking.Unref() == 0 {
1237 2 : obsolete = append(obsolete, file.FileMetadata.FileBacking)
1238 2 : }
1239 : }
1240 2 : return obsolete
1241 : }
1242 :
1243 2 : entry.flushForced = true
1244 2 : entry.releaseMemAccounting = func() {}
1245 2 : return entry, nil
1246 : }
1247 :
1248 : // Both DB.mu and commitPipeline.mu must be held while this is called. Since
1249 : // we're holding both locks, the order in which we rotate the memtable or
1250 : // recycle the WAL in this function is irrelevant as long as the correct log
1251 : // numbers are assigned to the appropriate flushable.
1252 : func (d *DB) handleIngestAsFlushable(
1253 : meta []*fileMetadata, seqNum base.SeqNum, exciseSpan KeyRange,
1254 2 : ) error {
1255 2 : b := d.NewBatch()
1256 2 : if exciseSpan.Valid() {
1257 2 : b.excise(exciseSpan.Start, exciseSpan.End)
1258 2 : }
1259 2 : for _, m := range meta {
1260 2 : b.ingestSST(m.FileNum)
1261 2 : }
1262 2 : b.setSeqNum(seqNum)
1263 2 :
1264 2 : // If the WAL is disabled, then the logNum used to create the flushable
1265 2 : // entry doesn't matter. We just use the logNum assigned to the current
1266 2 : // mutable memtable. If the WAL is enabled, then this logNum will be
1267 2 : // overwritten by the logNum of the log which will contain the log entry
1268 2 : // for the ingestedFlushable.
1269 2 : logNum := d.mu.mem.queue[len(d.mu.mem.queue)-1].logNum
1270 2 : if !d.opts.DisableWAL {
1271 2 : // We create a new WAL for the flushable instead of reusing the end of
1272 2 : // the previous WAL. This simplifies the increment of the minimum
1273 2 : // unflushed log number, and also simplifies WAL replay.
1274 2 : var prevLogSize uint64
1275 2 : logNum, prevLogSize = d.rotateWAL()
1276 2 : // As the rotator of the WAL, we're responsible for updating the
1277 2 : // previous flushable queue tail's log size.
1278 2 : d.mu.mem.queue[len(d.mu.mem.queue)-1].logSize = prevLogSize
1279 2 :
1280 2 : d.mu.Unlock()
1281 2 : err := d.commit.directWrite(b)
1282 2 : if err != nil {
1283 0 : d.opts.Logger.Fatalf("%v", err)
1284 0 : }
1285 2 : d.mu.Lock()
1286 : }
1287 :
1288 : // The excise span is going to outlive this ingestion call. Copy it.
1289 2 : exciseSpan = KeyRange{
1290 2 : Start: slices.Clone(exciseSpan.Start),
1291 2 : End: slices.Clone(exciseSpan.End),
1292 2 : }
1293 2 : entry, err := d.newIngestedFlushableEntry(meta, seqNum, logNum, exciseSpan)
1294 2 : if err != nil {
1295 0 : return err
1296 0 : }
1297 2 : nextSeqNum := seqNum + base.SeqNum(b.Count())
1298 2 :
1299 2 : // Set newLogNum to the logNum of the previous flushable. This value is
1300 2 : // irrelevant if the WAL is disabled. If the WAL is enabled, then we set
1301 2 : // the appropriate value below.
1302 2 : newLogNum := d.mu.mem.queue[len(d.mu.mem.queue)-1].logNum
1303 2 : if !d.opts.DisableWAL {
1304 2 : // newLogNum will be the WAL num of the next mutable memtable which
1305 2 : // comes after the ingestedFlushable in the flushable queue. The mutable
1306 2 : // memtable will be created below.
1307 2 : //
1308 2 : // The prevLogSize returned by rotateWAL is the WAL to which the
1309 2 : // flushable ingest keys were appended. This intermediary WAL is only
1310 2 : // used to record the flushable ingest and nothing else.
1311 2 : newLogNum, entry.logSize = d.rotateWAL()
1312 2 : }
1313 :
1314 2 : d.mu.versions.metrics.Ingest.Count++
1315 2 : currMem := d.mu.mem.mutable
1316 2 : // NB: Placing ingested sstables above the current memtables
1317 2 : // requires rotating of the existing memtables/WAL. There is
1318 2 : // some concern of churning through tiny memtables due to
1319 2 : // ingested sstables being placed on top of them, but those
1320 2 : // memtables would have to be flushed anyways.
1321 2 : d.mu.mem.queue = append(d.mu.mem.queue, entry)
1322 2 : d.rotateMemtable(newLogNum, nextSeqNum, currMem, 0 /* minSize */)
1323 2 : d.updateReadStateLocked(d.opts.DebugCheck)
1324 2 : // TODO(aaditya): is this necessary? we call this already in rotateMemtable above
1325 2 : d.maybeScheduleFlush()
1326 2 : return nil
1327 : }
1328 :
1329 : // See comment at Ingest() for details on how this works.
1330 : func (d *DB) ingest(
1331 : ctx context.Context,
1332 : paths []string,
1333 : shared []SharedSSTMeta,
1334 : exciseSpan KeyRange,
1335 : external []ExternalFile,
1336 2 : ) (IngestOperationStats, error) {
1337 2 : if len(shared) > 0 && d.opts.Experimental.RemoteStorage == nil {
1338 0 : panic("cannot ingest shared sstables with nil SharedStorage")
1339 : }
1340 2 : if (exciseSpan.Valid() || len(shared) > 0 || len(external) > 0) && d.FormatMajorVersion() < FormatVirtualSSTables {
1341 0 : return IngestOperationStats{}, errors.New("pebble: format major version too old for excise, shared or external sstable ingestion")
1342 0 : }
1343 2 : if len(external) > 0 && d.FormatMajorVersion() < FormatSyntheticPrefixSuffix {
1344 1 : for i := range external {
1345 1 : if len(external[i].SyntheticPrefix) > 0 {
1346 1 : return IngestOperationStats{}, errors.New("pebble: format major version too old for synthetic prefix ingestion")
1347 1 : }
1348 1 : if len(external[i].SyntheticSuffix) > 0 {
1349 1 : return IngestOperationStats{}, errors.New("pebble: format major version too old for synthetic suffix ingestion")
1350 1 : }
1351 : }
1352 : }
1353 : // Allocate file numbers for all of the files being ingested and mark them as
1354 : // pending in order to prevent them from being deleted. Note that this causes
1355 : // the file number ordering to be out of alignment with sequence number
1356 : // ordering. The sorting of L0 tables by sequence number avoids relying on
1357 : // that (busted) invariant.
1358 2 : pendingOutputs := make([]base.FileNum, len(paths)+len(shared)+len(external))
1359 2 : for i := 0; i < len(paths)+len(shared)+len(external); i++ {
1360 2 : pendingOutputs[i] = d.mu.versions.getNextFileNum()
1361 2 : }
1362 :
1363 2 : jobID := d.newJobID()
1364 2 :
1365 2 : // Load the metadata for all the files being ingested. This step detects
1366 2 : // and elides empty sstables.
1367 2 : loadResult, err := ingestLoad(ctx, d.opts, d.FormatMajorVersion(), paths, shared, external, d.cacheID, pendingOutputs)
1368 2 : if err != nil {
1369 1 : return IngestOperationStats{}, err
1370 1 : }
1371 :
1372 2 : if loadResult.fileCount() == 0 {
1373 2 : // All of the sstables to be ingested were empty. Nothing to do.
1374 2 : return IngestOperationStats{}, nil
1375 2 : }
1376 :
1377 : // Verify the sstables do not overlap.
1378 2 : if err := ingestSortAndVerify(d.cmp, loadResult, exciseSpan); err != nil {
1379 2 : return IngestOperationStats{}, err
1380 2 : }
1381 :
1382 : // Hard link the sstables into the DB directory. Since the sstables aren't
1383 : // referenced by a version, they won't be used. If the hard linking fails
1384 : // (e.g. because the files reside on a different filesystem), ingestLinkLocal
1385 : // will fall back to copying, and if that fails we undo our work and return an
1386 : // error.
1387 2 : if err := ingestLinkLocal(ctx, jobID, d.opts, d.objProvider, loadResult.local); err != nil {
1388 0 : return IngestOperationStats{}, err
1389 0 : }
1390 :
1391 2 : err = d.ingestAttachRemote(jobID, loadResult)
1392 2 : defer d.ingestUnprotectExternalBackings(loadResult)
1393 2 : if err != nil {
1394 0 : return IngestOperationStats{}, err
1395 0 : }
1396 :
1397 : // Make the new tables durable. We need to do this at some point before we
1398 : // update the MANIFEST (via logAndApply), otherwise a crash can have the
1399 : // tables referenced in the MANIFEST, but not present in the provider.
1400 2 : if err := d.objProvider.Sync(); err != nil {
1401 1 : return IngestOperationStats{}, err
1402 1 : }
1403 :
1404 : // metaFlushableOverlaps is a map indicating which of the ingested sstables
1405 : // overlap some table in the flushable queue. It's used to approximate
1406 : // ingest-into-L0 stats when using flushable ingests.
1407 2 : metaFlushableOverlaps := make(map[FileNum]bool, loadResult.fileCount())
1408 2 : var mem *flushableEntry
1409 2 : var mut *memTable
1410 2 : // asFlushable indicates whether the sstable was ingested as a flushable.
1411 2 : var asFlushable bool
1412 2 : prepare := func(seqNum base.SeqNum) {
1413 2 : // Note that d.commit.mu is held by commitPipeline when calling prepare.
1414 2 :
1415 2 : // Determine the set of bounds we care about for the purpose of checking
1416 2 : // for overlap among the flushables. If there's an excise span, we need
1417 2 : // to check for overlap with its bounds as well.
1418 2 : overlapBounds := make([]bounded, 0, loadResult.fileCount()+1)
1419 2 : for _, m := range loadResult.local {
1420 2 : overlapBounds = append(overlapBounds, m.fileMetadata)
1421 2 : }
1422 2 : for _, m := range loadResult.shared {
1423 2 : overlapBounds = append(overlapBounds, m.fileMetadata)
1424 2 : }
1425 2 : for _, m := range loadResult.external {
1426 2 : overlapBounds = append(overlapBounds, m.fileMetadata)
1427 2 : }
1428 2 : if exciseSpan.Valid() {
1429 2 : overlapBounds = append(overlapBounds, &exciseSpan)
1430 2 : }
1431 :
1432 2 : d.mu.Lock()
1433 2 : defer d.mu.Unlock()
1434 2 :
1435 2 : // Check if any of the currently-open EventuallyFileOnlySnapshots overlap
1436 2 : // in key ranges with the excise span. If so, we need to check for memtable
1437 2 : // overlaps with all bounds of that EventuallyFileOnlySnapshot in addition
1438 2 : // to the ingestion's own bounds too.
1439 2 :
1440 2 : if exciseSpan.Valid() {
1441 2 : for s := d.mu.snapshots.root.next; s != &d.mu.snapshots.root; s = s.next {
1442 2 : if s.efos == nil {
1443 0 : continue
1444 : }
1445 2 : if base.Visible(seqNum, s.efos.seqNum, base.SeqNumMax) {
1446 0 : // We only worry about snapshots older than the excise. Any snapshots
1447 0 : // created after the excise should see the excised view of the LSM
1448 0 : // anyway.
1449 0 : //
1450 0 : // Since we delay publishing the excise seqnum as visible until after
1451 0 : // the apply step, this case will never be hit in practice until we
1452 0 : // make excises flushable ingests.
1453 0 : continue
1454 : }
1455 2 : if invariants.Enabled {
1456 2 : if s.efos.hasTransitioned() {
1457 0 : panic("unexpected transitioned EFOS in snapshots list")
1458 : }
1459 : }
1460 2 : for i := range s.efos.protectedRanges {
1461 2 : if !s.efos.protectedRanges[i].OverlapsKeyRange(d.cmp, exciseSpan) {
1462 2 : continue
1463 : }
1464 : // Our excise conflicts with this EFOS. We need to add its protected
1465 : // ranges to our overlapBounds. Grow overlapBounds in one allocation
1466 : // if necesary.
1467 2 : prs := s.efos.protectedRanges
1468 2 : if cap(overlapBounds) < len(overlapBounds)+len(prs) {
1469 2 : oldOverlapBounds := overlapBounds
1470 2 : overlapBounds = make([]bounded, len(oldOverlapBounds), len(oldOverlapBounds)+len(prs))
1471 2 : copy(overlapBounds, oldOverlapBounds)
1472 2 : }
1473 2 : for i := range prs {
1474 2 : overlapBounds = append(overlapBounds, &prs[i])
1475 2 : }
1476 2 : break
1477 : }
1478 : }
1479 : }
1480 :
1481 : // Check to see if any files overlap with any of the memtables. The queue
1482 : // is ordered from oldest to newest with the mutable memtable being the
1483 : // last element in the slice. We want to wait for the newest table that
1484 : // overlaps.
1485 :
1486 2 : for i := len(d.mu.mem.queue) - 1; i >= 0; i-- {
1487 2 : m := d.mu.mem.queue[i]
1488 2 : m.computePossibleOverlaps(func(b bounded) shouldContinue {
1489 2 : // If this is the first table to overlap a flushable, save
1490 2 : // the flushable. This ingest must be ingested or flushed
1491 2 : // after it.
1492 2 : if mem == nil {
1493 2 : mem = m
1494 2 : }
1495 :
1496 2 : switch v := b.(type) {
1497 2 : case *fileMetadata:
1498 2 : // NB: False positives are possible if `m` is a flushable
1499 2 : // ingest that overlaps the file `v` in bounds but doesn't
1500 2 : // contain overlapping data. This is considered acceptable
1501 2 : // because it's rare (in CockroachDB a bound overlap likely
1502 2 : // indicates a data overlap), and blocking the commit
1503 2 : // pipeline while we perform I/O to check for overlap may be
1504 2 : // more disruptive than enqueueing this ingestion on the
1505 2 : // flushable queue and switching to a new memtable.
1506 2 : metaFlushableOverlaps[v.FileNum] = true
1507 2 : case *KeyRange:
1508 : // An excise span or an EventuallyFileOnlySnapshot protected range;
1509 : // not a file.
1510 0 : default:
1511 0 : panic("unreachable")
1512 : }
1513 2 : return continueIteration
1514 : }, overlapBounds...)
1515 : }
1516 :
1517 2 : if mem == nil {
1518 2 : // No overlap with any of the queued flushables, so no need to queue
1519 2 : // after them.
1520 2 :
1521 2 : // New writes with higher sequence numbers may be concurrently
1522 2 : // committed. We must ensure they don't flush before this ingest
1523 2 : // completes. To do that, we ref the mutable memtable as a writer,
1524 2 : // preventing its flushing (and the flushing of all subsequent
1525 2 : // flushables in the queue). Once we've acquired the manifest lock
1526 2 : // to add the ingested sstables to the LSM, we can unref as we're
1527 2 : // guaranteed that the flush won't edit the LSM before this ingest.
1528 2 : mut = d.mu.mem.mutable
1529 2 : mut.writerRef()
1530 2 : return
1531 2 : }
1532 :
1533 : // The ingestion overlaps with some entry in the flushable queue. If the
1534 : // pre-conditions are met below, we can treat this ingestion as a flushable
1535 : // ingest, otherwise we wait on the memtable flush before ingestion.
1536 : //
1537 : // TODO(aaditya): We should make flushableIngest compatible with remote
1538 : // files.
1539 2 : hasRemoteFiles := len(shared) > 0 || len(external) > 0
1540 2 : canIngestFlushable := d.FormatMajorVersion() >= FormatFlushableIngest &&
1541 2 : (len(d.mu.mem.queue) < d.opts.MemTableStopWritesThreshold) &&
1542 2 : !d.opts.Experimental.DisableIngestAsFlushable() && !hasRemoteFiles &&
1543 2 : (!exciseSpan.Valid() || d.FormatMajorVersion() >= FormatFlushableIngestExcises)
1544 2 :
1545 2 : if !canIngestFlushable {
1546 2 : // We're not able to ingest as a flushable,
1547 2 : // so we must synchronously flush.
1548 2 : //
1549 2 : // TODO(bilal): Currently, if any of the files being ingested are shared,
1550 2 : // we cannot use flushable ingests and need
1551 2 : // to wait synchronously.
1552 2 : if mem.flushable == d.mu.mem.mutable {
1553 2 : err = d.makeRoomForWrite(nil)
1554 2 : }
1555 : // New writes with higher sequence numbers may be concurrently
1556 : // committed. We must ensure they don't flush before this ingest
1557 : // completes. To do that, we ref the mutable memtable as a writer,
1558 : // preventing its flushing (and the flushing of all subsequent
1559 : // flushables in the queue). Once we've acquired the manifest lock
1560 : // to add the ingested sstables to the LSM, we can unref as we're
1561 : // guaranteed that the flush won't edit the LSM before this ingest.
1562 2 : mut = d.mu.mem.mutable
1563 2 : mut.writerRef()
1564 2 : mem.flushForced = true
1565 2 : d.maybeScheduleFlush()
1566 2 : return
1567 : }
1568 : // Since there aren't too many memtables already queued up, we can
1569 : // slide the ingested sstables on top of the existing memtables.
1570 2 : asFlushable = true
1571 2 : fileMetas := make([]*fileMetadata, len(loadResult.local))
1572 2 : for i := range fileMetas {
1573 2 : fileMetas[i] = loadResult.local[i].fileMetadata
1574 2 : }
1575 2 : err = d.handleIngestAsFlushable(fileMetas, seqNum, exciseSpan)
1576 : }
1577 :
1578 2 : var ve *versionEdit
1579 2 : apply := func(seqNum base.SeqNum) {
1580 2 : if err != nil || asFlushable {
1581 2 : // An error occurred during prepare.
1582 2 : if mut != nil {
1583 0 : if mut.writerUnref() {
1584 0 : d.mu.Lock()
1585 0 : d.maybeScheduleFlush()
1586 0 : d.mu.Unlock()
1587 0 : }
1588 : }
1589 2 : return
1590 : }
1591 :
1592 : // If there's an excise being done atomically with the same ingest, we
1593 : // assign the lowest sequence number in the set of sequence numbers for this
1594 : // ingestion to the excise. Note that we've already allocated fileCount+1
1595 : // sequence numbers in this case.
1596 2 : if exciseSpan.Valid() {
1597 2 : seqNum++ // the first seqNum is reserved for the excise.
1598 2 : }
1599 : // Update the sequence numbers for all ingested sstables'
1600 : // metadata. When the version edit is applied, the metadata is
1601 : // written to the manifest, persisting the sequence number.
1602 : // The sstables themselves are left unmodified.
1603 2 : if err = ingestUpdateSeqNum(
1604 2 : d.cmp, d.opts.Comparer.FormatKey, seqNum, loadResult,
1605 2 : ); err != nil {
1606 0 : if mut != nil {
1607 0 : if mut.writerUnref() {
1608 0 : d.mu.Lock()
1609 0 : d.maybeScheduleFlush()
1610 0 : d.mu.Unlock()
1611 0 : }
1612 : }
1613 0 : return
1614 : }
1615 :
1616 : // If we overlapped with a memtable in prepare wait for the flush to
1617 : // finish.
1618 2 : if mem != nil {
1619 2 : <-mem.flushed
1620 2 : }
1621 :
1622 : // Assign the sstables to the correct level in the LSM and apply the
1623 : // version edit.
1624 2 : ve, err = d.ingestApply(ctx, jobID, loadResult, mut, exciseSpan, seqNum)
1625 : }
1626 :
1627 : // Only one ingest can occur at a time because if not, one would block waiting
1628 : // for the other to finish applying. This blocking would happen while holding
1629 : // the commit mutex which would prevent unrelated batches from writing their
1630 : // changes to the WAL and memtable. This will cause a bigger commit hiccup
1631 : // during ingestion.
1632 2 : seqNumCount := loadResult.fileCount()
1633 2 : if exciseSpan.Valid() {
1634 2 : seqNumCount++
1635 2 : }
1636 2 : d.commit.ingestSem <- struct{}{}
1637 2 : d.commit.AllocateSeqNum(seqNumCount, prepare, apply)
1638 2 : <-d.commit.ingestSem
1639 2 :
1640 2 : if err != nil {
1641 1 : if err2 := ingestCleanup(d.objProvider, loadResult.local); err2 != nil {
1642 0 : d.opts.Logger.Errorf("ingest cleanup failed: %v", err2)
1643 0 : }
1644 2 : } else {
1645 2 : // Since we either created a hard link to the ingesting files, or copied
1646 2 : // them over, it is safe to remove the originals paths.
1647 2 : for i := range loadResult.local {
1648 2 : path := loadResult.local[i].path
1649 2 : if err2 := d.opts.FS.Remove(path); err2 != nil {
1650 1 : d.opts.Logger.Errorf("ingest failed to remove original file: %s", err2)
1651 1 : }
1652 : }
1653 : }
1654 :
1655 2 : info := TableIngestInfo{
1656 2 : JobID: int(jobID),
1657 2 : Err: err,
1658 2 : flushable: asFlushable,
1659 2 : }
1660 2 : if len(loadResult.local) > 0 {
1661 2 : info.GlobalSeqNum = loadResult.local[0].SmallestSeqNum
1662 2 : } else if len(loadResult.shared) > 0 {
1663 2 : info.GlobalSeqNum = loadResult.shared[0].SmallestSeqNum
1664 2 : } else {
1665 2 : info.GlobalSeqNum = loadResult.external[0].SmallestSeqNum
1666 2 : }
1667 2 : var stats IngestOperationStats
1668 2 : if ve != nil {
1669 2 : info.Tables = make([]struct {
1670 2 : TableInfo
1671 2 : Level int
1672 2 : }, len(ve.NewFiles))
1673 2 : for i := range ve.NewFiles {
1674 2 : e := &ve.NewFiles[i]
1675 2 : info.Tables[i].Level = e.Level
1676 2 : info.Tables[i].TableInfo = e.Meta.TableInfo()
1677 2 : stats.Bytes += e.Meta.Size
1678 2 : if e.Level == 0 {
1679 2 : stats.ApproxIngestedIntoL0Bytes += e.Meta.Size
1680 2 : }
1681 2 : if metaFlushableOverlaps[e.Meta.FileNum] {
1682 2 : stats.MemtableOverlappingFiles++
1683 2 : }
1684 : }
1685 2 : } else if asFlushable {
1686 2 : // NB: If asFlushable == true, there are no shared sstables.
1687 2 : info.Tables = make([]struct {
1688 2 : TableInfo
1689 2 : Level int
1690 2 : }, len(loadResult.local))
1691 2 : for i, f := range loadResult.local {
1692 2 : info.Tables[i].Level = -1
1693 2 : info.Tables[i].TableInfo = f.TableInfo()
1694 2 : stats.Bytes += f.Size
1695 2 : // We don't have exact stats on which files will be ingested into
1696 2 : // L0, because actual ingestion into the LSM has been deferred until
1697 2 : // flush time. Instead, we infer based on memtable overlap.
1698 2 : //
1699 2 : // TODO(jackson): If we optimistically compute data overlap (#2112)
1700 2 : // before entering the commit pipeline, we can use that overlap to
1701 2 : // improve our approximation by incorporating overlap with L0, not
1702 2 : // just memtables.
1703 2 : if metaFlushableOverlaps[f.FileNum] {
1704 2 : stats.ApproxIngestedIntoL0Bytes += f.Size
1705 2 : stats.MemtableOverlappingFiles++
1706 2 : }
1707 : }
1708 : }
1709 2 : d.opts.EventListener.TableIngested(info)
1710 2 :
1711 2 : return stats, err
1712 : }
1713 :
1714 : // excise updates ve to include a replacement of the file m with new virtual
1715 : // sstables that exclude exciseSpan, returning a slice of newly-created files if
1716 : // any. If the entirety of m is deleted by exciseSpan, no new sstables are added
1717 : // and m is deleted. Note that ve is updated in-place.
1718 : //
1719 : // The manifest lock must be held when calling this method.
1720 : func (d *DB) excise(
1721 : ctx context.Context, exciseSpan base.UserKeyBounds, m *fileMetadata, ve *versionEdit, level int,
1722 2 : ) ([]manifest.NewFileEntry, error) {
1723 2 : numCreatedFiles := 0
1724 2 : // Check if there's actually an overlap between m and exciseSpan.
1725 2 : mBounds := base.UserKeyBoundsFromInternal(m.Smallest, m.Largest)
1726 2 : if !exciseSpan.Overlaps(d.cmp, &mBounds) {
1727 2 : return nil, nil
1728 2 : }
1729 2 : ve.DeletedFiles[deletedFileEntry{
1730 2 : Level: level,
1731 2 : FileNum: m.FileNum,
1732 2 : }] = m
1733 2 : // Fast path: m sits entirely within the exciseSpan, so just delete it.
1734 2 : if exciseSpan.ContainsInternalKey(d.cmp, m.Smallest) && exciseSpan.ContainsInternalKey(d.cmp, m.Largest) {
1735 2 : return nil, nil
1736 2 : }
1737 :
1738 2 : var iters iterSet
1739 2 : var itersLoaded bool
1740 2 : defer iters.CloseAll()
1741 2 : loadItersIfNecessary := func() error {
1742 2 : if itersLoaded {
1743 2 : return nil
1744 2 : }
1745 2 : var err error
1746 2 : iters, err = d.newIters(ctx, m, &IterOptions{
1747 2 : CategoryAndQoS: sstable.CategoryAndQoS{
1748 2 : Category: "pebble-ingest",
1749 2 : QoSLevel: sstable.LatencySensitiveQoSLevel,
1750 2 : },
1751 2 : layer: manifest.Level(level),
1752 2 : }, internalIterOpts{}, iterPointKeys|iterRangeDeletions|iterRangeKeys)
1753 2 : itersLoaded = true
1754 2 : return err
1755 : }
1756 :
1757 2 : needsBacking := false
1758 2 : // Create a file to the left of the excise span, if necessary.
1759 2 : // The bounds of this file will be [m.Smallest, lastKeyBefore(exciseSpan.Start)].
1760 2 : //
1761 2 : // We create bounds that are tight on user keys, and we make the effort to find
1762 2 : // the last key in the original sstable that's smaller than exciseSpan.Start
1763 2 : // even though it requires some sstable reads. We could choose to create
1764 2 : // virtual sstables on loose userKey bounds, in which case we could just set
1765 2 : // leftFile.Largest to an exclusive sentinel at exciseSpan.Start. The biggest
1766 2 : // issue with that approach would be that it'd lead to lots of small virtual
1767 2 : // sstables in the LSM that have no guarantee on containing even a single user
1768 2 : // key within the file bounds. This has the potential to increase both read and
1769 2 : // write-amp as we will be opening up these sstables only to find no relevant
1770 2 : // keys in the read path, and compacting sstables on top of them instead of
1771 2 : // directly into the space occupied by them. We choose to incur the cost of
1772 2 : // calculating tight bounds at this time instead of creating more work in the
1773 2 : // future.
1774 2 : //
1775 2 : // TODO(bilal): Some of this work can happen without grabbing the manifest
1776 2 : // lock; we could grab one currentVersion, release the lock, calculate excised
1777 2 : // files, then grab the lock again and recalculate for just the files that
1778 2 : // have changed since our previous calculation. Do this optimiaztino as part of
1779 2 : // https://github.com/cockroachdb/pebble/issues/2112 .
1780 2 : if d.cmp(m.Smallest.UserKey, exciseSpan.Start) < 0 {
1781 2 : leftFile := &fileMetadata{
1782 2 : Virtual: true,
1783 2 : FileBacking: m.FileBacking,
1784 2 : FileNum: d.mu.versions.getNextFileNum(),
1785 2 : // Note that these are loose bounds for smallest/largest seqnums, but they're
1786 2 : // sufficient for maintaining correctness.
1787 2 : SmallestSeqNum: m.SmallestSeqNum,
1788 2 : LargestSeqNum: m.LargestSeqNum,
1789 2 : LargestSeqNumAbsolute: m.LargestSeqNumAbsolute,
1790 2 : SyntheticPrefix: m.SyntheticPrefix,
1791 2 : SyntheticSuffix: m.SyntheticSuffix,
1792 2 : }
1793 2 : if m.HasPointKeys && !exciseSpan.ContainsInternalKey(d.cmp, m.SmallestPointKey) {
1794 2 : // This file will probably contain point keys.
1795 2 : if err := loadItersIfNecessary(); err != nil {
1796 0 : return nil, err
1797 0 : }
1798 2 : smallestPointKey := m.SmallestPointKey
1799 2 : if kv := iters.Point().SeekLT(exciseSpan.Start, base.SeekLTFlagsNone); kv != nil {
1800 2 : leftFile.ExtendPointKeyBounds(d.cmp, smallestPointKey, kv.K.Clone())
1801 2 : }
1802 : // Store the min of (exciseSpan.Start, rdel.End) in lastRangeDel. This
1803 : // needs to be a copy if the key is owned by the range del iter.
1804 2 : var lastRangeDel []byte
1805 2 : if rdel, err := iters.RangeDeletion().SeekLT(exciseSpan.Start); err != nil {
1806 0 : return nil, err
1807 2 : } else if rdel != nil {
1808 2 : lastRangeDel = append(lastRangeDel[:0], rdel.End...)
1809 2 : if d.cmp(lastRangeDel, exciseSpan.Start) > 0 {
1810 2 : lastRangeDel = exciseSpan.Start
1811 2 : }
1812 : }
1813 2 : if lastRangeDel != nil {
1814 2 : leftFile.ExtendPointKeyBounds(d.cmp, smallestPointKey, base.MakeExclusiveSentinelKey(InternalKeyKindRangeDelete, lastRangeDel))
1815 2 : }
1816 : }
1817 2 : if m.HasRangeKeys && !exciseSpan.ContainsInternalKey(d.cmp, m.SmallestRangeKey) {
1818 2 : // This file will probably contain range keys.
1819 2 : if err := loadItersIfNecessary(); err != nil {
1820 0 : return nil, err
1821 0 : }
1822 2 : smallestRangeKey := m.SmallestRangeKey
1823 2 : // Store the min of (exciseSpan.Start, rkey.End) in lastRangeKey. This
1824 2 : // needs to be a copy if the key is owned by the range key iter.
1825 2 : var lastRangeKey []byte
1826 2 : var lastRangeKeyKind InternalKeyKind
1827 2 : if rkey, err := iters.RangeKey().SeekLT(exciseSpan.Start); err != nil {
1828 0 : return nil, err
1829 2 : } else if rkey != nil {
1830 2 : lastRangeKey = append(lastRangeKey[:0], rkey.End...)
1831 2 : if d.cmp(lastRangeKey, exciseSpan.Start) > 0 {
1832 2 : lastRangeKey = exciseSpan.Start
1833 2 : }
1834 2 : lastRangeKeyKind = rkey.Keys[0].Kind()
1835 : }
1836 2 : if lastRangeKey != nil {
1837 2 : leftFile.ExtendRangeKeyBounds(d.cmp, smallestRangeKey, base.MakeExclusiveSentinelKey(lastRangeKeyKind, lastRangeKey))
1838 2 : }
1839 : }
1840 2 : if leftFile.HasRangeKeys || leftFile.HasPointKeys {
1841 2 : var err error
1842 2 : leftFile.Size, err = d.tableCache.estimateSize(m, leftFile.Smallest.UserKey, leftFile.Largest.UserKey)
1843 2 : if err != nil {
1844 0 : return nil, err
1845 0 : }
1846 2 : if leftFile.Size == 0 {
1847 2 : // On occasion, estimateSize gives us a low estimate, i.e. a 0 file size,
1848 2 : // such as if the excised file only has range keys/dels and no point
1849 2 : // keys. This can cause panics in places where we divide by file sizes.
1850 2 : // Correct for it here.
1851 2 : leftFile.Size = 1
1852 2 : }
1853 2 : if err := leftFile.Validate(d.cmp, d.opts.Comparer.FormatKey); err != nil {
1854 0 : return nil, err
1855 0 : }
1856 2 : leftFile.ValidateVirtual(m)
1857 2 : ve.NewFiles = append(ve.NewFiles, newFileEntry{Level: level, Meta: leftFile})
1858 2 : needsBacking = true
1859 2 : numCreatedFiles++
1860 : }
1861 : }
1862 : // Create a file to the right, if necessary.
1863 2 : if exciseSpan.ContainsInternalKey(d.cmp, m.Largest) {
1864 2 : // No key exists to the right of the excise span in this file.
1865 2 : if needsBacking && !m.Virtual {
1866 2 : // If m is virtual, then its file backing is already known to the manifest.
1867 2 : // We don't need to create another file backing. Note that there must be
1868 2 : // only one CreatedBackingTables entry per backing sstable. This is
1869 2 : // indicated by the VersionEdit.CreatedBackingTables invariant.
1870 2 : ve.CreatedBackingTables = append(ve.CreatedBackingTables, m.FileBacking)
1871 2 : }
1872 2 : return ve.NewFiles[len(ve.NewFiles)-numCreatedFiles:], nil
1873 : }
1874 : // Create a new file, rightFile, between [firstKeyAfter(exciseSpan.End), m.Largest].
1875 : //
1876 : // See comment before the definition of leftFile for the motivation behind
1877 : // calculating tight user-key bounds.
1878 2 : rightFile := &fileMetadata{
1879 2 : Virtual: true,
1880 2 : FileBacking: m.FileBacking,
1881 2 : FileNum: d.mu.versions.getNextFileNum(),
1882 2 : // Note that these are loose bounds for smallest/largest seqnums, but they're
1883 2 : // sufficient for maintaining correctness.
1884 2 : SmallestSeqNum: m.SmallestSeqNum,
1885 2 : LargestSeqNum: m.LargestSeqNum,
1886 2 : LargestSeqNumAbsolute: m.LargestSeqNumAbsolute,
1887 2 : SyntheticPrefix: m.SyntheticPrefix,
1888 2 : SyntheticSuffix: m.SyntheticSuffix,
1889 2 : }
1890 2 : if m.HasPointKeys && !exciseSpan.ContainsInternalKey(d.cmp, m.LargestPointKey) {
1891 2 : // This file will probably contain point keys
1892 2 : if err := loadItersIfNecessary(); err != nil {
1893 0 : return nil, err
1894 0 : }
1895 2 : largestPointKey := m.LargestPointKey
1896 2 : if kv := iters.Point().SeekGE(exciseSpan.End.Key, base.SeekGEFlagsNone); kv != nil {
1897 2 : if exciseSpan.End.Kind == base.Inclusive && d.equal(exciseSpan.End.Key, kv.K.UserKey) {
1898 0 : return nil, base.AssertionFailedf("cannot excise with an inclusive end key and data overlap at end key")
1899 0 : }
1900 2 : rightFile.ExtendPointKeyBounds(d.cmp, kv.K.Clone(), largestPointKey)
1901 : }
1902 : // Store the max of (exciseSpan.End, rdel.Start) in firstRangeDel. This
1903 : // needs to be a copy if the key is owned by the range del iter.
1904 2 : var firstRangeDel []byte
1905 2 : rdel, err := iters.RangeDeletion().SeekGE(exciseSpan.End.Key)
1906 2 : if err != nil {
1907 0 : return nil, err
1908 2 : } else if rdel != nil {
1909 2 : firstRangeDel = append(firstRangeDel[:0], rdel.Start...)
1910 2 : if d.cmp(firstRangeDel, exciseSpan.End.Key) < 0 {
1911 2 : // NB: This can only be done if the end bound is exclusive.
1912 2 : if exciseSpan.End.Kind != base.Exclusive {
1913 0 : return nil, base.AssertionFailedf("cannot truncate rangedel during excise with an inclusive upper bound")
1914 0 : }
1915 2 : firstRangeDel = exciseSpan.End.Key
1916 : }
1917 : }
1918 2 : if firstRangeDel != nil {
1919 2 : smallestPointKey := rdel.SmallestKey()
1920 2 : smallestPointKey.UserKey = firstRangeDel
1921 2 : rightFile.ExtendPointKeyBounds(d.cmp, smallestPointKey, largestPointKey)
1922 2 : }
1923 : }
1924 2 : if m.HasRangeKeys && !exciseSpan.ContainsInternalKey(d.cmp, m.LargestRangeKey) {
1925 2 : // This file will probably contain range keys.
1926 2 : if err := loadItersIfNecessary(); err != nil {
1927 0 : return nil, err
1928 0 : }
1929 2 : largestRangeKey := m.LargestRangeKey
1930 2 : // Store the max of (exciseSpan.End, rkey.Start) in firstRangeKey. This
1931 2 : // needs to be a copy if the key is owned by the range key iter.
1932 2 : var firstRangeKey []byte
1933 2 : rkey, err := iters.RangeKey().SeekGE(exciseSpan.End.Key)
1934 2 : if err != nil {
1935 0 : return nil, err
1936 2 : } else if rkey != nil {
1937 2 : firstRangeKey = append(firstRangeKey[:0], rkey.Start...)
1938 2 : if d.cmp(firstRangeKey, exciseSpan.End.Key) < 0 {
1939 2 : if exciseSpan.End.Kind != base.Exclusive {
1940 0 : return nil, base.AssertionFailedf("cannot truncate range key during excise with an inclusive upper bound")
1941 0 : }
1942 2 : firstRangeKey = exciseSpan.End.Key
1943 : }
1944 : }
1945 2 : if firstRangeKey != nil {
1946 2 : smallestRangeKey := rkey.SmallestKey()
1947 2 : smallestRangeKey.UserKey = firstRangeKey
1948 2 : // We call ExtendRangeKeyBounds so any internal boundType fields are
1949 2 : // set correctly. Note that this is mildly wasteful as we'll be comparing
1950 2 : // rightFile.{Smallest,Largest}RangeKey with themselves, which can be
1951 2 : // avoided if we exported ExtendOverallKeyBounds or so.
1952 2 : rightFile.ExtendRangeKeyBounds(d.cmp, smallestRangeKey, largestRangeKey)
1953 2 : }
1954 : }
1955 2 : if rightFile.HasRangeKeys || rightFile.HasPointKeys {
1956 2 : var err error
1957 2 : rightFile.Size, err = d.tableCache.estimateSize(m, rightFile.Smallest.UserKey, rightFile.Largest.UserKey)
1958 2 : if err != nil {
1959 0 : return nil, err
1960 0 : }
1961 2 : if rightFile.Size == 0 {
1962 2 : // On occasion, estimateSize gives us a low estimate, i.e. a 0 file size,
1963 2 : // such as if the excised file only has range keys/dels and no point keys.
1964 2 : // This can cause panics in places where we divide by file sizes. Correct
1965 2 : // for it here.
1966 2 : rightFile.Size = 1
1967 2 : }
1968 2 : if err := rightFile.Validate(d.cmp, d.opts.Comparer.FormatKey); err != nil {
1969 0 : return nil, err
1970 0 : }
1971 2 : rightFile.ValidateVirtual(m)
1972 2 : ve.NewFiles = append(ve.NewFiles, newFileEntry{Level: level, Meta: rightFile})
1973 2 : needsBacking = true
1974 2 : numCreatedFiles++
1975 : }
1976 :
1977 2 : if needsBacking && !m.Virtual {
1978 2 : // If m is virtual, then its file backing is already known to the manifest.
1979 2 : // We don't need to create another file backing. Note that there must be
1980 2 : // only one CreatedBackingTables entry per backing sstable. This is
1981 2 : // indicated by the VersionEdit.CreatedBackingTables invariant.
1982 2 : ve.CreatedBackingTables = append(ve.CreatedBackingTables, m.FileBacking)
1983 2 : }
1984 :
1985 2 : return ve.NewFiles[len(ve.NewFiles)-numCreatedFiles:], nil
1986 : }
1987 :
1988 : type ingestSplitFile struct {
1989 : // ingestFile is the file being ingested.
1990 : ingestFile *fileMetadata
1991 : // splitFile is the file that needs to be split to allow ingestFile to slot
1992 : // into `level` level.
1993 : splitFile *fileMetadata
1994 : // The level where ingestFile will go (and where splitFile already is).
1995 : level int
1996 : }
1997 :
1998 : // ingestSplit splits files specified in `files` and updates ve in-place to
1999 : // account for existing files getting split into two virtual sstables. The map
2000 : // `replacedFiles` contains an in-progress map of all files that have been
2001 : // replaced with new virtual sstables in this version edit so far, which is also
2002 : // updated in-place.
2003 : //
2004 : // d.mu as well as the manifest lock must be held when calling this method.
2005 : func (d *DB) ingestSplit(
2006 : ctx context.Context,
2007 : ve *versionEdit,
2008 : updateMetrics func(*fileMetadata, int, []newFileEntry),
2009 : files []ingestSplitFile,
2010 : replacedFiles map[base.FileNum][]newFileEntry,
2011 2 : ) error {
2012 2 : for _, s := range files {
2013 2 : ingestFileBounds := s.ingestFile.UserKeyBounds()
2014 2 : // replacedFiles can be thought of as a tree, where we start iterating with
2015 2 : // s.splitFile and run its fileNum through replacedFiles, then find which of
2016 2 : // the replaced files overlaps with s.ingestFile, which becomes the new
2017 2 : // splitFile, then we check splitFile's replacements in replacedFiles again
2018 2 : // for overlap with s.ingestFile, and so on until we either can't find the
2019 2 : // current splitFile in replacedFiles (i.e. that's the file that now needs to
2020 2 : // be split), or we don't find a file that overlaps with s.ingestFile, which
2021 2 : // means a prior ingest split already produced enough room for s.ingestFile
2022 2 : // to go into this level without necessitating another ingest split.
2023 2 : splitFile := s.splitFile
2024 2 : for splitFile != nil {
2025 2 : replaced, ok := replacedFiles[splitFile.FileNum]
2026 2 : if !ok {
2027 2 : break
2028 : }
2029 2 : updatedSplitFile := false
2030 2 : for i := range replaced {
2031 2 : if replaced[i].Meta.Overlaps(d.cmp, &ingestFileBounds) {
2032 2 : if updatedSplitFile {
2033 0 : // This should never happen because the earlier ingestTargetLevel
2034 0 : // function only finds split file candidates that are guaranteed to
2035 0 : // have no data overlap, only boundary overlap. See the comments
2036 0 : // in that method to see the definitions of data vs boundary
2037 0 : // overlap. That, plus the fact that files in `replaced` are
2038 0 : // guaranteed to have file bounds that are tight on user keys
2039 0 : // (as that's what `d.excise` produces), means that the only case
2040 0 : // where we overlap with two or more files in `replaced` is if we
2041 0 : // actually had data overlap all along, or if the ingestion files
2042 0 : // were overlapping, either of which is an invariant violation.
2043 0 : panic("updated with two files in ingestSplit")
2044 : }
2045 2 : splitFile = replaced[i].Meta
2046 2 : updatedSplitFile = true
2047 : }
2048 : }
2049 2 : if !updatedSplitFile {
2050 2 : // None of the replaced files overlapped with the file being ingested.
2051 2 : // This can happen if we've already excised a span overlapping with
2052 2 : // this file, or if we have consecutive ingested files that can slide
2053 2 : // within the same gap between keys in an existing file. For instance,
2054 2 : // if an existing file has keys a and g and we're ingesting b-c, d-e,
2055 2 : // the first loop iteration will split the existing file into one that
2056 2 : // ends in a and another that starts at g, and the second iteration will
2057 2 : // fall into this case and require no splitting.
2058 2 : //
2059 2 : // No splitting necessary.
2060 2 : splitFile = nil
2061 2 : }
2062 : }
2063 2 : if splitFile == nil {
2064 2 : continue
2065 : }
2066 : // NB: excise operates on [start, end). We're splitting at [start, end]
2067 : // (assuming !s.ingestFile.Largest.IsExclusiveSentinel()). The conflation
2068 : // of exclusive vs inclusive end bounds should not make a difference here
2069 : // as we're guaranteed to not have any data overlap between splitFile and
2070 : // s.ingestFile. d.excise will return an error if we pass an inclusive user
2071 : // key bound _and_ we end up seeing data overlap at the end key.
2072 2 : added, err := d.excise(ctx, base.UserKeyBoundsFromInternal(s.ingestFile.Smallest, s.ingestFile.Largest), splitFile, ve, s.level)
2073 2 : if err != nil {
2074 0 : return err
2075 0 : }
2076 2 : if _, ok := ve.DeletedFiles[deletedFileEntry{
2077 2 : Level: s.level,
2078 2 : FileNum: splitFile.FileNum,
2079 2 : }]; !ok {
2080 0 : panic("did not split file that was expected to be split")
2081 : }
2082 2 : replacedFiles[splitFile.FileNum] = added
2083 2 : for i := range added {
2084 2 : addedBounds := added[i].Meta.UserKeyBounds()
2085 2 : if s.ingestFile.Overlaps(d.cmp, &addedBounds) {
2086 0 : panic("ingest-time split produced a file that overlaps with ingested file")
2087 : }
2088 : }
2089 2 : updateMetrics(splitFile, s.level, added)
2090 : }
2091 : // Flatten the version edit by removing any entries from ve.NewFiles that
2092 : // are also in ve.DeletedFiles.
2093 2 : newNewFiles := ve.NewFiles[:0]
2094 2 : for i := range ve.NewFiles {
2095 2 : fn := ve.NewFiles[i].Meta.FileNum
2096 2 : deEntry := deletedFileEntry{Level: ve.NewFiles[i].Level, FileNum: fn}
2097 2 : if _, ok := ve.DeletedFiles[deEntry]; ok {
2098 2 : delete(ve.DeletedFiles, deEntry)
2099 2 : } else {
2100 2 : newNewFiles = append(newNewFiles, ve.NewFiles[i])
2101 2 : }
2102 : }
2103 2 : ve.NewFiles = newNewFiles
2104 2 : return nil
2105 : }
2106 :
2107 : func (d *DB) ingestApply(
2108 : ctx context.Context,
2109 : jobID JobID,
2110 : lr ingestLoadResult,
2111 : mut *memTable,
2112 : exciseSpan KeyRange,
2113 : exciseSeqNum base.SeqNum,
2114 2 : ) (*versionEdit, error) {
2115 2 : d.mu.Lock()
2116 2 : defer d.mu.Unlock()
2117 2 :
2118 2 : ve := &versionEdit{
2119 2 : NewFiles: make([]newFileEntry, lr.fileCount()),
2120 2 : }
2121 2 : if exciseSpan.Valid() || (d.opts.Experimental.IngestSplit != nil && d.opts.Experimental.IngestSplit()) {
2122 2 : ve.DeletedFiles = map[manifest.DeletedFileEntry]*manifest.FileMetadata{}
2123 2 : }
2124 2 : metrics := make(map[int]*LevelMetrics)
2125 2 :
2126 2 : // Lock the manifest for writing before we use the current version to
2127 2 : // determine the target level. This prevents two concurrent ingestion jobs
2128 2 : // from using the same version to determine the target level, and also
2129 2 : // provides serialization with concurrent compaction and flush jobs.
2130 2 : // logAndApply unconditionally releases the manifest lock, but any earlier
2131 2 : // returns must unlock the manifest.
2132 2 : d.mu.versions.logLock()
2133 2 :
2134 2 : if mut != nil {
2135 2 : // Unref the mutable memtable to allows its flush to proceed. Now that we've
2136 2 : // acquired the manifest lock, we can be certain that if the mutable
2137 2 : // memtable has received more recent conflicting writes, the flush won't
2138 2 : // beat us to applying to the manifest resulting in sequence number
2139 2 : // inversion. Even though we call maybeScheduleFlush right now, this flush
2140 2 : // will apply after our ingestion.
2141 2 : if mut.writerUnref() {
2142 2 : d.maybeScheduleFlush()
2143 2 : }
2144 : }
2145 :
2146 2 : current := d.mu.versions.currentVersion()
2147 2 : overlapChecker := &overlapChecker{
2148 2 : comparer: d.opts.Comparer,
2149 2 : newIters: d.newIters,
2150 2 : opts: IterOptions{
2151 2 : logger: d.opts.Logger,
2152 2 : CategoryAndQoS: sstable.CategoryAndQoS{
2153 2 : Category: "pebble-ingest",
2154 2 : QoSLevel: sstable.LatencySensitiveQoSLevel,
2155 2 : },
2156 2 : },
2157 2 : v: current,
2158 2 : }
2159 2 : shouldIngestSplit := d.opts.Experimental.IngestSplit != nil &&
2160 2 : d.opts.Experimental.IngestSplit() && d.FormatMajorVersion() >= FormatVirtualSSTables
2161 2 : baseLevel := d.mu.versions.picker.getBaseLevel()
2162 2 : // filesToSplit is a list where each element is a pair consisting of a file
2163 2 : // being ingested and a file being split to make room for an ingestion into
2164 2 : // that level. Each ingested file will appear at most once in this list. It
2165 2 : // is possible for split files to appear twice in this list.
2166 2 : filesToSplit := make([]ingestSplitFile, 0)
2167 2 : checkCompactions := false
2168 2 : for i := 0; i < lr.fileCount(); i++ {
2169 2 : // Determine the lowest level in the LSM for which the sstable doesn't
2170 2 : // overlap any existing files in the level.
2171 2 : var m *fileMetadata
2172 2 : specifiedLevel := -1
2173 2 : isShared := false
2174 2 : isExternal := false
2175 2 : if i < len(lr.local) {
2176 2 : // local file.
2177 2 : m = lr.local[i].fileMetadata
2178 2 : } else if (i - len(lr.local)) < len(lr.shared) {
2179 2 : // shared file.
2180 2 : isShared = true
2181 2 : sharedIdx := i - len(lr.local)
2182 2 : m = lr.shared[sharedIdx].fileMetadata
2183 2 : specifiedLevel = int(lr.shared[sharedIdx].shared.Level)
2184 2 : } else {
2185 2 : // external file.
2186 2 : isExternal = true
2187 2 : externalIdx := i - (len(lr.local) + len(lr.shared))
2188 2 : m = lr.external[externalIdx].fileMetadata
2189 2 : if lr.externalFilesHaveLevel {
2190 1 : specifiedLevel = int(lr.external[externalIdx].external.Level)
2191 1 : }
2192 : }
2193 :
2194 : // Add to CreatedBackingTables if this is a new backing.
2195 : //
2196 : // Shared files always have a new backing. External files have new backings
2197 : // iff the backing disk file num and the file num match (see ingestAttachRemote).
2198 2 : if isShared || (isExternal && m.FileBacking.DiskFileNum == base.DiskFileNum(m.FileNum)) {
2199 2 : ve.CreatedBackingTables = append(ve.CreatedBackingTables, m.FileBacking)
2200 2 : }
2201 :
2202 2 : f := &ve.NewFiles[i]
2203 2 : var err error
2204 2 : if specifiedLevel != -1 {
2205 2 : f.Level = specifiedLevel
2206 2 : } else {
2207 2 : var splitFile *fileMetadata
2208 2 : if exciseSpan.Valid() && exciseSpan.Contains(d.cmp, m.Smallest) && exciseSpan.Contains(d.cmp, m.Largest) {
2209 2 : // This file fits perfectly within the excise span. We can slot it at
2210 2 : // L6, or sharedLevelsStart - 1 if we have shared files.
2211 2 : if len(lr.shared) > 0 || lr.externalFilesHaveLevel {
2212 2 : f.Level = sharedLevelsStart - 1
2213 2 : if baseLevel > f.Level {
2214 2 : f.Level = 0
2215 2 : }
2216 2 : } else {
2217 2 : f.Level = 6
2218 2 : }
2219 2 : } else {
2220 2 : // We check overlap against the LSM without holding DB.mu. Note that we
2221 2 : // are still holding the log lock, so the version cannot change.
2222 2 : // TODO(radu): perform this check optimistically outside of the log lock.
2223 2 : var lsmOverlap overlap.WithLSM
2224 2 : lsmOverlap, err = func() (overlap.WithLSM, error) {
2225 2 : d.mu.Unlock()
2226 2 : defer d.mu.Lock()
2227 2 : return overlapChecker.DetermineLSMOverlap(ctx, m.UserKeyBounds())
2228 2 : }()
2229 2 : if err == nil {
2230 2 : f.Level, splitFile, err = ingestTargetLevel(
2231 2 : ctx, d.cmp, lsmOverlap, baseLevel, d.mu.compact.inProgress, m, shouldIngestSplit,
2232 2 : )
2233 2 : }
2234 : }
2235 :
2236 2 : if splitFile != nil {
2237 2 : if invariants.Enabled {
2238 2 : if lf := current.Levels[f.Level].Find(d.cmp, splitFile); lf.Empty() {
2239 0 : panic("splitFile returned is not in level it should be")
2240 : }
2241 : }
2242 : // We take advantage of the fact that we won't drop the db mutex
2243 : // between now and the call to logAndApply. So, no files should
2244 : // get added to a new in-progress compaction at this point. We can
2245 : // avoid having to iterate on in-progress compactions to cancel them
2246 : // if none of the files being split have a compacting state.
2247 2 : if splitFile.IsCompacting() {
2248 1 : checkCompactions = true
2249 1 : }
2250 2 : filesToSplit = append(filesToSplit, ingestSplitFile{ingestFile: m, splitFile: splitFile, level: f.Level})
2251 : }
2252 : }
2253 2 : if err != nil {
2254 0 : d.mu.versions.logUnlock()
2255 0 : return nil, err
2256 0 : }
2257 2 : if isShared && f.Level < sharedLevelsStart {
2258 0 : panic(fmt.Sprintf("cannot slot a shared file higher than the highest shared level: %d < %d",
2259 0 : f.Level, sharedLevelsStart))
2260 : }
2261 2 : f.Meta = m
2262 2 : levelMetrics := metrics[f.Level]
2263 2 : if levelMetrics == nil {
2264 2 : levelMetrics = &LevelMetrics{}
2265 2 : metrics[f.Level] = levelMetrics
2266 2 : }
2267 2 : levelMetrics.NumFiles++
2268 2 : levelMetrics.Size += int64(m.Size)
2269 2 : levelMetrics.BytesIngested += m.Size
2270 2 : levelMetrics.TablesIngested++
2271 : }
2272 : // replacedFiles maps files excised due to exciseSpan (or splitFiles returned
2273 : // by ingestTargetLevel), to files that were created to replace it. This map
2274 : // is used to resolve references to split files in filesToSplit, as it is
2275 : // possible for a file that we want to split to no longer exist or have a
2276 : // newer fileMetadata due to a split induced by another ingestion file, or an
2277 : // excise.
2278 2 : replacedFiles := make(map[base.FileNum][]newFileEntry)
2279 2 : updateLevelMetricsOnExcise := func(m *fileMetadata, level int, added []newFileEntry) {
2280 2 : levelMetrics := metrics[level]
2281 2 : if levelMetrics == nil {
2282 2 : levelMetrics = &LevelMetrics{}
2283 2 : metrics[level] = levelMetrics
2284 2 : }
2285 2 : levelMetrics.NumFiles--
2286 2 : levelMetrics.Size -= int64(m.Size)
2287 2 : for i := range added {
2288 2 : levelMetrics.NumFiles++
2289 2 : levelMetrics.Size += int64(added[i].Meta.Size)
2290 2 : }
2291 : }
2292 2 : if exciseSpan.Valid() {
2293 2 : // Iterate through all levels and find files that intersect with exciseSpan.
2294 2 : //
2295 2 : // TODO(bilal): We could drop the DB mutex here as we don't need it for
2296 2 : // excises; we only need to hold the version lock which we already are
2297 2 : // holding. However releasing the DB mutex could mess with the
2298 2 : // ingestTargetLevel calculation that happened above, as it assumed that it
2299 2 : // had a complete view of in-progress compactions that wouldn't change
2300 2 : // until logAndApply is called. If we were to drop the mutex now, we could
2301 2 : // schedule another in-progress compaction that would go into the chosen target
2302 2 : // level and lead to file overlap within level (which would panic in
2303 2 : // logAndApply). We should drop the db mutex here, do the excise, then
2304 2 : // re-grab the DB mutex and rerun just the in-progress compaction check to
2305 2 : // see if any new compactions are conflicting with our chosen target levels
2306 2 : // for files, and if they are, we should signal those compactions to error
2307 2 : // out.
2308 2 : for level := range current.Levels {
2309 2 : overlaps := current.Overlaps(level, exciseSpan.UserKeyBounds())
2310 2 : iter := overlaps.Iter()
2311 2 :
2312 2 : for m := iter.First(); m != nil; m = iter.Next() {
2313 2 : newFiles, err := d.excise(ctx, exciseSpan.UserKeyBounds(), m, ve, level)
2314 2 : if err != nil {
2315 0 : return nil, err
2316 0 : }
2317 :
2318 2 : if _, ok := ve.DeletedFiles[deletedFileEntry{
2319 2 : Level: level,
2320 2 : FileNum: m.FileNum,
2321 2 : }]; !ok {
2322 2 : // We did not excise this file.
2323 2 : continue
2324 : }
2325 2 : replacedFiles[m.FileNum] = newFiles
2326 2 : updateLevelMetricsOnExcise(m, level, newFiles)
2327 : }
2328 : }
2329 : }
2330 2 : if len(filesToSplit) > 0 {
2331 2 : // For the same reasons as the above call to excise, we hold the db mutex
2332 2 : // while calling this method.
2333 2 : if err := d.ingestSplit(ctx, ve, updateLevelMetricsOnExcise, filesToSplit, replacedFiles); err != nil {
2334 0 : return nil, err
2335 0 : }
2336 : }
2337 2 : if len(filesToSplit) > 0 || exciseSpan.Valid() {
2338 2 : for c := range d.mu.compact.inProgress {
2339 2 : if c.versionEditApplied {
2340 1 : continue
2341 : }
2342 : // Check if this compaction overlaps with the excise span. Note that just
2343 : // checking if the inputs individually overlap with the excise span
2344 : // isn't sufficient; for instance, a compaction could have [a,b] and [e,f]
2345 : // as inputs and write it all out as [a,b,e,f] in one sstable. If we're
2346 : // doing a [c,d) excise at the same time as this compaction, we will have
2347 : // to error out the whole compaction as we can't guarantee it hasn't/won't
2348 : // write a file overlapping with the excise span.
2349 2 : if exciseSpan.OverlapsInternalKeyRange(d.cmp, c.smallest, c.largest) {
2350 2 : c.cancel.Store(true)
2351 2 : }
2352 : // Check if this compaction's inputs have been replaced due to an
2353 : // ingest-time split. In that case, cancel the compaction as a newly picked
2354 : // compaction would need to include any new files that slid in between
2355 : // previously-existing files. Note that we cancel any compaction that has a
2356 : // file that was ingest-split as an input, even if it started before this
2357 : // ingestion.
2358 2 : if checkCompactions {
2359 1 : for i := range c.inputs {
2360 1 : iter := c.inputs[i].files.Iter()
2361 1 : for f := iter.First(); f != nil; f = iter.Next() {
2362 1 : if _, ok := replacedFiles[f.FileNum]; ok {
2363 1 : c.cancel.Store(true)
2364 1 : break
2365 : }
2366 : }
2367 : }
2368 : }
2369 : }
2370 : }
2371 :
2372 2 : if err := d.mu.versions.logAndApply(jobID, ve, metrics, false /* forceRotation */, func() []compactionInfo {
2373 2 : return d.getInProgressCompactionInfoLocked(nil)
2374 2 : }); err != nil {
2375 1 : // Note: any error during logAndApply is fatal; this won't be reachable in production.
2376 1 : return nil, err
2377 1 : }
2378 :
2379 : // Check for any EventuallyFileOnlySnapshots that could be watching for
2380 : // an excise on this span. There should be none as the
2381 : // computePossibleOverlaps steps should have forced these EFOS to transition
2382 : // to file-only snapshots by now. If we see any that conflict with this
2383 : // excise, panic.
2384 2 : if exciseSpan.Valid() {
2385 2 : for s := d.mu.snapshots.root.next; s != &d.mu.snapshots.root; s = s.next {
2386 1 : // Skip non-EFOS snapshots, and also skip any EFOS that were created
2387 1 : // *after* the excise.
2388 1 : if s.efos == nil || base.Visible(exciseSeqNum, s.efos.seqNum, base.SeqNumMax) {
2389 0 : continue
2390 : }
2391 1 : efos := s.efos
2392 1 : // TODO(bilal): We can make this faster by taking advantage of the sorted
2393 1 : // nature of protectedRanges to do a sort.Search, or even maintaining a
2394 1 : // global list of all protected ranges instead of having to peer into every
2395 1 : // snapshot.
2396 1 : for i := range efos.protectedRanges {
2397 1 : if efos.protectedRanges[i].OverlapsKeyRange(d.cmp, exciseSpan) {
2398 0 : panic("unexpected excise of an EventuallyFileOnlySnapshot's bounds")
2399 : }
2400 : }
2401 : }
2402 : }
2403 :
2404 2 : d.mu.versions.metrics.Ingest.Count++
2405 2 :
2406 2 : d.updateReadStateLocked(d.opts.DebugCheck)
2407 2 : // updateReadStateLocked could have generated obsolete tables, schedule a
2408 2 : // cleanup job if necessary.
2409 2 : d.deleteObsoleteFiles(jobID)
2410 2 : d.updateTableStatsLocked(ve.NewFiles)
2411 2 : // The ingestion may have pushed a level over the threshold for compaction,
2412 2 : // so check to see if one is necessary and schedule it.
2413 2 : d.maybeScheduleCompaction()
2414 2 : var toValidate []manifest.NewFileEntry
2415 2 : dedup := make(map[base.DiskFileNum]struct{})
2416 2 : for _, entry := range ve.NewFiles {
2417 2 : if _, ok := dedup[entry.Meta.FileBacking.DiskFileNum]; !ok {
2418 2 : toValidate = append(toValidate, entry)
2419 2 : dedup[entry.Meta.FileBacking.DiskFileNum] = struct{}{}
2420 2 : }
2421 : }
2422 2 : d.maybeValidateSSTablesLocked(toValidate)
2423 2 : return ve, nil
2424 : }
2425 :
2426 : // maybeValidateSSTablesLocked adds the slice of newFileEntrys to the pending
2427 : // queue of files to be validated, when the feature is enabled.
2428 : //
2429 : // Note that if two entries with the same backing file are added twice, then the
2430 : // block checksums for the backing file will be validated twice.
2431 : //
2432 : // DB.mu must be locked when calling.
2433 2 : func (d *DB) maybeValidateSSTablesLocked(newFiles []newFileEntry) {
2434 2 : // Only add to the validation queue when the feature is enabled.
2435 2 : if !d.opts.Experimental.ValidateOnIngest {
2436 2 : return
2437 2 : }
2438 :
2439 2 : d.mu.tableValidation.pending = append(d.mu.tableValidation.pending, newFiles...)
2440 2 : if d.shouldValidateSSTablesLocked() {
2441 2 : go d.validateSSTables()
2442 2 : }
2443 : }
2444 :
2445 : // shouldValidateSSTablesLocked returns true if SSTable validation should run.
2446 : // DB.mu must be locked when calling.
2447 2 : func (d *DB) shouldValidateSSTablesLocked() bool {
2448 2 : return !d.mu.tableValidation.validating &&
2449 2 : d.closed.Load() == nil &&
2450 2 : d.opts.Experimental.ValidateOnIngest &&
2451 2 : len(d.mu.tableValidation.pending) > 0
2452 2 : }
2453 :
2454 : // validateSSTables runs a round of validation on the tables in the pending
2455 : // queue.
2456 2 : func (d *DB) validateSSTables() {
2457 2 : d.mu.Lock()
2458 2 : if !d.shouldValidateSSTablesLocked() {
2459 2 : d.mu.Unlock()
2460 2 : return
2461 2 : }
2462 :
2463 2 : pending := d.mu.tableValidation.pending
2464 2 : d.mu.tableValidation.pending = nil
2465 2 : d.mu.tableValidation.validating = true
2466 2 : jobID := d.newJobIDLocked()
2467 2 : rs := d.loadReadState()
2468 2 :
2469 2 : // Drop DB.mu before performing IO.
2470 2 : d.mu.Unlock()
2471 2 :
2472 2 : // Validate all tables in the pending queue. This could lead to a situation
2473 2 : // where we are starving IO from other tasks due to having to page through
2474 2 : // all the blocks in all the sstables in the queue.
2475 2 : // TODO(travers): Add some form of pacing to avoid IO starvation.
2476 2 :
2477 2 : // If we fail to validate any files due to reasons other than uncovered
2478 2 : // corruption, accumulate them and re-queue them for another attempt.
2479 2 : var retry []manifest.NewFileEntry
2480 2 :
2481 2 : for _, f := range pending {
2482 2 : // The file may have been moved or deleted since it was ingested, in
2483 2 : // which case we skip.
2484 2 : if !rs.current.Contains(f.Level, f.Meta) {
2485 2 : // Assume the file was moved to a lower level. It is rare enough
2486 2 : // that a table is moved or deleted between the time it was ingested
2487 2 : // and the time the validation routine runs that the overall cost of
2488 2 : // this inner loop is tolerably low, when amortized over all
2489 2 : // ingested tables.
2490 2 : found := false
2491 2 : for i := f.Level + 1; i < numLevels; i++ {
2492 2 : if rs.current.Contains(i, f.Meta) {
2493 1 : found = true
2494 1 : break
2495 : }
2496 : }
2497 2 : if !found {
2498 2 : continue
2499 : }
2500 : }
2501 :
2502 2 : var err error
2503 2 : if f.Meta.Virtual {
2504 2 : err = d.tableCache.withVirtualReader(
2505 2 : f.Meta.VirtualMeta(), func(v sstable.VirtualReader) error {
2506 2 : return v.ValidateBlockChecksumsOnBacking()
2507 2 : })
2508 2 : } else {
2509 2 : err = d.tableCache.withReader(
2510 2 : f.Meta.PhysicalMeta(), func(r *sstable.Reader) error {
2511 2 : return r.ValidateBlockChecksums()
2512 2 : })
2513 : }
2514 :
2515 2 : if err != nil {
2516 1 : if IsCorruptionError(err) {
2517 1 : // TODO(travers): Hook into the corruption reporting pipeline, once
2518 1 : // available. See pebble#1192.
2519 1 : d.opts.Logger.Fatalf("pebble: encountered corruption during ingestion: %s", err)
2520 1 : } else {
2521 1 : // If there was some other, possibly transient, error that
2522 1 : // caused table validation to fail inform the EventListener and
2523 1 : // move on. We remember the table so that we can retry it in a
2524 1 : // subsequent table validation job.
2525 1 : //
2526 1 : // TODO(jackson): If the error is not transient, this will retry
2527 1 : // validation indefinitely. While not great, it's the same
2528 1 : // behavior as erroring flushes and compactions. We should
2529 1 : // address this as a part of #270.
2530 1 : d.opts.EventListener.BackgroundError(err)
2531 1 : retry = append(retry, f)
2532 1 : continue
2533 : }
2534 : }
2535 :
2536 2 : d.opts.EventListener.TableValidated(TableValidatedInfo{
2537 2 : JobID: int(jobID),
2538 2 : Meta: f.Meta,
2539 2 : })
2540 : }
2541 2 : rs.unref()
2542 2 : d.mu.Lock()
2543 2 : defer d.mu.Unlock()
2544 2 : d.mu.tableValidation.pending = append(d.mu.tableValidation.pending, retry...)
2545 2 : d.mu.tableValidation.validating = false
2546 2 : d.mu.tableValidation.cond.Broadcast()
2547 2 : if d.shouldValidateSSTablesLocked() {
2548 2 : go d.validateSSTables()
2549 2 : }
2550 : }
|