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