Line data Source code
1 : // Copyright 2011 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 sstable
6 :
7 : import (
8 : "bytes"
9 : "cmp"
10 : "context"
11 : "encoding/binary"
12 : "fmt"
13 : "io"
14 : "os"
15 : "slices"
16 : "time"
17 :
18 : "github.com/cespare/xxhash/v2"
19 : "github.com/cockroachdb/errors"
20 : "github.com/cockroachdb/pebble/internal/base"
21 : "github.com/cockroachdb/pebble/internal/bytealloc"
22 : "github.com/cockroachdb/pebble/internal/cache"
23 : "github.com/cockroachdb/pebble/internal/crc"
24 : "github.com/cockroachdb/pebble/internal/invariants"
25 : "github.com/cockroachdb/pebble/internal/keyspan"
26 : "github.com/cockroachdb/pebble/internal/private"
27 : "github.com/cockroachdb/pebble/objstorage"
28 : "github.com/cockroachdb/pebble/objstorage/objstorageprovider/objiotracing"
29 : )
30 :
31 : var errReaderClosed = errors.New("pebble/table: reader is closed")
32 :
33 : // decodeBlockHandle returns the block handle encoded at the start of src, as
34 : // well as the number of bytes it occupies. It returns zero if given invalid
35 : // input. A block handle for a data block or a first/lower level index block
36 : // should not be decoded using decodeBlockHandle since the caller may validate
37 : // that the number of bytes decoded is equal to the length of src, which will
38 : // be false if the properties are not decoded. In those cases the caller
39 : // should use decodeBlockHandleWithProperties.
40 1 : func decodeBlockHandle(src []byte) (BlockHandle, int) {
41 1 : offset, n := binary.Uvarint(src)
42 1 : length, m := binary.Uvarint(src[n:])
43 1 : if n == 0 || m == 0 {
44 0 : return BlockHandle{}, 0
45 0 : }
46 1 : return BlockHandle{offset, length}, n + m
47 : }
48 :
49 : // decodeBlockHandleWithProperties returns the block handle and properties
50 : // encoded in src. src needs to be exactly the length that was encoded. This
51 : // method must be used for data block and first/lower level index blocks. The
52 : // properties in the block handle point to the bytes in src.
53 1 : func decodeBlockHandleWithProperties(src []byte) (BlockHandleWithProperties, error) {
54 1 : bh, n := decodeBlockHandle(src)
55 1 : if n == 0 {
56 0 : return BlockHandleWithProperties{}, errors.Errorf("invalid BlockHandle")
57 0 : }
58 1 : return BlockHandleWithProperties{
59 1 : BlockHandle: bh,
60 1 : Props: src[n:],
61 1 : }, nil
62 : }
63 :
64 1 : func encodeBlockHandle(dst []byte, b BlockHandle) int {
65 1 : n := binary.PutUvarint(dst, b.Offset)
66 1 : m := binary.PutUvarint(dst[n:], b.Length)
67 1 : return n + m
68 1 : }
69 :
70 1 : func encodeBlockHandleWithProperties(dst []byte, b BlockHandleWithProperties) []byte {
71 1 : n := encodeBlockHandle(dst, b.BlockHandle)
72 1 : dst = append(dst[:n], b.Props...)
73 1 : return dst
74 1 : }
75 :
76 : // block is a []byte that holds a sequence of key/value pairs plus an index
77 : // over those pairs.
78 : type block []byte
79 :
80 : type loadBlockResult int8
81 :
82 : const (
83 : loadBlockOK loadBlockResult = iota
84 : // Could be due to error or because no block left to load.
85 : loadBlockFailed
86 : loadBlockIrrelevant
87 : )
88 :
89 : type blockTransform func([]byte) ([]byte, error)
90 :
91 : // ReaderOption provide an interface to do work on Reader while it is being
92 : // opened.
93 : type ReaderOption interface {
94 : // readerApply is called on the reader during opening in order to set internal
95 : // parameters.
96 : readerApply(*Reader)
97 : }
98 :
99 : // Comparers is a map from comparer name to comparer. It is used for debugging
100 : // tools which may be used on multiple databases configured with different
101 : // comparers. Comparers implements the OpenOption interface and can be passed
102 : // as a parameter to NewReader.
103 : type Comparers map[string]*Comparer
104 :
105 0 : func (c Comparers) readerApply(r *Reader) {
106 0 : if r.Compare != nil || r.Properties.ComparerName == "" {
107 0 : return
108 0 : }
109 0 : if comparer, ok := c[r.Properties.ComparerName]; ok {
110 0 : r.Compare = comparer.Compare
111 0 : r.Equal = comparer.Equal
112 0 : r.FormatKey = comparer.FormatKey
113 0 : r.Split = comparer.Split
114 0 : }
115 : }
116 :
117 : // Mergers is a map from merger name to merger. It is used for debugging tools
118 : // which may be used on multiple databases configured with different
119 : // mergers. Mergers implements the OpenOption interface and can be passed as
120 : // a parameter to NewReader.
121 : type Mergers map[string]*Merger
122 :
123 0 : func (m Mergers) readerApply(r *Reader) {
124 0 : if r.mergerOK || r.Properties.MergerName == "" {
125 0 : return
126 0 : }
127 0 : _, r.mergerOK = m[r.Properties.MergerName]
128 : }
129 :
130 : // cacheOpts is a Reader open option for specifying the cache ID and sstable file
131 : // number. If not specified, a unique cache ID will be used.
132 : type cacheOpts struct {
133 : cacheID uint64
134 : fileNum base.DiskFileNum
135 : }
136 :
137 : // Marker function to indicate the option should be applied before reading the
138 : // sstable properties and, in the write path, before writing the default
139 : // sstable properties.
140 0 : func (c *cacheOpts) preApply() {}
141 :
142 1 : func (c *cacheOpts) readerApply(r *Reader) {
143 1 : if r.cacheID == 0 {
144 1 : r.cacheID = c.cacheID
145 1 : }
146 1 : if r.fileNum == 0 {
147 1 : r.fileNum = c.fileNum
148 1 : }
149 : }
150 :
151 1 : func (c *cacheOpts) writerApply(w *Writer) {
152 1 : if w.cacheID == 0 {
153 1 : w.cacheID = c.cacheID
154 1 : }
155 1 : if w.fileNum == 0 {
156 1 : w.fileNum = c.fileNum
157 1 : }
158 : }
159 :
160 : // SyntheticSuffix will replace every suffix of every key surfaced during block
161 : // iteration. A synthetic suffix can be used if:
162 : // 1. no two keys in the sst share the same prefix; and
163 : // 2. pebble.Compare(prefix + replacementSuffix, prefix + originalSuffix) < 0,
164 : // for all keys in the backing sst which have a suffix (i.e. originalSuffix
165 : // is not empty).
166 : type SyntheticSuffix []byte
167 :
168 : // IsSet returns true if the synthetic suffix is not enpty.
169 1 : func (ss SyntheticSuffix) IsSet() bool {
170 1 : return len(ss) > 0
171 1 : }
172 :
173 : // SyntheticPrefix represents a byte slice that is implicitly prepended to every
174 : // key in a file being read or accessed by a reader. Note that the table is
175 : // assumed to contain "prefix-less" keys that become full keys when prepended
176 : // with the synthetic prefix. The table's bloom filters are constructed only on
177 : // the "prefix-less" keys in the table, but interactions with the file including
178 : // seeks and reads, will all behave as if the file had been constructed from
179 : // keys that did include the prefix. Note that all Compare operations may act on
180 : // a prefix-less key as the synthetic prefix will never modify key metadata
181 : // stored in the key suffix.
182 : //
183 : // NB: Since this transformation currently only applies to point keys, a block
184 : // with range keys cannot be iterated over with a synthetic prefix.
185 : type SyntheticPrefix []byte
186 :
187 : // IsSet returns true if the synthetic prefix is not enpty.
188 1 : func (sp SyntheticPrefix) IsSet() bool {
189 1 : return len(sp) > 0
190 1 : }
191 :
192 : // Apply prepends the synthetic prefix to a key.
193 1 : func (sp SyntheticPrefix) Apply(key []byte) []byte {
194 1 : res := make([]byte, 0, len(sp)+len(key))
195 1 : res = append(res, sp...)
196 1 : res = append(res, key...)
197 1 : return res
198 1 : }
199 :
200 : // Invert removes the synthetic prefix from a key.
201 1 : func (sp SyntheticPrefix) Invert(key []byte) []byte {
202 1 : res, ok := bytes.CutPrefix(key, sp)
203 1 : if !ok {
204 0 : panic(fmt.Sprintf("unexpected prefix: %s", key))
205 : }
206 1 : return res
207 : }
208 :
209 : // rawTombstonesOpt is a Reader open option for specifying that range
210 : // tombstones returned by Reader.NewRangeDelIter() should not be
211 : // fragmented. Used by debug tools to get a raw view of the tombstones
212 : // contained in an sstable.
213 : type rawTombstonesOpt struct{}
214 :
215 0 : func (rawTombstonesOpt) preApply() {}
216 :
217 0 : func (rawTombstonesOpt) readerApply(r *Reader) {
218 0 : r.rawTombstones = true
219 0 : }
220 :
221 1 : func init() {
222 1 : private.SSTableCacheOpts = func(cacheID uint64, fileNum base.DiskFileNum) interface{} {
223 1 : return &cacheOpts{cacheID, fileNum}
224 1 : }
225 1 : private.SSTableRawTombstonesOpt = rawTombstonesOpt{}
226 : }
227 :
228 : // Reader is a table reader.
229 : type Reader struct {
230 : readable objstorage.Readable
231 : cacheID uint64
232 : fileNum base.DiskFileNum
233 : err error
234 : indexBH BlockHandle
235 : filterBH BlockHandle
236 : rangeDelBH BlockHandle
237 : rangeKeyBH BlockHandle
238 : rangeDelTransform blockTransform
239 : valueBIH valueBlocksIndexHandle
240 : propertiesBH BlockHandle
241 : metaIndexBH BlockHandle
242 : footerBH BlockHandle
243 : opts ReaderOptions
244 : Compare Compare
245 : Equal Equal
246 : FormatKey base.FormatKey
247 : Split Split
248 : tableFilter *tableFilterReader
249 : // Keep types that are not multiples of 8 bytes at the end and with
250 : // decreasing size.
251 : Properties Properties
252 : tableFormat TableFormat
253 : rawTombstones bool
254 : mergerOK bool
255 : checksumType ChecksumType
256 : // metaBufferPool is a buffer pool used exclusively when opening a table and
257 : // loading its meta blocks. metaBufferPoolAlloc is used to batch-allocate
258 : // the BufferPool.pool slice as a part of the Reader allocation. It's
259 : // capacity 3 to accommodate the meta block (1), and both the compressed
260 : // properties block (1) and decompressed properties block (1)
261 : // simultaneously.
262 : metaBufferPool BufferPool
263 : metaBufferPoolAlloc [3]allocedBuffer
264 : }
265 :
266 : var _ CommonReader = (*Reader)(nil)
267 :
268 : // Close implements DB.Close, as documented in the pebble package.
269 1 : func (r *Reader) Close() error {
270 1 : r.opts.Cache.Unref()
271 1 :
272 1 : if r.readable != nil {
273 1 : r.err = firstError(r.err, r.readable.Close())
274 1 : r.readable = nil
275 1 : }
276 :
277 1 : if r.err != nil {
278 0 : return r.err
279 0 : }
280 : // Make any future calls to Get, NewIter or Close return an error.
281 1 : r.err = errReaderClosed
282 1 : return nil
283 : }
284 :
285 : // NewIterWithBlockPropertyFilters returns an iterator for the contents of the
286 : // table. If an error occurs, NewIterWithBlockPropertyFilters cleans up after
287 : // itself and returns a nil iterator.
288 : func (r *Reader) NewIterWithBlockPropertyFilters(
289 : transforms IterTransforms,
290 : lower, upper []byte,
291 : filterer *BlockPropertiesFilterer,
292 : useFilterBlock bool,
293 : stats *base.InternalIteratorStats,
294 : categoryAndQoS CategoryAndQoS,
295 : statsCollector *CategoryStatsCollector,
296 : rp ReaderProvider,
297 1 : ) (Iterator, error) {
298 1 : return r.newIterWithBlockPropertyFiltersAndContext(
299 1 : context.Background(), transforms, lower, upper, filterer, useFilterBlock,
300 1 : stats, categoryAndQoS, statsCollector, rp, nil)
301 1 : }
302 :
303 : // NewIterWithBlockPropertyFiltersAndContextEtc is similar to
304 : // NewIterWithBlockPropertyFilters and additionally accepts a context for
305 : // tracing.
306 : //
307 : // If transform.HideObsoletePoints is set, the callee assumes that filterer
308 : // already includes obsoleteKeyBlockPropertyFilter. The caller can satisfy this
309 : // contract by first calling TryAddBlockPropertyFilterForHideObsoletePoints.
310 : func (r *Reader) NewIterWithBlockPropertyFiltersAndContextEtc(
311 : ctx context.Context,
312 : transforms IterTransforms,
313 : lower, upper []byte,
314 : filterer *BlockPropertiesFilterer,
315 : useFilterBlock bool,
316 : stats *base.InternalIteratorStats,
317 : categoryAndQoS CategoryAndQoS,
318 : statsCollector *CategoryStatsCollector,
319 : rp ReaderProvider,
320 1 : ) (Iterator, error) {
321 1 : return r.newIterWithBlockPropertyFiltersAndContext(
322 1 : ctx, transforms, lower, upper, filterer, useFilterBlock,
323 1 : stats, categoryAndQoS, statsCollector, rp, nil)
324 1 : }
325 :
326 : // TryAddBlockPropertyFilterForHideObsoletePoints is expected to be called
327 : // before the call to NewIterWithBlockPropertyFiltersAndContextEtc, to get the
328 : // value of hideObsoletePoints and potentially add a block property filter.
329 : func (r *Reader) TryAddBlockPropertyFilterForHideObsoletePoints(
330 : snapshotForHideObsoletePoints uint64,
331 : fileLargestSeqNum uint64,
332 : pointKeyFilters []BlockPropertyFilter,
333 1 : ) (hideObsoletePoints bool, filters []BlockPropertyFilter) {
334 1 : hideObsoletePoints = r.tableFormat >= TableFormatPebblev4 &&
335 1 : snapshotForHideObsoletePoints > fileLargestSeqNum
336 1 : if hideObsoletePoints {
337 1 : pointKeyFilters = append(pointKeyFilters, obsoleteKeyBlockPropertyFilter{})
338 1 : }
339 1 : return hideObsoletePoints, pointKeyFilters
340 : }
341 :
342 : func (r *Reader) newIterWithBlockPropertyFiltersAndContext(
343 : ctx context.Context,
344 : transforms IterTransforms,
345 : lower, upper []byte,
346 : filterer *BlockPropertiesFilterer,
347 : useFilterBlock bool,
348 : stats *base.InternalIteratorStats,
349 : categoryAndQoS CategoryAndQoS,
350 : statsCollector *CategoryStatsCollector,
351 : rp ReaderProvider,
352 : vState *virtualState,
353 1 : ) (Iterator, error) {
354 1 : // NB: pebble.tableCache wraps the returned iterator with one which performs
355 1 : // reference counting on the Reader, preventing the Reader from being closed
356 1 : // until the final iterator closes.
357 1 : if r.Properties.IndexType == twoLevelIndex {
358 1 : i := twoLevelIterPool.Get().(*twoLevelIterator)
359 1 : err := i.init(ctx, r, vState, transforms, lower, upper, filterer, useFilterBlock,
360 1 : stats, categoryAndQoS, statsCollector, rp, nil /* bufferPool */)
361 1 : if err != nil {
362 0 : return nil, err
363 0 : }
364 1 : return i, nil
365 : }
366 :
367 1 : i := singleLevelIterPool.Get().(*singleLevelIterator)
368 1 : err := i.init(ctx, r, vState, transforms, lower, upper, filterer, useFilterBlock,
369 1 : stats, categoryAndQoS, statsCollector, rp, nil /* bufferPool */)
370 1 : if err != nil {
371 0 : return nil, err
372 0 : }
373 1 : return i, nil
374 : }
375 :
376 : // NewIter returns an iterator for the contents of the table. If an error
377 : // occurs, NewIter cleans up after itself and returns a nil iterator. NewIter
378 : // must only be used when the Reader is guaranteed to outlive any LazyValues
379 : // returned from the iter.
380 1 : func (r *Reader) NewIter(transforms IterTransforms, lower, upper []byte) (Iterator, error) {
381 1 : return r.NewIterWithBlockPropertyFilters(
382 1 : transforms, lower, upper, nil, true, /* useFilterBlock */
383 1 : nil /* stats */, CategoryAndQoS{}, nil /* statsCollector */, TrivialReaderProvider{Reader: r})
384 1 : }
385 :
386 : // NewCompactionIter returns an iterator similar to NewIter but it also increments
387 : // the number of bytes iterated. If an error occurs, NewCompactionIter cleans up
388 : // after itself and returns a nil iterator.
389 : func (r *Reader) NewCompactionIter(
390 : transforms IterTransforms,
391 : categoryAndQoS CategoryAndQoS,
392 : statsCollector *CategoryStatsCollector,
393 : rp ReaderProvider,
394 : bufferPool *BufferPool,
395 1 : ) (Iterator, error) {
396 1 : return r.newCompactionIter(transforms, categoryAndQoS, statsCollector, rp, nil, bufferPool)
397 1 : }
398 :
399 : func (r *Reader) newCompactionIter(
400 : transforms IterTransforms,
401 : categoryAndQoS CategoryAndQoS,
402 : statsCollector *CategoryStatsCollector,
403 : rp ReaderProvider,
404 : vState *virtualState,
405 : bufferPool *BufferPool,
406 1 : ) (Iterator, error) {
407 1 : if vState != nil && vState.isSharedIngested {
408 1 : transforms.HideObsoletePoints = true
409 1 : }
410 1 : if r.Properties.IndexType == twoLevelIndex {
411 1 : i := twoLevelIterPool.Get().(*twoLevelIterator)
412 1 : err := i.init(
413 1 : context.Background(),
414 1 : r, vState, transforms, nil /* lower */, nil /* upper */, nil,
415 1 : false /* useFilter */, nil /* stats */, categoryAndQoS, statsCollector, rp, bufferPool,
416 1 : )
417 1 : if err != nil {
418 0 : return nil, err
419 0 : }
420 1 : i.setupForCompaction()
421 1 : return &twoLevelCompactionIterator{twoLevelIterator: i}, nil
422 : }
423 1 : i := singleLevelIterPool.Get().(*singleLevelIterator)
424 1 : err := i.init(
425 1 : context.Background(), r, vState, transforms, nil /* lower */, nil, /* upper */
426 1 : nil, false /* useFilter */, nil /* stats */, categoryAndQoS, statsCollector, rp, bufferPool,
427 1 : )
428 1 : if err != nil {
429 0 : return nil, err
430 0 : }
431 1 : i.setupForCompaction()
432 1 : return &compactionIterator{singleLevelIterator: i}, nil
433 : }
434 :
435 : // NewRawRangeDelIter returns an internal iterator for the contents of the
436 : // range-del block for the table. Returns nil if the table does not contain
437 : // any range deletions.
438 : //
439 : // TODO(sumeer): plumb context.Context since this path is relevant in the user-facing
440 : // iterator. Add WithContext methods since the existing ones are public.
441 1 : func (r *Reader) NewRawRangeDelIter(transforms IterTransforms) (keyspan.FragmentIterator, error) {
442 1 : if r.rangeDelBH.Length == 0 {
443 1 : return nil, nil
444 1 : }
445 1 : if transforms.SyntheticSuffix.IsSet() {
446 0 : return nil, base.AssertionFailedf("synthetic suffix not supported with range del iterator")
447 0 : }
448 1 : if transforms.SyntheticPrefix.IsSet() {
449 0 : return nil, base.AssertionFailedf("synthetic prefix not supported with range del iterator")
450 0 : }
451 1 : h, err := r.readRangeDel(nil /* stats */, nil /* iterStats */)
452 1 : if err != nil {
453 0 : return nil, err
454 0 : }
455 1 : i := &fragmentBlockIter{elideSameSeqnum: true}
456 1 : // It's okay for hideObsoletePoints to be false here, even for shared ingested
457 1 : // sstables. This is because rangedels do not apply to points in the same
458 1 : // sstable at the same sequence number anyway, so exposing obsolete rangedels
459 1 : // is harmless.
460 1 : if err := i.blockIter.initHandle(r.Compare, r.Split, h, transforms); err != nil {
461 0 : return nil, err
462 0 : }
463 1 : return i, nil
464 : }
465 :
466 : // NewRawRangeKeyIter returns an internal iterator for the contents of the
467 : // range-key block for the table. Returns nil if the table does not contain any
468 : // range keys.
469 : //
470 : // TODO(sumeer): plumb context.Context since this path is relevant in the user-facing
471 : // iterator. Add WithContext methods since the existing ones are public.
472 1 : func (r *Reader) NewRawRangeKeyIter(transforms IterTransforms) (keyspan.FragmentIterator, error) {
473 1 : if r.rangeKeyBH.Length == 0 {
474 1 : return nil, nil
475 1 : }
476 1 : if transforms.SyntheticSuffix.IsSet() {
477 0 : return nil, base.AssertionFailedf("synthetic suffix not supported with range key iterator")
478 0 : }
479 1 : if transforms.SyntheticPrefix.IsSet() {
480 0 : return nil, base.AssertionFailedf("synthetic prefix not supported with range key iterator")
481 0 : }
482 1 : h, err := r.readRangeKey(nil /* stats */, nil /* iterStats */)
483 1 : if err != nil {
484 0 : return nil, err
485 0 : }
486 1 : i := rangeKeyFragmentBlockIterPool.Get().(*rangeKeyFragmentBlockIter)
487 1 :
488 1 : if err := i.blockIter.initHandle(r.Compare, r.Split, h, transforms); err != nil {
489 0 : return nil, err
490 0 : }
491 1 : return i, nil
492 : }
493 :
494 : type rangeKeyFragmentBlockIter struct {
495 : fragmentBlockIter
496 : }
497 :
498 1 : func (i *rangeKeyFragmentBlockIter) Close() error {
499 1 : err := i.fragmentBlockIter.Close()
500 1 : i.fragmentBlockIter = i.fragmentBlockIter.resetForReuse()
501 1 : rangeKeyFragmentBlockIterPool.Put(i)
502 1 : return err
503 1 : }
504 :
505 : func (r *Reader) readIndex(
506 : ctx context.Context, stats *base.InternalIteratorStats, iterStats *iterStatsAccumulator,
507 1 : ) (bufferHandle, error) {
508 1 : ctx = objiotracing.WithBlockType(ctx, objiotracing.MetadataBlock)
509 1 : return r.readBlock(ctx, r.indexBH, nil, nil, stats, iterStats, nil /* buffer pool */)
510 1 : }
511 :
512 : func (r *Reader) readFilter(
513 : ctx context.Context, stats *base.InternalIteratorStats, iterStats *iterStatsAccumulator,
514 1 : ) (bufferHandle, error) {
515 1 : ctx = objiotracing.WithBlockType(ctx, objiotracing.FilterBlock)
516 1 : return r.readBlock(ctx, r.filterBH, nil /* transform */, nil /* readHandle */, stats, iterStats, nil /* buffer pool */)
517 1 : }
518 :
519 : func (r *Reader) readRangeDel(
520 : stats *base.InternalIteratorStats, iterStats *iterStatsAccumulator,
521 1 : ) (bufferHandle, error) {
522 1 : ctx := objiotracing.WithBlockType(context.Background(), objiotracing.MetadataBlock)
523 1 : return r.readBlock(ctx, r.rangeDelBH, r.rangeDelTransform, nil /* readHandle */, stats, iterStats, nil /* buffer pool */)
524 1 : }
525 :
526 : func (r *Reader) readRangeKey(
527 : stats *base.InternalIteratorStats, iterStats *iterStatsAccumulator,
528 1 : ) (bufferHandle, error) {
529 1 : ctx := objiotracing.WithBlockType(context.Background(), objiotracing.MetadataBlock)
530 1 : return r.readBlock(ctx, r.rangeKeyBH, nil /* transform */, nil /* readHandle */, stats, iterStats, nil /* buffer pool */)
531 1 : }
532 :
533 : func checkChecksum(
534 : checksumType ChecksumType, b []byte, bh BlockHandle, fileNum base.DiskFileNum,
535 1 : ) error {
536 1 : expectedChecksum := binary.LittleEndian.Uint32(b[bh.Length+1:])
537 1 : var computedChecksum uint32
538 1 : switch checksumType {
539 1 : case ChecksumTypeCRC32c:
540 1 : computedChecksum = crc.New(b[:bh.Length+1]).Value()
541 0 : case ChecksumTypeXXHash64:
542 0 : computedChecksum = uint32(xxhash.Sum64(b[:bh.Length+1]))
543 0 : default:
544 0 : return errors.Errorf("unsupported checksum type: %d", checksumType)
545 : }
546 :
547 1 : if expectedChecksum != computedChecksum {
548 0 : return base.CorruptionErrorf(
549 0 : "pebble/table: invalid table %s (checksum mismatch at %d/%d)",
550 0 : fileNum, errors.Safe(bh.Offset), errors.Safe(bh.Length))
551 0 : }
552 1 : return nil
553 : }
554 :
555 : type cacheValueOrBuf struct {
556 : // buf.Valid() returns true if backed by a BufferPool.
557 : buf Buf
558 : // v is non-nil if backed by the block cache.
559 : v *cache.Value
560 : }
561 :
562 1 : func (b cacheValueOrBuf) get() []byte {
563 1 : if b.buf.Valid() {
564 1 : return b.buf.p.pool[b.buf.i].b
565 1 : }
566 1 : return b.v.Buf()
567 : }
568 :
569 1 : func (b cacheValueOrBuf) release() {
570 1 : if b.buf.Valid() {
571 1 : b.buf.Release()
572 1 : } else {
573 1 : cache.Free(b.v)
574 1 : }
575 : }
576 :
577 1 : func (b cacheValueOrBuf) truncate(n int) {
578 1 : if b.buf.Valid() {
579 1 : b.buf.p.pool[b.buf.i].b = b.buf.p.pool[b.buf.i].b[:n]
580 1 : } else {
581 1 : b.v.Truncate(n)
582 1 : }
583 : }
584 :
585 : // DeterministicReadBlockDurationForTesting is for tests that want a
586 : // deterministic value of the time to read a block (that is not in the cache).
587 : // The return value is a function that must be called before the test exits.
588 0 : func DeterministicReadBlockDurationForTesting() func() {
589 0 : drbdForTesting := deterministicReadBlockDurationForTesting
590 0 : deterministicReadBlockDurationForTesting = true
591 0 : return func() {
592 0 : deterministicReadBlockDurationForTesting = drbdForTesting
593 0 : }
594 : }
595 :
596 : var deterministicReadBlockDurationForTesting = false
597 :
598 : func (r *Reader) readBlock(
599 : ctx context.Context,
600 : bh BlockHandle,
601 : transform blockTransform,
602 : readHandle objstorage.ReadHandle,
603 : stats *base.InternalIteratorStats,
604 : iterStats *iterStatsAccumulator,
605 : bufferPool *BufferPool,
606 1 : ) (handle bufferHandle, _ error) {
607 1 : if h := r.opts.Cache.Get(r.cacheID, r.fileNum, bh.Offset); h.Get() != nil {
608 1 : // Cache hit.
609 1 : if readHandle != nil {
610 1 : readHandle.RecordCacheHit(ctx, int64(bh.Offset), int64(bh.Length+blockTrailerLen))
611 1 : }
612 1 : if stats != nil {
613 1 : stats.BlockBytes += bh.Length
614 1 : stats.BlockBytesInCache += bh.Length
615 1 : }
616 1 : if iterStats != nil {
617 1 : iterStats.reportStats(bh.Length, bh.Length, 0)
618 1 : }
619 : // This block is already in the cache; return a handle to existing vlaue
620 : // in the cache.
621 1 : return bufferHandle{h: h}, nil
622 : }
623 :
624 : // Cache miss.
625 1 : var compressed cacheValueOrBuf
626 1 : if bufferPool != nil {
627 1 : compressed = cacheValueOrBuf{
628 1 : buf: bufferPool.Alloc(int(bh.Length + blockTrailerLen)),
629 1 : }
630 1 : } else {
631 1 : compressed = cacheValueOrBuf{
632 1 : v: cache.Alloc(int(bh.Length + blockTrailerLen)),
633 1 : }
634 1 : }
635 :
636 1 : readStartTime := time.Now()
637 1 : var err error
638 1 : if readHandle != nil {
639 1 : err = readHandle.ReadAt(ctx, compressed.get(), int64(bh.Offset))
640 1 : } else {
641 1 : err = r.readable.ReadAt(ctx, compressed.get(), int64(bh.Offset))
642 1 : }
643 1 : readDuration := time.Since(readStartTime)
644 1 : // TODO(sumeer): should the threshold be configurable.
645 1 : const slowReadTracingThreshold = 5 * time.Millisecond
646 1 : // For deterministic testing.
647 1 : if deterministicReadBlockDurationForTesting {
648 0 : readDuration = slowReadTracingThreshold
649 0 : }
650 : // Call IsTracingEnabled to avoid the allocations of boxing integers into an
651 : // interface{}, unless necessary.
652 1 : if readDuration >= slowReadTracingThreshold && r.opts.LoggerAndTracer.IsTracingEnabled(ctx) {
653 0 : r.opts.LoggerAndTracer.Eventf(ctx, "reading %d bytes took %s",
654 0 : int(bh.Length+blockTrailerLen), readDuration.String())
655 0 : }
656 1 : if stats != nil {
657 1 : stats.BlockReadDuration += readDuration
658 1 : }
659 1 : if err != nil {
660 0 : compressed.release()
661 0 : return bufferHandle{}, err
662 0 : }
663 1 : if err := checkChecksum(r.checksumType, compressed.get(), bh, r.fileNum); err != nil {
664 0 : compressed.release()
665 0 : return bufferHandle{}, err
666 0 : }
667 :
668 1 : typ := blockType(compressed.get()[bh.Length])
669 1 : compressed.truncate(int(bh.Length))
670 1 :
671 1 : var decompressed cacheValueOrBuf
672 1 : if typ == noCompressionBlockType {
673 1 : decompressed = compressed
674 1 : } else {
675 1 : // Decode the length of the decompressed value.
676 1 : decodedLen, prefixLen, err := decompressedLen(typ, compressed.get())
677 1 : if err != nil {
678 0 : compressed.release()
679 0 : return bufferHandle{}, err
680 0 : }
681 :
682 1 : if bufferPool != nil {
683 1 : decompressed = cacheValueOrBuf{buf: bufferPool.Alloc(decodedLen)}
684 1 : } else {
685 1 : decompressed = cacheValueOrBuf{v: cache.Alloc(decodedLen)}
686 1 : }
687 1 : if err := decompressInto(typ, compressed.get()[prefixLen:], decompressed.get()); err != nil {
688 0 : compressed.release()
689 0 : return bufferHandle{}, err
690 0 : }
691 1 : compressed.release()
692 : }
693 :
694 1 : if transform != nil {
695 0 : // Transforming blocks is very rare, so the extra copy of the
696 0 : // transformed data is not problematic.
697 0 : tmpTransformed, err := transform(decompressed.get())
698 0 : if err != nil {
699 0 : decompressed.release()
700 0 : return bufferHandle{}, err
701 0 : }
702 :
703 0 : var transformed cacheValueOrBuf
704 0 : if bufferPool != nil {
705 0 : transformed = cacheValueOrBuf{buf: bufferPool.Alloc(len(tmpTransformed))}
706 0 : } else {
707 0 : transformed = cacheValueOrBuf{v: cache.Alloc(len(tmpTransformed))}
708 0 : }
709 0 : copy(transformed.get(), tmpTransformed)
710 0 : decompressed.release()
711 0 : decompressed = transformed
712 : }
713 :
714 1 : if stats != nil {
715 1 : stats.BlockBytes += bh.Length
716 1 : }
717 1 : if iterStats != nil {
718 1 : iterStats.reportStats(bh.Length, 0, readDuration)
719 1 : }
720 1 : if decompressed.buf.Valid() {
721 1 : return bufferHandle{b: decompressed.buf}, nil
722 1 : }
723 1 : h := r.opts.Cache.Set(r.cacheID, r.fileNum, bh.Offset, decompressed.v)
724 1 : return bufferHandle{h: h}, nil
725 : }
726 :
727 0 : func (r *Reader) transformRangeDelV1(b []byte) ([]byte, error) {
728 0 : // Convert v1 (RocksDB format) range-del blocks to v2 blocks on the fly. The
729 0 : // v1 format range-del blocks have unfragmented and unsorted range
730 0 : // tombstones. We need properly fragmented and sorted range tombstones in
731 0 : // order to serve from them directly.
732 0 : iter := &blockIter{}
733 0 : if err := iter.init(r.Compare, r.Split, b, NoTransforms); err != nil {
734 0 : return nil, err
735 0 : }
736 0 : var tombstones []keyspan.Span
737 0 : for kv := iter.First(); kv != nil; kv = iter.Next() {
738 0 : t := keyspan.Span{
739 0 : Start: kv.K.UserKey,
740 0 : End: kv.InPlaceValue(),
741 0 : Keys: []keyspan.Key{{Trailer: kv.K.Trailer}},
742 0 : }
743 0 : tombstones = append(tombstones, t)
744 0 : }
745 0 : keyspan.Sort(r.Compare, tombstones)
746 0 :
747 0 : // Fragment the tombstones, outputting them directly to a block writer.
748 0 : rangeDelBlock := blockWriter{
749 0 : restartInterval: 1,
750 0 : }
751 0 : frag := keyspan.Fragmenter{
752 0 : Cmp: r.Compare,
753 0 : Format: r.FormatKey,
754 0 : Emit: func(s keyspan.Span) {
755 0 : for _, k := range s.Keys {
756 0 : startIK := InternalKey{UserKey: s.Start, Trailer: k.Trailer}
757 0 : rangeDelBlock.add(startIK, s.End)
758 0 : }
759 : },
760 : }
761 0 : for i := range tombstones {
762 0 : frag.Add(tombstones[i])
763 0 : }
764 0 : frag.Finish()
765 0 :
766 0 : // Return the contents of the constructed v2 format range-del block.
767 0 : return rangeDelBlock.finish(), nil
768 : }
769 :
770 1 : func (r *Reader) readMetaindex(metaindexBH BlockHandle) error {
771 1 : // We use a BufferPool when reading metaindex blocks in order to avoid
772 1 : // populating the block cache with these blocks. In heavy-write workloads,
773 1 : // especially with high compaction concurrency, new tables may be created
774 1 : // frequently. Populating the block cache with these metaindex blocks adds
775 1 : // additional contention on the block cache mutexes (see #1997).
776 1 : // Additionally, these blocks are exceedingly unlikely to be read again
777 1 : // while they're still in the block cache except in misconfigurations with
778 1 : // excessive sstables counts or a table cache that's far too small.
779 1 : r.metaBufferPool.initPreallocated(r.metaBufferPoolAlloc[:0])
780 1 : // When we're finished, release the buffers we've allocated back to memory
781 1 : // allocator. We don't expect to use metaBufferPool again.
782 1 : defer r.metaBufferPool.Release()
783 1 :
784 1 : b, err := r.readBlock(
785 1 : context.Background(), metaindexBH, nil /* transform */, nil /* readHandle */, nil, /* stats */
786 1 : nil /* iterStats */, &r.metaBufferPool)
787 1 : if err != nil {
788 0 : return err
789 0 : }
790 1 : data := b.Get()
791 1 : defer b.Release()
792 1 :
793 1 : if uint64(len(data)) != metaindexBH.Length {
794 0 : return base.CorruptionErrorf("pebble/table: unexpected metaindex block size: %d vs %d",
795 0 : errors.Safe(len(data)), errors.Safe(metaindexBH.Length))
796 0 : }
797 :
798 1 : i, err := newRawBlockIter(bytes.Compare, data)
799 1 : if err != nil {
800 0 : return err
801 0 : }
802 :
803 1 : meta := map[string]BlockHandle{}
804 1 : for valid := i.First(); valid; valid = i.Next() {
805 1 : value := i.Value()
806 1 : if bytes.Equal(i.Key().UserKey, []byte(metaValueIndexName)) {
807 1 : vbih, n, err := decodeValueBlocksIndexHandle(i.Value())
808 1 : if err != nil {
809 0 : return err
810 0 : }
811 1 : if n == 0 || n != len(value) {
812 0 : return base.CorruptionErrorf("pebble/table: invalid table (bad value blocks index handle)")
813 0 : }
814 1 : r.valueBIH = vbih
815 1 : } else {
816 1 : bh, n := decodeBlockHandle(value)
817 1 : if n == 0 || n != len(value) {
818 0 : return base.CorruptionErrorf("pebble/table: invalid table (bad block handle)")
819 0 : }
820 1 : meta[string(i.Key().UserKey)] = bh
821 : }
822 : }
823 1 : if err := i.Close(); err != nil {
824 0 : return err
825 0 : }
826 :
827 1 : if bh, ok := meta[metaPropertiesName]; ok {
828 1 : b, err = r.readBlock(
829 1 : context.Background(), bh, nil /* transform */, nil /* readHandle */, nil, /* stats */
830 1 : nil /* iterStats */, nil /* buffer pool */)
831 1 : if err != nil {
832 0 : return err
833 0 : }
834 1 : r.propertiesBH = bh
835 1 : err := r.Properties.load(b.Get(), bh.Offset, r.opts.DeniedUserProperties)
836 1 : b.Release()
837 1 : if err != nil {
838 0 : return err
839 0 : }
840 : }
841 :
842 1 : if bh, ok := meta[metaRangeDelV2Name]; ok {
843 1 : r.rangeDelBH = bh
844 1 : } else if bh, ok := meta[metaRangeDelName]; ok {
845 0 : r.rangeDelBH = bh
846 0 : if !r.rawTombstones {
847 0 : r.rangeDelTransform = r.transformRangeDelV1
848 0 : }
849 : }
850 :
851 1 : if bh, ok := meta[metaRangeKeyName]; ok {
852 1 : r.rangeKeyBH = bh
853 1 : }
854 :
855 1 : for name, fp := range r.opts.Filters {
856 1 : types := []struct {
857 1 : ftype FilterType
858 1 : prefix string
859 1 : }{
860 1 : {TableFilter, "fullfilter."},
861 1 : }
862 1 : var done bool
863 1 : for _, t := range types {
864 1 : if bh, ok := meta[t.prefix+name]; ok {
865 1 : r.filterBH = bh
866 1 :
867 1 : switch t.ftype {
868 1 : case TableFilter:
869 1 : r.tableFilter = newTableFilterReader(fp)
870 0 : default:
871 0 : return base.CorruptionErrorf("unknown filter type: %v", errors.Safe(t.ftype))
872 : }
873 :
874 1 : done = true
875 1 : break
876 : }
877 : }
878 1 : if done {
879 1 : break
880 : }
881 : }
882 1 : return nil
883 : }
884 :
885 : // Layout returns the layout (block organization) for an sstable.
886 1 : func (r *Reader) Layout() (*Layout, error) {
887 1 : if r.err != nil {
888 0 : return nil, r.err
889 0 : }
890 :
891 1 : l := &Layout{
892 1 : Data: make([]BlockHandleWithProperties, 0, r.Properties.NumDataBlocks),
893 1 : Filter: r.filterBH,
894 1 : RangeDel: r.rangeDelBH,
895 1 : RangeKey: r.rangeKeyBH,
896 1 : ValueIndex: r.valueBIH.h,
897 1 : Properties: r.propertiesBH,
898 1 : MetaIndex: r.metaIndexBH,
899 1 : Footer: r.footerBH,
900 1 : Format: r.tableFormat,
901 1 : }
902 1 :
903 1 : indexH, err := r.readIndex(context.Background(), nil, nil)
904 1 : if err != nil {
905 0 : return nil, err
906 0 : }
907 1 : defer indexH.Release()
908 1 :
909 1 : var alloc bytealloc.A
910 1 :
911 1 : if r.Properties.IndexPartitions == 0 {
912 1 : l.Index = append(l.Index, r.indexBH)
913 1 : iter, _ := newBlockIter(r.Compare, r.Split, indexH.Get(), NoTransforms)
914 1 : for kv := iter.First(); kv != nil; kv = iter.Next() {
915 1 : dataBH, err := decodeBlockHandleWithProperties(kv.InPlaceValue())
916 1 : if err != nil {
917 0 : return nil, errCorruptIndexEntry(err)
918 0 : }
919 1 : if len(dataBH.Props) > 0 {
920 1 : alloc, dataBH.Props = alloc.Copy(dataBH.Props)
921 1 : }
922 1 : l.Data = append(l.Data, dataBH)
923 : }
924 1 : } else {
925 1 : l.TopIndex = r.indexBH
926 1 : topIter, _ := newBlockIter(r.Compare, r.Split, indexH.Get(), NoTransforms)
927 1 : iter := &blockIter{}
928 1 : for kv := topIter.First(); kv != nil; kv = topIter.Next() {
929 1 : indexBH, err := decodeBlockHandleWithProperties(kv.InPlaceValue())
930 1 : if err != nil {
931 0 : return nil, errCorruptIndexEntry(err)
932 0 : }
933 1 : l.Index = append(l.Index, indexBH.BlockHandle)
934 1 :
935 1 : subIndex, err := r.readBlock(context.Background(), indexBH.BlockHandle,
936 1 : nil /* transform */, nil /* readHandle */, nil /* stats */, nil /* iterStats */, nil /* buffer pool */)
937 1 : if err != nil {
938 0 : return nil, err
939 0 : }
940 : // TODO(msbutler): figure out how to pass virtualState to layout call.
941 1 : if err := iter.init(r.Compare, r.Split, subIndex.Get(), NoTransforms); err != nil {
942 0 : return nil, err
943 0 : }
944 1 : for kv := iter.First(); kv != nil; kv = iter.Next() {
945 1 : dataBH, err := decodeBlockHandleWithProperties(kv.InPlaceValue())
946 1 : if len(dataBH.Props) > 0 {
947 1 : alloc, dataBH.Props = alloc.Copy(dataBH.Props)
948 1 : }
949 1 : if err != nil {
950 0 : return nil, errCorruptIndexEntry(err)
951 0 : }
952 1 : l.Data = append(l.Data, dataBH)
953 : }
954 1 : subIndex.Release()
955 1 : *iter = iter.resetForReuse()
956 : }
957 : }
958 1 : if r.valueBIH.h.Length != 0 {
959 1 : vbiH, err := r.readBlock(context.Background(), r.valueBIH.h, nil, nil, nil, nil, nil /* buffer pool */)
960 1 : if err != nil {
961 0 : return nil, err
962 0 : }
963 1 : defer vbiH.Release()
964 1 : vbiBlock := vbiH.Get()
965 1 : indexEntryLen := int(r.valueBIH.blockNumByteLength + r.valueBIH.blockOffsetByteLength +
966 1 : r.valueBIH.blockLengthByteLength)
967 1 : i := 0
968 1 : for len(vbiBlock) != 0 {
969 1 : if len(vbiBlock) < indexEntryLen {
970 0 : return nil, errors.Errorf(
971 0 : "remaining value index block %d does not contain a full entry of length %d",
972 0 : len(vbiBlock), indexEntryLen)
973 0 : }
974 1 : n := int(r.valueBIH.blockNumByteLength)
975 1 : bn := int(littleEndianGet(vbiBlock, n))
976 1 : if bn != i {
977 0 : return nil, errors.Errorf("unexpected block num %d, expected %d",
978 0 : bn, i)
979 0 : }
980 1 : i++
981 1 : vbiBlock = vbiBlock[n:]
982 1 : n = int(r.valueBIH.blockOffsetByteLength)
983 1 : blockOffset := littleEndianGet(vbiBlock, n)
984 1 : vbiBlock = vbiBlock[n:]
985 1 : n = int(r.valueBIH.blockLengthByteLength)
986 1 : blockLen := littleEndianGet(vbiBlock, n)
987 1 : vbiBlock = vbiBlock[n:]
988 1 : l.ValueBlock = append(l.ValueBlock, BlockHandle{Offset: blockOffset, Length: blockLen})
989 : }
990 : }
991 :
992 1 : return l, nil
993 : }
994 :
995 : // ValidateBlockChecksums validates the checksums for each block in the SSTable.
996 1 : func (r *Reader) ValidateBlockChecksums() error {
997 1 : // Pre-compute the BlockHandles for the underlying file.
998 1 : l, err := r.Layout()
999 1 : if err != nil {
1000 0 : return err
1001 0 : }
1002 :
1003 : // Construct the set of blocks to check. Note that the footer is not checked
1004 : // as it is not a block with a checksum.
1005 1 : blocks := make([]BlockHandle, len(l.Data))
1006 1 : for i := range l.Data {
1007 1 : blocks[i] = l.Data[i].BlockHandle
1008 1 : }
1009 1 : blocks = append(blocks, l.Index...)
1010 1 : blocks = append(blocks, l.TopIndex, l.Filter, l.RangeDel, l.RangeKey, l.Properties, l.MetaIndex)
1011 1 :
1012 1 : // Sorting by offset ensures we are performing a sequential scan of the
1013 1 : // file.
1014 1 : slices.SortFunc(blocks, func(a, b BlockHandle) int {
1015 1 : return cmp.Compare(a.Offset, b.Offset)
1016 1 : })
1017 :
1018 : // Check all blocks sequentially. Make use of read-ahead, given we are
1019 : // scanning the entire file from start to end.
1020 1 : rh := r.readable.NewReadHandle(context.TODO())
1021 1 : defer rh.Close()
1022 1 :
1023 1 : for _, bh := range blocks {
1024 1 : // Certain blocks may not be present, in which case we skip them.
1025 1 : if bh.Length == 0 {
1026 1 : continue
1027 : }
1028 :
1029 : // Read the block, which validates the checksum.
1030 1 : h, err := r.readBlock(context.Background(), bh, nil, rh, nil, nil /* iterStats */, nil /* buffer pool */)
1031 1 : if err != nil {
1032 0 : return err
1033 0 : }
1034 1 : h.Release()
1035 : }
1036 :
1037 1 : return nil
1038 : }
1039 :
1040 : // CommonProperties implemented the CommonReader interface.
1041 1 : func (r *Reader) CommonProperties() *CommonProperties {
1042 1 : return &r.Properties.CommonProperties
1043 1 : }
1044 :
1045 : // EstimateDiskUsage returns the total size of data blocks overlapping the range
1046 : // `[start, end]`. Even if a data block partially overlaps, or we cannot
1047 : // determine overlap due to abbreviated index keys, the full data block size is
1048 : // included in the estimation.
1049 : //
1050 : // This function does not account for any metablock space usage. Assumes there
1051 : // is at least partial overlap, i.e., `[start, end]` falls neither completely
1052 : // before nor completely after the file's range.
1053 : //
1054 : // Only blocks containing point keys are considered. Range deletion and range
1055 : // key blocks are not considered.
1056 : //
1057 : // TODO(ajkr): account for metablock space usage. Perhaps look at the fraction of
1058 : // data blocks overlapped and add that same fraction of the metadata blocks to the
1059 : // estimate.
1060 1 : func (r *Reader) EstimateDiskUsage(start, end []byte) (uint64, error) {
1061 1 : if r.err != nil {
1062 0 : return 0, r.err
1063 0 : }
1064 :
1065 1 : indexH, err := r.readIndex(context.Background(), nil, nil)
1066 1 : if err != nil {
1067 0 : return 0, err
1068 0 : }
1069 1 : defer indexH.Release()
1070 1 :
1071 1 : // Iterators over the bottom-level index blocks containing start and end.
1072 1 : // These may be different in case of partitioned index but will both point
1073 1 : // to the same blockIter over the single index in the unpartitioned case.
1074 1 : var startIdxIter, endIdxIter *blockIter
1075 1 : if r.Properties.IndexPartitions == 0 {
1076 1 : iter, err := newBlockIter(r.Compare, r.Split, indexH.Get(), NoTransforms)
1077 1 : if err != nil {
1078 0 : return 0, err
1079 0 : }
1080 1 : startIdxIter = iter
1081 1 : endIdxIter = iter
1082 1 : } else {
1083 1 : topIter, err := newBlockIter(r.Compare, r.Split, indexH.Get(), NoTransforms)
1084 1 : if err != nil {
1085 0 : return 0, err
1086 0 : }
1087 :
1088 1 : kv := topIter.SeekGE(start, base.SeekGEFlagsNone)
1089 1 : if kv == nil {
1090 1 : // The range falls completely after this file, or an error occurred.
1091 1 : return 0, topIter.Error()
1092 1 : }
1093 1 : startIdxBH, err := decodeBlockHandleWithProperties(kv.InPlaceValue())
1094 1 : if err != nil {
1095 0 : return 0, errCorruptIndexEntry(err)
1096 0 : }
1097 1 : startIdxBlock, err := r.readBlock(context.Background(), startIdxBH.BlockHandle,
1098 1 : nil /* transform */, nil /* readHandle */, nil /* stats */, nil /* iterStats */, nil /* buffer pool */)
1099 1 : if err != nil {
1100 0 : return 0, err
1101 0 : }
1102 1 : defer startIdxBlock.Release()
1103 1 : startIdxIter, err = newBlockIter(r.Compare, r.Split, startIdxBlock.Get(), NoTransforms)
1104 1 : if err != nil {
1105 0 : return 0, err
1106 0 : }
1107 :
1108 1 : kv = topIter.SeekGE(end, base.SeekGEFlagsNone)
1109 1 : if kv == nil {
1110 1 : if err := topIter.Error(); err != nil {
1111 0 : return 0, err
1112 0 : }
1113 1 : } else {
1114 1 : endIdxBH, err := decodeBlockHandleWithProperties(kv.InPlaceValue())
1115 1 : if err != nil {
1116 0 : return 0, errCorruptIndexEntry(err)
1117 0 : }
1118 1 : endIdxBlock, err := r.readBlock(context.Background(),
1119 1 : endIdxBH.BlockHandle, nil /* transform */, nil /* readHandle */, nil /* stats */, nil /* iterStats */, nil /* buffer pool */)
1120 1 : if err != nil {
1121 0 : return 0, err
1122 0 : }
1123 1 : defer endIdxBlock.Release()
1124 1 : endIdxIter, err = newBlockIter(r.Compare, r.Split, endIdxBlock.Get(), NoTransforms)
1125 1 : if err != nil {
1126 0 : return 0, err
1127 0 : }
1128 : }
1129 : }
1130 : // startIdxIter should not be nil at this point, while endIdxIter can be if the
1131 : // range spans past the end of the file.
1132 :
1133 1 : kv := startIdxIter.SeekGE(start, base.SeekGEFlagsNone)
1134 1 : if kv == nil {
1135 1 : // The range falls completely after this file, or an error occurred.
1136 1 : return 0, startIdxIter.Error()
1137 1 : }
1138 1 : startBH, err := decodeBlockHandleWithProperties(kv.InPlaceValue())
1139 1 : if err != nil {
1140 0 : return 0, errCorruptIndexEntry(err)
1141 0 : }
1142 :
1143 1 : includeInterpolatedValueBlocksSize := func(dataBlockSize uint64) uint64 {
1144 1 : // INVARIANT: r.Properties.DataSize > 0 since startIdxIter is not nil.
1145 1 : // Linearly interpolate what is stored in value blocks.
1146 1 : //
1147 1 : // TODO(sumeer): if we need more accuracy, without loading any data blocks
1148 1 : // (which contain the value handles, and which may also be insufficient if
1149 1 : // the values are in separate files), we will need to accumulate the
1150 1 : // logical size of the key-value pairs and store the cumulative value for
1151 1 : // each data block in the index block entry. This increases the size of
1152 1 : // the BlockHandle, so wait until this becomes necessary.
1153 1 : return dataBlockSize +
1154 1 : uint64((float64(dataBlockSize)/float64(r.Properties.DataSize))*
1155 1 : float64(r.Properties.ValueBlocksSize))
1156 1 : }
1157 1 : if endIdxIter == nil {
1158 1 : // The range spans beyond this file. Include data blocks through the last.
1159 1 : return includeInterpolatedValueBlocksSize(r.Properties.DataSize - startBH.Offset), nil
1160 1 : }
1161 1 : kv = endIdxIter.SeekGE(end, base.SeekGEFlagsNone)
1162 1 : if kv == nil {
1163 1 : if err := endIdxIter.Error(); err != nil {
1164 0 : return 0, err
1165 0 : }
1166 : // The range spans beyond this file. Include data blocks through the last.
1167 1 : return includeInterpolatedValueBlocksSize(r.Properties.DataSize - startBH.Offset), nil
1168 : }
1169 1 : endBH, err := decodeBlockHandleWithProperties(kv.InPlaceValue())
1170 1 : if err != nil {
1171 0 : return 0, errCorruptIndexEntry(err)
1172 0 : }
1173 1 : return includeInterpolatedValueBlocksSize(
1174 1 : endBH.Offset + endBH.Length + blockTrailerLen - startBH.Offset), nil
1175 : }
1176 :
1177 : // TableFormat returns the format version for the table.
1178 1 : func (r *Reader) TableFormat() (TableFormat, error) {
1179 1 : if r.err != nil {
1180 0 : return TableFormatUnspecified, r.err
1181 0 : }
1182 1 : return r.tableFormat, nil
1183 : }
1184 :
1185 : // NewReader returns a new table reader for the file. Closing the reader will
1186 : // close the file.
1187 1 : func NewReader(f objstorage.Readable, o ReaderOptions, extraOpts ...ReaderOption) (*Reader, error) {
1188 1 : o = o.ensureDefaults()
1189 1 : r := &Reader{
1190 1 : readable: f,
1191 1 : opts: o,
1192 1 : }
1193 1 : if r.opts.Cache == nil {
1194 1 : r.opts.Cache = cache.New(0)
1195 1 : } else {
1196 1 : r.opts.Cache.Ref()
1197 1 : }
1198 :
1199 1 : if f == nil {
1200 0 : r.err = errors.New("pebble/table: nil file")
1201 0 : return nil, r.Close()
1202 0 : }
1203 :
1204 : // Note that the extra options are applied twice. First here for pre-apply
1205 : // options, and then below for post-apply options. Pre and post refer to
1206 : // before and after reading the metaindex and properties.
1207 1 : type preApply interface{ preApply() }
1208 1 : for _, opt := range extraOpts {
1209 1 : if _, ok := opt.(preApply); ok {
1210 1 : opt.readerApply(r)
1211 1 : }
1212 : }
1213 1 : if r.cacheID == 0 {
1214 1 : r.cacheID = r.opts.Cache.NewID()
1215 1 : }
1216 :
1217 1 : footer, err := readFooter(f)
1218 1 : if err != nil {
1219 0 : r.err = err
1220 0 : return nil, r.Close()
1221 0 : }
1222 1 : r.checksumType = footer.checksum
1223 1 : r.tableFormat = footer.format
1224 1 : // Read the metaindex.
1225 1 : if err := r.readMetaindex(footer.metaindexBH); err != nil {
1226 0 : r.err = err
1227 0 : return nil, r.Close()
1228 0 : }
1229 1 : r.indexBH = footer.indexBH
1230 1 : r.metaIndexBH = footer.metaindexBH
1231 1 : r.footerBH = footer.footerBH
1232 1 :
1233 1 : if r.Properties.ComparerName == "" || o.Comparer.Name == r.Properties.ComparerName {
1234 1 : r.Compare = o.Comparer.Compare
1235 1 : r.Equal = o.Comparer.Equal
1236 1 : r.FormatKey = o.Comparer.FormatKey
1237 1 : r.Split = o.Comparer.Split
1238 1 : }
1239 :
1240 1 : if o.MergerName == r.Properties.MergerName {
1241 1 : r.mergerOK = true
1242 1 : }
1243 :
1244 : // Apply the extra options again now that the comparer and merger names are
1245 : // known.
1246 1 : for _, opt := range extraOpts {
1247 1 : if _, ok := opt.(preApply); !ok {
1248 1 : opt.readerApply(r)
1249 1 : }
1250 : }
1251 :
1252 1 : if r.Compare == nil {
1253 0 : r.err = errors.Errorf("pebble/table: %d: unknown comparer %s",
1254 0 : errors.Safe(r.fileNum), errors.Safe(r.Properties.ComparerName))
1255 0 : }
1256 1 : if !r.mergerOK {
1257 0 : if name := r.Properties.MergerName; name != "" && name != "nullptr" {
1258 0 : r.err = errors.Errorf("pebble/table: %d: unknown merger %s",
1259 0 : errors.Safe(r.fileNum), errors.Safe(r.Properties.MergerName))
1260 0 : }
1261 : }
1262 1 : if r.err != nil {
1263 0 : return nil, r.Close()
1264 0 : }
1265 :
1266 1 : return r, nil
1267 : }
1268 :
1269 : // ReadableFile describes the smallest subset of vfs.File that is required for
1270 : // reading SSTs.
1271 : type ReadableFile interface {
1272 : io.ReaderAt
1273 : io.Closer
1274 : Stat() (os.FileInfo, error)
1275 : }
1276 :
1277 : // NewSimpleReadable wraps a ReadableFile in a objstorage.Readable
1278 : // implementation (which does not support read-ahead)
1279 1 : func NewSimpleReadable(r ReadableFile) (objstorage.Readable, error) {
1280 1 : info, err := r.Stat()
1281 1 : if err != nil {
1282 0 : return nil, err
1283 0 : }
1284 1 : res := &simpleReadable{
1285 1 : f: r,
1286 1 : size: info.Size(),
1287 1 : }
1288 1 : res.rh = objstorage.MakeNoopReadHandle(res)
1289 1 : return res, nil
1290 : }
1291 :
1292 : // simpleReadable wraps a ReadableFile to implement objstorage.Readable.
1293 : type simpleReadable struct {
1294 : f ReadableFile
1295 : size int64
1296 : rh objstorage.NoopReadHandle
1297 : }
1298 :
1299 : var _ objstorage.Readable = (*simpleReadable)(nil)
1300 :
1301 : // ReadAt is part of the objstorage.Readable interface.
1302 1 : func (s *simpleReadable) ReadAt(_ context.Context, p []byte, off int64) error {
1303 1 : n, err := s.f.ReadAt(p, off)
1304 1 : if invariants.Enabled && err == nil && n != len(p) {
1305 0 : panic("short read")
1306 : }
1307 1 : return err
1308 : }
1309 :
1310 : // Close is part of the objstorage.Readable interface.
1311 1 : func (s *simpleReadable) Close() error {
1312 1 : return s.f.Close()
1313 1 : }
1314 :
1315 : // Size is part of the objstorage.Readable interface.
1316 1 : func (s *simpleReadable) Size() int64 {
1317 1 : return s.size
1318 1 : }
1319 :
1320 : // NewReaddHandle is part of the objstorage.Readable interface.
1321 1 : func (s *simpleReadable) NewReadHandle(_ context.Context) objstorage.ReadHandle {
1322 1 : return &s.rh
1323 1 : }
1324 :
1325 0 : func errCorruptIndexEntry(err error) error {
1326 0 : err = base.CorruptionErrorf("pebble/table: corrupt index entry: %v", err)
1327 0 : if invariants.Enabled {
1328 0 : panic(err)
1329 : }
1330 0 : return err
1331 : }
|