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 :
10 : "github.com/cockroachdb/errors"
11 : "github.com/cockroachdb/pebble/internal/base"
12 : "github.com/cockroachdb/pebble/internal/keyspan"
13 : "github.com/cockroachdb/pebble/internal/manifest"
14 : "github.com/cockroachdb/pebble/sstable"
15 : )
16 :
17 : // NewExternalIter takes an input 2d array of sstable files which may overlap
18 : // across subarrays but not within a subarray (at least as far as points are
19 : // concerned; range keys are allowed to overlap arbitrarily even within a
20 : // subarray), and returns an Iterator over the merged contents of the sstables.
21 : // Input sstables may contain point keys, range keys, range deletions, etc. The
22 : // input files slice must be sorted in reverse chronological ordering. A key in a
23 : // file at a lower index subarray will shadow a key with an identical user key
24 : // contained within a file at a higher index subarray. Each subarray must be
25 : // sorted in internal key order, where lower index files contain keys that sort
26 : // left of files with higher indexes.
27 : //
28 : // Input sstables must only contain keys with the zero sequence number.
29 : //
30 : // Iterators constructed through NewExternalIter do not support all iterator
31 : // options, including block-property and table filters. NewExternalIter errors
32 : // if an incompatible option is set.
33 : func NewExternalIter(
34 : o *Options, iterOpts *IterOptions, files [][]sstable.ReadableFile,
35 0 : ) (it *Iterator, err error) {
36 0 : return NewExternalIterWithContext(context.Background(), o, iterOpts, files)
37 0 : }
38 :
39 : // NewExternalIterWithContext is like NewExternalIter, and additionally
40 : // accepts a context for tracing.
41 : func NewExternalIterWithContext(
42 : ctx context.Context, o *Options, iterOpts *IterOptions, files [][]sstable.ReadableFile,
43 0 : ) (it *Iterator, err error) {
44 0 : if iterOpts != nil {
45 0 : if err := validateExternalIterOpts(iterOpts); err != nil {
46 0 : return nil, err
47 0 : }
48 : }
49 :
50 0 : var readers [][]*sstable.Reader
51 0 :
52 0 : seqNumOffset := 0
53 0 : for _, levelFiles := range files {
54 0 : seqNumOffset += len(levelFiles)
55 0 : }
56 0 : for _, levelFiles := range files {
57 0 : seqNumOffset -= len(levelFiles)
58 0 : subReaders, err := openExternalTables(ctx, o, levelFiles, seqNumOffset, o.MakeReaderOptions())
59 0 : readers = append(readers, subReaders)
60 0 : if err != nil {
61 0 : // Close all the opened readers.
62 0 : for i := range readers {
63 0 : for j := range readers[i] {
64 0 : _ = readers[i][j].Close()
65 0 : }
66 : }
67 0 : return nil, err
68 : }
69 : }
70 :
71 0 : buf := iterAllocPool.Get().(*iterAlloc)
72 0 : dbi := &buf.dbi
73 0 : *dbi = Iterator{
74 0 : ctx: ctx,
75 0 : alloc: buf,
76 0 : merge: o.Merger.Merge,
77 0 : comparer: *o.Comparer,
78 0 : readState: nil,
79 0 : keyBuf: buf.keyBuf,
80 0 : prefixOrFullSeekKey: buf.prefixOrFullSeekKey,
81 0 : boundsBuf: buf.boundsBuf,
82 0 : batch: nil,
83 0 : // Add the readers to the Iterator so that Close closes them, and
84 0 : // SetOptions can re-construct iterators from them.
85 0 : externalReaders: readers,
86 0 : newIters: func(context.Context, *manifest.FileMetadata, *IterOptions,
87 0 : internalIterOpts, iterKinds) (iterSet, error) {
88 0 : // NB: External iterators are currently constructed without any
89 0 : // `levelIters`. newIters should never be called. When we support
90 0 : // organizing multiple non-overlapping files into a single level
91 0 : // (see TODO below), we'll need to adjust this tableNewIters
92 0 : // implementation to open iterators by looking up f in a map
93 0 : // of readers indexed by *fileMetadata.
94 0 : panic("unreachable")
95 : },
96 : seqNum: base.SeqNumMax,
97 : }
98 0 : if iterOpts != nil {
99 0 : dbi.opts = *iterOpts
100 0 : dbi.processBounds(iterOpts.LowerBound, iterOpts.UpperBound)
101 0 : }
102 0 : if err := finishInitializingExternal(ctx, dbi); err != nil {
103 0 : dbi.Close()
104 0 : return nil, err
105 0 : }
106 0 : return dbi, nil
107 : }
108 :
109 0 : func validateExternalIterOpts(iterOpts *IterOptions) error {
110 0 : switch {
111 0 : case iterOpts.TableFilter != nil:
112 0 : return errors.Errorf("pebble: external iterator: TableFilter unsupported")
113 0 : case iterOpts.PointKeyFilters != nil:
114 0 : return errors.Errorf("pebble: external iterator: PointKeyFilters unsupported")
115 0 : case iterOpts.RangeKeyFilters != nil:
116 0 : return errors.Errorf("pebble: external iterator: RangeKeyFilters unsupported")
117 0 : case iterOpts.OnlyReadGuaranteedDurable:
118 0 : return errors.Errorf("pebble: external iterator: OnlyReadGuaranteedDurable unsupported")
119 0 : case iterOpts.UseL6Filters:
120 0 : return errors.Errorf("pebble: external iterator: UseL6Filters unsupported")
121 : }
122 0 : return nil
123 : }
124 :
125 0 : func createExternalPointIter(ctx context.Context, it *Iterator) (topLevelIterator, error) {
126 0 : // TODO(jackson): In some instances we could generate fewer levels by using
127 0 : // L0Sublevels code to organize nonoverlapping files into the same level.
128 0 : // This would allow us to use levelIters and keep a smaller set of data and
129 0 : // files in-memory. However, it would also require us to identify the bounds
130 0 : // of all the files upfront.
131 0 :
132 0 : if !it.opts.pointKeys() {
133 0 : return emptyIter, nil
134 0 : } else if it.pointIter != nil {
135 0 : return it.pointIter, nil
136 0 : }
137 0 : mlevels := it.alloc.mlevels[:0]
138 0 :
139 0 : if len(it.externalReaders) > cap(mlevels) {
140 0 : mlevels = make([]mergingIterLevel, 0, len(it.externalReaders))
141 0 : }
142 : // We set a synthetic sequence number, with lower levels having higer numbers.
143 0 : seqNum := 0
144 0 : for _, readers := range it.externalReaders {
145 0 : seqNum += len(readers)
146 0 : }
147 0 : for _, readers := range it.externalReaders {
148 0 : for _, r := range readers {
149 0 : var (
150 0 : rangeDelIter keyspan.FragmentIterator
151 0 : pointIter internalIterator
152 0 : err error
153 0 : )
154 0 : // We could set hideObsoletePoints=true, since we are reading at
155 0 : // InternalKeySeqNumMax, but we don't bother since these sstables should
156 0 : // not have obsolete points (so the performance optimization is
157 0 : // unnecessary), and we don't want to bother constructing a
158 0 : // BlockPropertiesFilterer that includes obsoleteKeyBlockPropertyFilter.
159 0 : transforms := sstable.IterTransforms{SyntheticSeqNum: sstable.SyntheticSeqNum(seqNum)}
160 0 : seqNum--
161 0 : pointIter, err = r.NewIterWithBlockPropertyFiltersAndContextEtc(
162 0 : ctx, transforms, it.opts.LowerBound, it.opts.UpperBound, nil, /* BlockPropertiesFilterer */
163 0 : false, /* useFilterBlock */
164 0 : &it.stats.InternalStats, it.opts.CategoryAndQoS, nil,
165 0 : sstable.TrivialReaderProvider{Reader: r})
166 0 : if err != nil {
167 0 : return nil, err
168 0 : }
169 0 : rangeDelIter, err = r.NewRawRangeDelIter(ctx, sstable.FragmentIterTransforms{
170 0 : SyntheticSeqNum: sstable.SyntheticSeqNum(seqNum),
171 0 : })
172 0 : if err != nil {
173 0 : return nil, err
174 0 : }
175 0 : mlevels = append(mlevels, mergingIterLevel{
176 0 : iter: pointIter,
177 0 : rangeDelIter: rangeDelIter,
178 0 : })
179 : }
180 : }
181 :
182 0 : it.alloc.merging.init(&it.opts, &it.stats.InternalStats, it.comparer.Compare, it.comparer.Split, mlevels...)
183 0 : it.alloc.merging.snapshot = base.SeqNumMax
184 0 : if len(mlevels) <= cap(it.alloc.levelsPositioned) {
185 0 : it.alloc.merging.levelsPositioned = it.alloc.levelsPositioned[:len(mlevels)]
186 0 : }
187 0 : return &it.alloc.merging, nil
188 : }
189 :
190 0 : func finishInitializingExternal(ctx context.Context, it *Iterator) error {
191 0 : pointIter, err := createExternalPointIter(ctx, it)
192 0 : if err != nil {
193 0 : return err
194 0 : }
195 0 : it.pointIter = pointIter
196 0 : it.iter = it.pointIter
197 0 :
198 0 : if it.opts.rangeKeys() {
199 0 : it.rangeKeyMasking.init(it, it.comparer.Compare, it.comparer.Split)
200 0 : var rangeKeyIters []keyspan.FragmentIterator
201 0 : if it.rangeKey == nil {
202 0 : // We could take advantage of the lack of overlaps in range keys within
203 0 : // each slice in it.externalReaders, and generate keyspanimpl.LevelIters
204 0 : // out of those. However, since range keys are expected to be sparse to
205 0 : // begin with, the performance gain might not be significant enough to
206 0 : // warrant it.
207 0 : //
208 0 : // TODO(bilal): Explore adding a simpleRangeKeyLevelIter that does not
209 0 : // operate on FileMetadatas (similar to simpleLevelIter), and implements
210 0 : // this optimization.
211 0 : // We set a synthetic sequence number, with lower levels having higer numbers.
212 0 : seqNum := 0
213 0 : for _, readers := range it.externalReaders {
214 0 : seqNum += len(readers)
215 0 : }
216 0 : for _, readers := range it.externalReaders {
217 0 : for _, r := range readers {
218 0 : transforms := sstable.FragmentIterTransforms{SyntheticSeqNum: sstable.SyntheticSeqNum(seqNum)}
219 0 : seqNum--
220 0 : if rki, err := r.NewRawRangeKeyIter(ctx, transforms); err != nil {
221 0 : return err
222 0 : } else if rki != nil {
223 0 : rangeKeyIters = append(rangeKeyIters, rki)
224 0 : }
225 : }
226 : }
227 0 : if len(rangeKeyIters) > 0 {
228 0 : it.rangeKey = iterRangeKeyStateAllocPool.Get().(*iteratorRangeKeyState)
229 0 : it.rangeKey.init(it.comparer.Compare, it.comparer.Split, &it.opts)
230 0 : it.rangeKey.rangeKeyIter = it.rangeKey.iterConfig.Init(
231 0 : &it.comparer,
232 0 : base.SeqNumMax,
233 0 : it.opts.LowerBound, it.opts.UpperBound,
234 0 : &it.hasPrefix, &it.prefixOrFullSeekKey,
235 0 : false /* internalKeys */, &it.rangeKey.internal,
236 0 : )
237 0 : for i := range rangeKeyIters {
238 0 : it.rangeKey.iterConfig.AddLevel(rangeKeyIters[i])
239 0 : }
240 : }
241 : }
242 0 : if it.rangeKey != nil {
243 0 : it.rangeKey.iiter.Init(&it.comparer, it.iter, it.rangeKey.rangeKeyIter,
244 0 : keyspan.InterleavingIterOpts{
245 0 : Mask: &it.rangeKeyMasking,
246 0 : LowerBound: it.opts.LowerBound,
247 0 : UpperBound: it.opts.UpperBound,
248 0 : })
249 0 : it.iter = &it.rangeKey.iiter
250 0 : }
251 : }
252 0 : return nil
253 : }
254 :
255 : func openExternalTables(
256 : ctx context.Context,
257 : o *Options,
258 : files []sstable.ReadableFile,
259 : seqNumOffset int,
260 : readerOpts sstable.ReaderOptions,
261 0 : ) (readers []*sstable.Reader, err error) {
262 0 : readers = make([]*sstable.Reader, 0, len(files))
263 0 : for i := range files {
264 0 : readable, err := sstable.NewSimpleReadable(files[i])
265 0 : if err != nil {
266 0 : return readers, err
267 0 : }
268 0 : r, err := sstable.NewReader(ctx, readable, readerOpts)
269 0 : if err != nil {
270 0 : return readers, err
271 0 : }
272 0 : readers = append(readers, r)
273 : }
274 0 : return readers, err
275 : }
|