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