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