Line data Source code
1 : // Copyright 2022 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 : "sort"
11 :
12 : "github.com/cockroachdb/errors"
13 : "github.com/cockroachdb/pebble/internal/base"
14 : "github.com/cockroachdb/pebble/internal/keyspan"
15 : "github.com/cockroachdb/pebble/internal/manifest"
16 : "github.com/cockroachdb/pebble/sstable"
17 : )
18 :
19 : // ExternalIterOption provide an interface to specify open-time options to
20 : // NewExternalIter.
21 : type ExternalIterOption interface {
22 : // iterApply is called on the iterator during opening in order to set internal
23 : // parameters.
24 : iterApply(*Iterator)
25 : // readerOptions returns any reader options added by this iter option.
26 : readerOptions() []sstable.ReaderOption
27 : }
28 :
29 : type externalIterReaderOptions struct {
30 : opts []sstable.ReaderOption
31 : }
32 :
33 0 : func (e *externalIterReaderOptions) iterApply(iterator *Iterator) {
34 0 : // Do nothing.
35 0 : }
36 :
37 0 : func (e *externalIterReaderOptions) readerOptions() []sstable.ReaderOption {
38 0 : return e.opts
39 0 : }
40 :
41 : // ExternalIterReaderOptions returns an ExternalIterOption that specifies
42 : // sstable.ReaderOptions to be applied on sstable readers in NewExternalIter.
43 0 : func ExternalIterReaderOptions(opts ...sstable.ReaderOption) ExternalIterOption {
44 0 : return &externalIterReaderOptions{opts: opts}
45 0 : }
46 :
47 : // NewExternalIter takes an input 2d array of sstable files which may overlap
48 : // across subarrays but not within a subarray (at least as far as points are
49 : // concerned; range keys are allowed to overlap arbitrarily even within a
50 : // subarray), and returns an Iterator over the merged contents of the sstables.
51 : // Input sstables may contain point keys, range keys, range deletions, etc. The
52 : // input files slice must be sorted in reverse chronological ordering. A key in a
53 : // file at a lower index subarray will shadow a key with an identical user key
54 : // contained within a file at a higher index subarray. Each subarray must be
55 : // sorted in internal key order, where lower index files contain keys that sort
56 : // left of files with higher indexes.
57 : //
58 : // Input sstables must only contain keys with the zero sequence number.
59 : //
60 : // Iterators constructed through NewExternalIter do not support all iterator
61 : // options, including block-property and table filters. NewExternalIter errors
62 : // if an incompatible option is set.
63 : func NewExternalIter(
64 : o *Options,
65 : iterOpts *IterOptions,
66 : files [][]sstable.ReadableFile,
67 : extraOpts ...ExternalIterOption,
68 1 : ) (it *Iterator, err error) {
69 1 : return NewExternalIterWithContext(context.Background(), o, iterOpts, files, extraOpts...)
70 1 : }
71 :
72 : // NewExternalIterWithContext is like NewExternalIter, and additionally
73 : // accepts a context for tracing.
74 : func NewExternalIterWithContext(
75 : ctx context.Context,
76 : o *Options,
77 : iterOpts *IterOptions,
78 : files [][]sstable.ReadableFile,
79 : extraOpts ...ExternalIterOption,
80 1 : ) (it *Iterator, err error) {
81 1 : if iterOpts != nil {
82 1 : if err := validateExternalIterOpts(iterOpts); err != nil {
83 0 : return nil, err
84 0 : }
85 : }
86 :
87 1 : var readers [][]*sstable.Reader
88 1 :
89 1 : seqNumOffset := 0
90 1 : var extraReaderOpts []sstable.ReaderOption
91 1 : for i := range extraOpts {
92 0 : extraReaderOpts = append(extraReaderOpts, extraOpts[i].readerOptions()...)
93 0 : }
94 1 : for _, levelFiles := range files {
95 1 : seqNumOffset += len(levelFiles)
96 1 : }
97 1 : for _, levelFiles := range files {
98 1 : seqNumOffset -= len(levelFiles)
99 1 : subReaders, err := openExternalTables(o, levelFiles, seqNumOffset, o.MakeReaderOptions(), extraReaderOpts...)
100 1 : readers = append(readers, subReaders)
101 1 : if err != nil {
102 0 : // Close all the opened readers.
103 0 : for i := range readers {
104 0 : for j := range readers[i] {
105 0 : _ = readers[i][j].Close()
106 0 : }
107 : }
108 0 : return nil, err
109 : }
110 : }
111 :
112 1 : buf := iterAllocPool.Get().(*iterAlloc)
113 1 : dbi := &buf.dbi
114 1 : *dbi = Iterator{
115 1 : ctx: ctx,
116 1 : alloc: buf,
117 1 : merge: o.Merger.Merge,
118 1 : comparer: *o.Comparer,
119 1 : readState: nil,
120 1 : keyBuf: buf.keyBuf,
121 1 : prefixOrFullSeekKey: buf.prefixOrFullSeekKey,
122 1 : boundsBuf: buf.boundsBuf,
123 1 : batch: nil,
124 1 : // Add the readers to the Iterator so that Close closes them, and
125 1 : // SetOptions can re-construct iterators from them.
126 1 : externalReaders: readers,
127 1 : newIters: func(context.Context, *manifest.FileMetadata, *IterOptions,
128 1 : internalIterOpts, iterKinds) (iterSet, error) {
129 0 : // NB: External iterators are currently constructed without any
130 0 : // `levelIters`. newIters should never be called. When we support
131 0 : // organizing multiple non-overlapping files into a single level
132 0 : // (see TODO below), we'll need to adjust this tableNewIters
133 0 : // implementation to open iterators by looking up f in a map
134 0 : // of readers indexed by *fileMetadata.
135 0 : panic("unreachable")
136 : },
137 : seqNum: base.InternalKeySeqNumMax,
138 : }
139 1 : if iterOpts != nil {
140 1 : dbi.opts = *iterOpts
141 1 : dbi.processBounds(iterOpts.LowerBound, iterOpts.UpperBound)
142 1 : }
143 1 : for i := range extraOpts {
144 0 : extraOpts[i].iterApply(dbi)
145 0 : }
146 1 : if err := finishInitializingExternal(ctx, dbi); err != nil {
147 0 : dbi.Close()
148 0 : return nil, err
149 0 : }
150 1 : return dbi, nil
151 : }
152 :
153 1 : func validateExternalIterOpts(iterOpts *IterOptions) error {
154 1 : switch {
155 0 : case iterOpts.TableFilter != nil:
156 0 : return errors.Errorf("pebble: external iterator: TableFilter unsupported")
157 0 : case iterOpts.PointKeyFilters != nil:
158 0 : return errors.Errorf("pebble: external iterator: PointKeyFilters unsupported")
159 0 : case iterOpts.RangeKeyFilters != nil:
160 0 : return errors.Errorf("pebble: external iterator: RangeKeyFilters unsupported")
161 0 : case iterOpts.OnlyReadGuaranteedDurable:
162 0 : return errors.Errorf("pebble: external iterator: OnlyReadGuaranteedDurable unsupported")
163 0 : case iterOpts.UseL6Filters:
164 0 : return errors.Errorf("pebble: external iterator: UseL6Filters unsupported")
165 : }
166 1 : return nil
167 : }
168 :
169 1 : func createExternalPointIter(ctx context.Context, it *Iterator) (internalIterator, error) {
170 1 : // TODO(jackson): In some instances we could generate fewer levels by using
171 1 : // L0Sublevels code to organize nonoverlapping files into the same level.
172 1 : // This would allow us to use levelIters and keep a smaller set of data and
173 1 : // files in-memory. However, it would also require us to identify the bounds
174 1 : // of all the files upfront.
175 1 :
176 1 : if !it.opts.pointKeys() {
177 0 : return emptyIter, nil
178 1 : } else if it.pointIter != nil {
179 1 : return it.pointIter, nil
180 1 : }
181 1 : mlevels := it.alloc.mlevels[:0]
182 1 :
183 1 : if len(it.externalReaders) > cap(mlevels) {
184 0 : mlevels = make([]mergingIterLevel, 0, len(it.externalReaders))
185 0 : }
186 1 : for _, readers := range it.externalReaders {
187 1 : var combinedIters []internalIterator
188 1 : for _, r := range readers {
189 1 : var (
190 1 : rangeDelIter keyspan.FragmentIterator
191 1 : pointIter internalIterator
192 1 : err error
193 1 : )
194 1 : // We could set hideObsoletePoints=true, since we are reading at
195 1 : // InternalKeySeqNumMax, but we don't bother since these sstables should
196 1 : // not have obsolete points (so the performance optimization is
197 1 : // unnecessary), and we don't want to bother constructing a
198 1 : // BlockPropertiesFilterer that includes obsoleteKeyBlockPropertyFilter.
199 1 : pointIter, err = r.NewIterWithBlockPropertyFiltersAndContextEtc(
200 1 : ctx, it.opts.LowerBound, it.opts.UpperBound, nil, /* BlockPropertiesFilterer */
201 1 : false /* hideObsoletePoints */, false, /* useFilterBlock */
202 1 : &it.stats.InternalStats, it.opts.CategoryAndQoS, nil,
203 1 : sstable.TrivialReaderProvider{Reader: r})
204 1 : if err != nil {
205 0 : return nil, err
206 0 : }
207 1 : rangeDelIter, err = r.NewRawRangeDelIter()
208 1 : if err != nil {
209 0 : return nil, err
210 0 : }
211 1 : mlevels = append(mlevels, mergingIterLevel{
212 1 : iter: pointIter,
213 1 : rangeDelIter: rangeDelIter,
214 1 : })
215 : }
216 1 : if len(combinedIters) == 1 {
217 0 : mlevels = append(mlevels, mergingIterLevel{
218 0 : iter: combinedIters[0],
219 0 : })
220 1 : } else if len(combinedIters) > 1 {
221 0 : sli := &simpleLevelIter{
222 0 : cmp: it.cmp,
223 0 : iters: combinedIters,
224 0 : }
225 0 : sli.init(it.opts)
226 0 : mlevels = append(mlevels, mergingIterLevel{
227 0 : iter: sli,
228 0 : rangeDelIter: nil,
229 0 : })
230 0 : }
231 : }
232 1 : if len(mlevels) == 1 && mlevels[0].rangeDelIter == nil {
233 1 : // Set closePointIterOnce to true. This is because we're bypassing the
234 1 : // merging iter, which turns Close()s on it idempotent for any child
235 1 : // iterators. The outer Iterator could call Close() on a point iter twice,
236 1 : // which sstable iterators do not support (as they release themselves to
237 1 : // a pool).
238 1 : it.closePointIterOnce = true
239 1 : return mlevels[0].iter, nil
240 1 : }
241 :
242 1 : it.alloc.merging.init(&it.opts, &it.stats.InternalStats, it.comparer.Compare, it.comparer.Split, mlevels...)
243 1 : it.alloc.merging.snapshot = base.InternalKeySeqNumMax
244 1 : if len(mlevels) <= cap(it.alloc.levelsPositioned) {
245 1 : it.alloc.merging.levelsPositioned = it.alloc.levelsPositioned[:len(mlevels)]
246 1 : }
247 1 : return &it.alloc.merging, nil
248 : }
249 :
250 1 : func finishInitializingExternal(ctx context.Context, it *Iterator) error {
251 1 : pointIter, err := createExternalPointIter(ctx, it)
252 1 : if err != nil {
253 0 : return err
254 0 : }
255 1 : it.pointIter = pointIter
256 1 : it.iter = it.pointIter
257 1 :
258 1 : if it.opts.rangeKeys() {
259 1 : it.rangeKeyMasking.init(it, it.comparer.Compare, it.comparer.Split)
260 1 : var rangeKeyIters []keyspan.FragmentIterator
261 1 : if it.rangeKey == nil {
262 1 : // We could take advantage of the lack of overlaps in range keys within
263 1 : // each slice in it.externalReaders, and generate keyspan.LevelIters
264 1 : // out of those. However, since range keys are expected to be sparse to
265 1 : // begin with, the performance gain might not be significant enough to
266 1 : // warrant it.
267 1 : //
268 1 : // TODO(bilal): Explore adding a simpleRangeKeyLevelIter that does not
269 1 : // operate on FileMetadatas (similar to simpleLevelIter), and implements
270 1 : // this optimization.
271 1 : for _, readers := range it.externalReaders {
272 1 : for _, r := range readers {
273 1 : if rki, err := r.NewRawRangeKeyIter(); err != nil {
274 0 : return err
275 1 : } else if rki != nil {
276 1 : rangeKeyIters = append(rangeKeyIters, rki)
277 1 : }
278 : }
279 : }
280 1 : if len(rangeKeyIters) > 0 {
281 1 : it.rangeKey = iterRangeKeyStateAllocPool.Get().(*iteratorRangeKeyState)
282 1 : it.rangeKey.init(it.comparer.Compare, it.comparer.Split, &it.opts)
283 1 : it.rangeKey.rangeKeyIter = it.rangeKey.iterConfig.Init(
284 1 : &it.comparer,
285 1 : base.InternalKeySeqNumMax,
286 1 : it.opts.LowerBound, it.opts.UpperBound,
287 1 : &it.hasPrefix, &it.prefixOrFullSeekKey,
288 1 : false /* internalKeys */, &it.rangeKey.internal,
289 1 : )
290 1 : for i := range rangeKeyIters {
291 1 : it.rangeKey.iterConfig.AddLevel(rangeKeyIters[i])
292 1 : }
293 : }
294 : }
295 1 : if it.rangeKey != nil {
296 1 : it.rangeKey.iiter.Init(&it.comparer, it.iter, it.rangeKey.rangeKeyIter,
297 1 : keyspan.InterleavingIterOpts{
298 1 : Mask: &it.rangeKeyMasking,
299 1 : LowerBound: it.opts.LowerBound,
300 1 : UpperBound: it.opts.UpperBound,
301 1 : })
302 1 : it.iter = &it.rangeKey.iiter
303 1 : }
304 : }
305 1 : return nil
306 : }
307 :
308 : func openExternalTables(
309 : o *Options,
310 : files []sstable.ReadableFile,
311 : seqNumOffset int,
312 : readerOpts sstable.ReaderOptions,
313 : extraReaderOpts ...sstable.ReaderOption,
314 1 : ) (readers []*sstable.Reader, err error) {
315 1 : readers = make([]*sstable.Reader, 0, len(files))
316 1 : for i := range files {
317 1 : readable, err := sstable.NewSimpleReadable(files[i])
318 1 : if err != nil {
319 0 : return readers, err
320 0 : }
321 1 : r, err := sstable.NewReader(readable, readerOpts, extraReaderOpts...)
322 1 : if err != nil {
323 0 : return readers, err
324 0 : }
325 : // Use the index of the file in files as the sequence number for all of
326 : // its keys.
327 1 : r.Properties.GlobalSeqNum = uint64(len(files) - i + seqNumOffset)
328 1 : readers = append(readers, r)
329 : }
330 1 : return readers, err
331 : }
332 :
333 : // simpleLevelIter is similar to a levelIter in that it merges the points
334 : // from multiple point iterators that are non-overlapping in the key ranges
335 : // they return. It is only expected to support forward iteration and forward
336 : // regular seeking; reverse iteration and prefix seeking is not supported.
337 : // Intended to be a low-overhead, non-FileMetadata dependent option for
338 : // NewExternalIter. To optimize seeking and forward iteration, it maintains
339 : // two slices of child iterators; one of all iterators, and a subset of it that
340 : // contains just the iterators that contain point keys within the current
341 : // bounds.
342 : //
343 : // Note that this levelIter does not support pausing at file boundaries
344 : // in case of range tombstones in this file that could apply to points outside
345 : // of this file (and outside of this level). This is sufficient for optimizing
346 : // the main use cases of NewExternalIter, however for completeness it would make
347 : // sense to build this pausing functionality in.
348 : type simpleLevelIter struct {
349 : cmp Compare
350 : err error
351 : lowerBound []byte
352 : iters []internalIterator
353 : filtered []internalIterator
354 : firstKeys [][]byte
355 : firstKeysBuf []byte
356 : currentIdx int
357 : }
358 :
359 : var _ internalIterator = &simpleLevelIter{}
360 :
361 : // init initializes this simpleLevelIter.
362 1 : func (s *simpleLevelIter) init(opts IterOptions) {
363 1 : s.currentIdx = 0
364 1 : s.lowerBound = opts.LowerBound
365 1 : s.resetFilteredIters()
366 1 : }
367 :
368 1 : func (s *simpleLevelIter) resetFilteredIters() {
369 1 : s.filtered = s.filtered[:0]
370 1 : s.firstKeys = s.firstKeys[:0]
371 1 : s.firstKeysBuf = s.firstKeysBuf[:0]
372 1 : s.err = nil
373 1 : for i := range s.iters {
374 1 : var iterKey *base.InternalKey
375 1 : if s.lowerBound != nil {
376 0 : iterKey, _ = s.iters[i].SeekGE(s.lowerBound, base.SeekGEFlagsNone)
377 1 : } else {
378 1 : iterKey, _ = s.iters[i].First()
379 1 : }
380 1 : if iterKey != nil {
381 1 : s.filtered = append(s.filtered, s.iters[i])
382 1 : bufStart := len(s.firstKeysBuf)
383 1 : s.firstKeysBuf = append(s.firstKeysBuf, iterKey.UserKey...)
384 1 : s.firstKeys = append(s.firstKeys, s.firstKeysBuf[bufStart:bufStart+len(iterKey.UserKey)])
385 1 : } else if err := s.iters[i].Error(); err != nil {
386 1 : s.err = err
387 1 : }
388 : }
389 : }
390 :
391 : func (s *simpleLevelIter) SeekGE(
392 : key []byte, flags base.SeekGEFlags,
393 1 : ) (*base.InternalKey, base.LazyValue) {
394 1 : if s.err != nil {
395 0 : return nil, base.LazyValue{}
396 0 : }
397 : // Find the first file that is entirely >= key. The file before that could
398 : // contain the key we're looking for.
399 1 : n := sort.Search(len(s.firstKeys), func(i int) bool {
400 1 : return s.cmp(key, s.firstKeys[i]) <= 0
401 1 : })
402 1 : if n > 0 {
403 1 : s.currentIdx = n - 1
404 1 : } else {
405 1 : s.currentIdx = n
406 1 : }
407 1 : if s.currentIdx < len(s.filtered) {
408 1 : if iterKey, val := s.filtered[s.currentIdx].SeekGE(key, flags); iterKey != nil {
409 1 : return iterKey, val
410 1 : }
411 1 : if err := s.filtered[s.currentIdx].Error(); err != nil {
412 0 : s.err = err
413 0 : }
414 1 : s.currentIdx++
415 : }
416 1 : return s.skipEmptyFileForward(key, flags)
417 : }
418 :
419 : func (s *simpleLevelIter) skipEmptyFileForward(
420 : seekKey []byte, flags base.SeekGEFlags,
421 1 : ) (*base.InternalKey, base.LazyValue) {
422 1 : var iterKey *base.InternalKey
423 1 : var val base.LazyValue
424 1 : for s.currentIdx >= 0 && s.currentIdx < len(s.filtered) && s.err == nil {
425 1 : if seekKey != nil {
426 1 : iterKey, val = s.filtered[s.currentIdx].SeekGE(seekKey, flags)
427 1 : } else if s.lowerBound != nil {
428 0 : iterKey, val = s.filtered[s.currentIdx].SeekGE(s.lowerBound, flags)
429 1 : } else {
430 1 : iterKey, val = s.filtered[s.currentIdx].First()
431 1 : }
432 1 : if iterKey != nil {
433 1 : return iterKey, val
434 1 : }
435 0 : if err := s.filtered[s.currentIdx].Error(); err != nil {
436 0 : s.err = err
437 0 : }
438 0 : s.currentIdx++
439 : }
440 1 : return nil, base.LazyValue{}
441 : }
442 :
443 : func (s *simpleLevelIter) SeekPrefixGE(
444 : prefix, key []byte, flags base.SeekGEFlags,
445 0 : ) (*base.InternalKey, base.LazyValue) {
446 0 : panic("unimplemented")
447 : }
448 :
449 : func (s *simpleLevelIter) SeekLT(
450 : key []byte, flags base.SeekLTFlags,
451 0 : ) (*base.InternalKey, base.LazyValue) {
452 0 : panic("unimplemented")
453 : }
454 :
455 1 : func (s *simpleLevelIter) First() (*base.InternalKey, base.LazyValue) {
456 1 : if s.err != nil {
457 1 : return nil, base.LazyValue{}
458 1 : }
459 1 : s.currentIdx = 0
460 1 : return s.skipEmptyFileForward(nil /* seekKey */, base.SeekGEFlagsNone)
461 : }
462 :
463 0 : func (s *simpleLevelIter) Last() (*base.InternalKey, base.LazyValue) {
464 0 : panic("unimplemented")
465 : }
466 :
467 1 : func (s *simpleLevelIter) Next() (*base.InternalKey, base.LazyValue) {
468 1 : if s.err != nil {
469 0 : return nil, base.LazyValue{}
470 0 : }
471 1 : if s.currentIdx < 0 || s.currentIdx >= len(s.filtered) {
472 1 : return nil, base.LazyValue{}
473 1 : }
474 1 : if iterKey, val := s.filtered[s.currentIdx].Next(); iterKey != nil {
475 1 : return iterKey, val
476 1 : }
477 1 : s.currentIdx++
478 1 : return s.skipEmptyFileForward(nil /* seekKey */, base.SeekGEFlagsNone)
479 : }
480 :
481 0 : func (s *simpleLevelIter) NextPrefix(succKey []byte) (*base.InternalKey, base.LazyValue) {
482 0 : if s.err != nil {
483 0 : return nil, base.LazyValue{}
484 0 : }
485 0 : if s.currentIdx < 0 || s.currentIdx >= len(s.filtered) {
486 0 : return nil, base.LazyValue{}
487 0 : }
488 0 : if iterKey, val := s.filtered[s.currentIdx].NextPrefix(succKey); iterKey != nil {
489 0 : return iterKey, val
490 0 : }
491 0 : s.currentIdx++
492 0 : return s.skipEmptyFileForward(succKey /* seekKey */, base.SeekGEFlagsNone)
493 : }
494 :
495 0 : func (s *simpleLevelIter) Prev() (*base.InternalKey, base.LazyValue) {
496 0 : panic("unimplemented")
497 : }
498 :
499 1 : func (s *simpleLevelIter) Error() error {
500 1 : if s.currentIdx >= 0 && s.currentIdx < len(s.filtered) {
501 0 : s.err = firstError(s.err, s.filtered[s.currentIdx].Error())
502 0 : }
503 1 : return s.err
504 : }
505 :
506 1 : func (s *simpleLevelIter) Close() error {
507 1 : var err error
508 1 : for i := range s.iters {
509 1 : err = firstError(err, s.iters[i].Close())
510 1 : }
511 1 : return err
512 : }
513 :
514 0 : func (s *simpleLevelIter) SetBounds(lower, upper []byte) {
515 0 : s.currentIdx = -1
516 0 : s.lowerBound = lower
517 0 : for i := range s.iters {
518 0 : s.iters[i].SetBounds(lower, upper)
519 0 : }
520 0 : s.resetFilteredIters()
521 : }
522 :
523 0 : func (s *simpleLevelIter) SetContext(_ context.Context) {}
524 :
525 0 : func (s *simpleLevelIter) String() string {
526 0 : if s.currentIdx < 0 || s.currentIdx >= len(s.filtered) {
527 0 : return "simpleLevelIter: current=<nil>"
528 0 : }
529 0 : return fmt.Sprintf("simpleLevelIter: current=%s", s.filtered[s.currentIdx])
530 : }
531 :
532 : var _ internalIterator = &simpleLevelIter{}
|