LCOV - code coverage report
Current view: top level - pebble/sstable - reader.go (source / functions) Hit Total Coverage
Test: 2024-01-20 08:15Z 5b092519 - tests only.lcov Lines: 729 825 88.4 %
Date: 2024-01-20 08:16:21 Functions: 0 0 -

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

Generated by: LCOV version 1.14