LCOV - code coverage report
Current view: top level - pebble - db.go (source / functions) Hit Total Coverage
Test: 2024-03-02 08:15Z dd51d85c - tests only.lcov Lines: 1500 1728 86.8 %
Date: 2024-03-02 08:16:35 Functions: 0 0 -

          Line data    Source code
       1             : // Copyright 2012 The LevelDB-Go and Pebble Authors. All rights reserved. Use
       2             : // of this source code is governed by a BSD-style license that can be found in
       3             : // the LICENSE file.
       4             : 
       5             : // Package pebble provides an ordered key/value store.
       6             : package pebble // import "github.com/cockroachdb/pebble"
       7             : 
       8             : import (
       9             :         "context"
      10             :         "fmt"
      11             :         "io"
      12             :         "strconv"
      13             :         "sync"
      14             :         "sync/atomic"
      15             :         "time"
      16             : 
      17             :         "github.com/cockroachdb/errors"
      18             :         "github.com/cockroachdb/pebble/internal/arenaskl"
      19             :         "github.com/cockroachdb/pebble/internal/base"
      20             :         "github.com/cockroachdb/pebble/internal/invalidating"
      21             :         "github.com/cockroachdb/pebble/internal/invariants"
      22             :         "github.com/cockroachdb/pebble/internal/keyspan"
      23             :         "github.com/cockroachdb/pebble/internal/keyspan/keyspanimpl"
      24             :         "github.com/cockroachdb/pebble/internal/manifest"
      25             :         "github.com/cockroachdb/pebble/internal/manual"
      26             :         "github.com/cockroachdb/pebble/objstorage"
      27             :         "github.com/cockroachdb/pebble/objstorage/remote"
      28             :         "github.com/cockroachdb/pebble/rangekey"
      29             :         "github.com/cockroachdb/pebble/record"
      30             :         "github.com/cockroachdb/pebble/sstable"
      31             :         "github.com/cockroachdb/pebble/vfs"
      32             :         "github.com/cockroachdb/pebble/vfs/atomicfs"
      33             :         "github.com/cockroachdb/pebble/wal"
      34             :         "github.com/cockroachdb/tokenbucket"
      35             :         "github.com/prometheus/client_golang/prometheus"
      36             : )
      37             : 
      38             : const (
      39             :         // minTableCacheSize is the minimum size of the table cache, for a single db.
      40             :         minTableCacheSize = 64
      41             : 
      42             :         // numNonTableCacheFiles is an approximation for the number of files
      43             :         // that we don't use for table caches, for a given db.
      44             :         numNonTableCacheFiles = 10
      45             : )
      46             : 
      47             : var (
      48             :         // ErrNotFound is returned when a get operation does not find the requested
      49             :         // key.
      50             :         ErrNotFound = base.ErrNotFound
      51             :         // ErrClosed is panicked when an operation is performed on a closed snapshot or
      52             :         // DB. Use errors.Is(err, ErrClosed) to check for this error.
      53             :         ErrClosed = errors.New("pebble: closed")
      54             :         // ErrReadOnly is returned when a write operation is performed on a read-only
      55             :         // database.
      56             :         ErrReadOnly = errors.New("pebble: read-only")
      57             :         // errNoSplit indicates that the user is trying to perform a range key
      58             :         // operation but the configured Comparer does not provide a Split
      59             :         // implementation.
      60             :         errNoSplit = errors.New("pebble: Comparer.Split required for range key operations")
      61             : )
      62             : 
      63             : // Reader is a readable key/value store.
      64             : //
      65             : // It is safe to call Get and NewIter from concurrent goroutines.
      66             : type Reader interface {
      67             :         // Get gets the value for the given key. It returns ErrNotFound if the DB
      68             :         // does not contain the key.
      69             :         //
      70             :         // The caller should not modify the contents of the returned slice, but it is
      71             :         // safe to modify the contents of the argument after Get returns. The
      72             :         // returned slice will remain valid until the returned Closer is closed. On
      73             :         // success, the caller MUST call closer.Close() or a memory leak will occur.
      74             :         Get(key []byte) (value []byte, closer io.Closer, err error)
      75             : 
      76             :         // NewIter returns an iterator that is unpositioned (Iterator.Valid() will
      77             :         // return false). The iterator can be positioned via a call to SeekGE,
      78             :         // SeekLT, First or Last.
      79             :         NewIter(o *IterOptions) (*Iterator, error)
      80             : 
      81             :         // NewIterWithContext is like NewIter, and additionally accepts a context
      82             :         // for tracing.
      83             :         NewIterWithContext(ctx context.Context, o *IterOptions) (*Iterator, error)
      84             : 
      85             :         // Close closes the Reader. It may or may not close any underlying io.Reader
      86             :         // or io.Writer, depending on how the DB was created.
      87             :         //
      88             :         // It is not safe to close a DB until all outstanding iterators are closed.
      89             :         // It is valid to call Close multiple times. Other methods should not be
      90             :         // called after the DB has been closed.
      91             :         Close() error
      92             : }
      93             : 
      94             : // Writer is a writable key/value store.
      95             : //
      96             : // Goroutine safety is dependent on the specific implementation.
      97             : type Writer interface {
      98             :         // Apply the operations contained in the batch to the DB.
      99             :         //
     100             :         // It is safe to modify the contents of the arguments after Apply returns.
     101             :         Apply(batch *Batch, o *WriteOptions) error
     102             : 
     103             :         // Delete deletes the value for the given key. Deletes are blind all will
     104             :         // succeed even if the given key does not exist.
     105             :         //
     106             :         // It is safe to modify the contents of the arguments after Delete returns.
     107             :         Delete(key []byte, o *WriteOptions) error
     108             : 
     109             :         // DeleteSized behaves identically to Delete, but takes an additional
     110             :         // argument indicating the size of the value being deleted. DeleteSized
     111             :         // should be preferred when the caller has the expectation that there exists
     112             :         // a single internal KV pair for the key (eg, the key has not been
     113             :         // overwritten recently), and the caller knows the size of its value.
     114             :         //
     115             :         // DeleteSized will record the value size within the tombstone and use it to
     116             :         // inform compaction-picking heuristics which strive to reduce space
     117             :         // amplification in the LSM. This "calling your shot" mechanic allows the
     118             :         // storage engine to more accurately estimate and reduce space
     119             :         // amplification.
     120             :         //
     121             :         // It is safe to modify the contents of the arguments after DeleteSized
     122             :         // returns.
     123             :         DeleteSized(key []byte, valueSize uint32, _ *WriteOptions) error
     124             : 
     125             :         // SingleDelete is similar to Delete in that it deletes the value for the given key. Like Delete,
     126             :         // it is a blind operation that will succeed even if the given key does not exist.
     127             :         //
     128             :         // WARNING: Undefined (non-deterministic) behavior will result if a key is overwritten and
     129             :         // then deleted using SingleDelete. The record may appear deleted immediately, but be
     130             :         // resurrected at a later time after compactions have been performed. Or the record may
     131             :         // be deleted permanently. A Delete operation lays down a "tombstone" which shadows all
     132             :         // previous versions of a key. The SingleDelete operation is akin to "anti-matter" and will
     133             :         // only delete the most recently written version for a key. These different semantics allow
     134             :         // the DB to avoid propagating a SingleDelete operation during a compaction as soon as the
     135             :         // corresponding Set operation is encountered. These semantics require extreme care to handle
     136             :         // properly. Only use if you have a workload where the performance gain is critical and you
     137             :         // can guarantee that a record is written once and then deleted once.
     138             :         //
     139             :         // SingleDelete is internally transformed into a Delete if the most recent record for a key is either
     140             :         // a Merge or Delete record.
     141             :         //
     142             :         // It is safe to modify the contents of the arguments after SingleDelete returns.
     143             :         SingleDelete(key []byte, o *WriteOptions) error
     144             : 
     145             :         // DeleteRange deletes all of the point keys (and values) in the range
     146             :         // [start,end) (inclusive on start, exclusive on end). DeleteRange does NOT
     147             :         // delete overlapping range keys (eg, keys set via RangeKeySet).
     148             :         //
     149             :         // It is safe to modify the contents of the arguments after DeleteRange
     150             :         // returns.
     151             :         DeleteRange(start, end []byte, o *WriteOptions) error
     152             : 
     153             :         // LogData adds the specified to the batch. The data will be written to the
     154             :         // WAL, but not added to memtables or sstables. Log data is never indexed,
     155             :         // which makes it useful for testing WAL performance.
     156             :         //
     157             :         // It is safe to modify the contents of the argument after LogData returns.
     158             :         LogData(data []byte, opts *WriteOptions) error
     159             : 
     160             :         // Merge merges the value for the given key. The details of the merge are
     161             :         // dependent upon the configured merge operation.
     162             :         //
     163             :         // It is safe to modify the contents of the arguments after Merge returns.
     164             :         Merge(key, value []byte, o *WriteOptions) error
     165             : 
     166             :         // Set sets the value for the given key. It overwrites any previous value
     167             :         // for that key; a DB is not a multi-map.
     168             :         //
     169             :         // It is safe to modify the contents of the arguments after Set returns.
     170             :         Set(key, value []byte, o *WriteOptions) error
     171             : 
     172             :         // RangeKeySet sets a range key mapping the key range [start, end) at the MVCC
     173             :         // timestamp suffix to value. The suffix is optional. If any portion of the key
     174             :         // range [start, end) is already set by a range key with the same suffix value,
     175             :         // RangeKeySet overrides it.
     176             :         //
     177             :         // It is safe to modify the contents of the arguments after RangeKeySet returns.
     178             :         RangeKeySet(start, end, suffix, value []byte, opts *WriteOptions) error
     179             : 
     180             :         // RangeKeyUnset removes a range key mapping the key range [start, end) at the
     181             :         // MVCC timestamp suffix. The suffix may be omitted to remove an unsuffixed
     182             :         // range key. RangeKeyUnset only removes portions of range keys that fall within
     183             :         // the [start, end) key span, and only range keys with suffixes that exactly
     184             :         // match the unset suffix.
     185             :         //
     186             :         // It is safe to modify the contents of the arguments after RangeKeyUnset
     187             :         // returns.
     188             :         RangeKeyUnset(start, end, suffix []byte, opts *WriteOptions) error
     189             : 
     190             :         // RangeKeyDelete deletes all of the range keys in the range [start,end)
     191             :         // (inclusive on start, exclusive on end). It does not delete point keys (for
     192             :         // that use DeleteRange). RangeKeyDelete removes all range keys within the
     193             :         // bounds, including those with or without suffixes.
     194             :         //
     195             :         // It is safe to modify the contents of the arguments after RangeKeyDelete
     196             :         // returns.
     197             :         RangeKeyDelete(start, end []byte, opts *WriteOptions) error
     198             : }
     199             : 
     200             : // CPUWorkHandle represents a handle used by the CPUWorkPermissionGranter API.
     201             : type CPUWorkHandle interface {
     202             :         // Permitted indicates whether Pebble can use additional CPU resources.
     203             :         Permitted() bool
     204             : }
     205             : 
     206             : // CPUWorkPermissionGranter is used to request permission to opportunistically
     207             : // use additional CPUs to speed up internal background work.
     208             : type CPUWorkPermissionGranter interface {
     209             :         // GetPermission returns a handle regardless of whether permission is granted
     210             :         // or not. In the latter case, the handle is only useful for recording
     211             :         // the CPU time actually spent on this calling goroutine.
     212             :         GetPermission(time.Duration) CPUWorkHandle
     213             :         // CPUWorkDone must be called regardless of whether CPUWorkHandle.Permitted
     214             :         // returns true or false.
     215             :         CPUWorkDone(CPUWorkHandle)
     216             : }
     217             : 
     218             : // Use a default implementation for the CPU work granter to avoid excessive nil
     219             : // checks in the code.
     220             : type defaultCPUWorkHandle struct{}
     221             : 
     222           1 : func (d defaultCPUWorkHandle) Permitted() bool {
     223           1 :         return false
     224           1 : }
     225             : 
     226             : type defaultCPUWorkGranter struct{}
     227             : 
     228           1 : func (d defaultCPUWorkGranter) GetPermission(_ time.Duration) CPUWorkHandle {
     229           1 :         return defaultCPUWorkHandle{}
     230           1 : }
     231             : 
     232           1 : func (d defaultCPUWorkGranter) CPUWorkDone(_ CPUWorkHandle) {}
     233             : 
     234             : // DB provides a concurrent, persistent ordered key/value store.
     235             : //
     236             : // A DB's basic operations (Get, Set, Delete) should be self-explanatory. Get
     237             : // and Delete will return ErrNotFound if the requested key is not in the store.
     238             : // Callers are free to ignore this error.
     239             : //
     240             : // A DB also allows for iterating over the key/value pairs in key order. If d
     241             : // is a DB, the code below prints all key/value pairs whose keys are 'greater
     242             : // than or equal to' k:
     243             : //
     244             : //      iter := d.NewIter(readOptions)
     245             : //      for iter.SeekGE(k); iter.Valid(); iter.Next() {
     246             : //              fmt.Printf("key=%q value=%q\n", iter.Key(), iter.Value())
     247             : //      }
     248             : //      return iter.Close()
     249             : //
     250             : // The Options struct holds the optional parameters for the DB, including a
     251             : // Comparer to define a 'less than' relationship over keys. It is always valid
     252             : // to pass a nil *Options, which means to use the default parameter values. Any
     253             : // zero field of a non-nil *Options also means to use the default value for
     254             : // that parameter. Thus, the code below uses a custom Comparer, but the default
     255             : // values for every other parameter:
     256             : //
     257             : //      db := pebble.Open(&Options{
     258             : //              Comparer: myComparer,
     259             : //      })
     260             : type DB struct {
     261             :         // The count and size of referenced memtables. This includes memtables
     262             :         // present in DB.mu.mem.queue, as well as memtables that have been flushed
     263             :         // but are still referenced by an inuse readState, as well as up to one
     264             :         // memTable waiting to be reused and stored in d.memTableRecycle.
     265             :         memTableCount    atomic.Int64
     266             :         memTableReserved atomic.Int64 // number of bytes reserved in the cache for memtables
     267             :         // memTableRecycle holds a pointer to an obsolete memtable. The next
     268             :         // memtable allocation will reuse this memtable if it has not already been
     269             :         // recycled.
     270             :         memTableRecycle atomic.Pointer[memTable]
     271             : 
     272             :         // The logical size of the current WAL.
     273             :         logSize atomic.Uint64
     274             : 
     275             :         // The number of bytes available on disk.
     276             :         diskAvailBytes atomic.Uint64
     277             : 
     278             :         cacheID        uint64
     279             :         dirname        string
     280             :         opts           *Options
     281             :         cmp            Compare
     282             :         equal          Equal
     283             :         merge          Merge
     284             :         split          Split
     285             :         abbreviatedKey AbbreviatedKey
     286             :         // The threshold for determining when a batch is "large" and will skip being
     287             :         // inserted into a memtable.
     288             :         largeBatchThreshold uint64
     289             :         // The current OPTIONS file number.
     290             :         optionsFileNum base.DiskFileNum
     291             :         // The on-disk size of the current OPTIONS file.
     292             :         optionsFileSize uint64
     293             : 
     294             :         // objProvider is used to access and manage SSTs.
     295             :         objProvider objstorage.Provider
     296             : 
     297             :         fileLock *Lock
     298             :         dataDir  vfs.File
     299             : 
     300             :         tableCache           *tableCacheContainer
     301             :         newIters             tableNewIters
     302             :         tableNewRangeKeyIter keyspanimpl.TableNewSpanIter
     303             : 
     304             :         commit *commitPipeline
     305             : 
     306             :         // readState provides access to the state needed for reading without needing
     307             :         // to acquire DB.mu.
     308             :         readState struct {
     309             :                 sync.RWMutex
     310             :                 val *readState
     311             :         }
     312             : 
     313             :         closed   *atomic.Value
     314             :         closedCh chan struct{}
     315             : 
     316             :         cleanupManager *cleanupManager
     317             : 
     318             :         // During an iterator close, we may asynchronously schedule read compactions.
     319             :         // We want to wait for those goroutines to finish, before closing the DB.
     320             :         // compactionShedulers.Wait() should not be called while the DB.mu is held.
     321             :         compactionSchedulers sync.WaitGroup
     322             : 
     323             :         // The main mutex protecting internal DB state. This mutex encompasses many
     324             :         // fields because those fields need to be accessed and updated atomically. In
     325             :         // particular, the current version, log.*, mem.*, and snapshot list need to
     326             :         // be accessed and updated atomically during compaction.
     327             :         //
     328             :         // Care is taken to avoid holding DB.mu during IO operations. Accomplishing
     329             :         // this sometimes requires releasing DB.mu in a method that was called with
     330             :         // it held. See versionSet.logAndApply() and DB.makeRoomForWrite() for
     331             :         // examples. This is a common pattern, so be careful about expectations that
     332             :         // DB.mu will be held continuously across a set of calls.
     333             :         mu struct {
     334             :                 sync.Mutex
     335             : 
     336             :                 formatVers struct {
     337             :                         // vers is the database's current format major version.
     338             :                         // Backwards-incompatible features are gated behind new
     339             :                         // format major versions and not enabled until a database's
     340             :                         // version is ratcheted upwards.
     341             :                         //
     342             :                         // Although this is under the `mu` prefix, readers may read vers
     343             :                         // atomically without holding d.mu. Writers must only write to this
     344             :                         // value through finalizeFormatVersUpgrade which requires d.mu is
     345             :                         // held.
     346             :                         vers atomic.Uint64
     347             :                         // marker is the atomic marker for the format major version.
     348             :                         // When a database's version is ratcheted upwards, the
     349             :                         // marker is moved in order to atomically record the new
     350             :                         // version.
     351             :                         marker *atomicfs.Marker
     352             :                         // ratcheting when set to true indicates that the database is
     353             :                         // currently in the process of ratcheting the format major version
     354             :                         // to vers + 1. As a part of ratcheting the format major version,
     355             :                         // migrations may drop and re-acquire the mutex.
     356             :                         ratcheting bool
     357             :                 }
     358             : 
     359             :                 // The ID of the next job. Job IDs are passed to event listener
     360             :                 // notifications and act as a mechanism for tying together the events and
     361             :                 // log messages for a single job such as a flush, compaction, or file
     362             :                 // ingestion. Job IDs are not serialized to disk or used for correctness.
     363             :                 nextJobID int
     364             : 
     365             :                 // The collection of immutable versions and state about the log and visible
     366             :                 // sequence numbers. Use the pointer here to ensure the atomic fields in
     367             :                 // version set are aligned properly.
     368             :                 versions *versionSet
     369             : 
     370             :                 log struct {
     371             :                         // manager is not protected by mu, but calls to Create must be
     372             :                         // serialized, and happen after the previous writer is closed.
     373             :                         manager wal.Manager
     374             :                         // The number of input bytes to the log. This is the raw size of the
     375             :                         // batches written to the WAL, without the overhead of the record
     376             :                         // envelopes.
     377             :                         bytesIn uint64
     378             :                         // The Writer is protected by commitPipeline.mu. This allows log writes
     379             :                         // to be performed without holding DB.mu, but requires both
     380             :                         // commitPipeline.mu and DB.mu to be held when rotating the WAL/memtable
     381             :                         // (i.e. makeRoomForWrite). Can be nil.
     382             :                         writer  wal.Writer
     383             :                         metrics struct {
     384             :                                 // fsyncLatency has its own internal synchronization, and is not
     385             :                                 // protected by mu.
     386             :                                 fsyncLatency prometheus.Histogram
     387             :                                 // Updated whenever a wal.Writer is closed.
     388             :                                 record.LogWriterMetrics
     389             :                         }
     390             :                 }
     391             : 
     392             :                 mem struct {
     393             :                         // The current mutable memTable.
     394             :                         mutable *memTable
     395             :                         // Queue of flushables (the mutable memtable is at end). Elements are
     396             :                         // added to the end of the slice and removed from the beginning. Once an
     397             :                         // index is set it is never modified making a fixed slice immutable and
     398             :                         // safe for concurrent reads.
     399             :                         queue flushableList
     400             :                         // nextSize is the size of the next memtable. The memtable size starts at
     401             :                         // min(256KB,Options.MemTableSize) and doubles each time a new memtable
     402             :                         // is allocated up to Options.MemTableSize. This reduces the memory
     403             :                         // footprint of memtables when lots of DB instances are used concurrently
     404             :                         // in test environments.
     405             :                         nextSize uint64
     406             :                 }
     407             : 
     408             :                 compact struct {
     409             :                         // Condition variable used to signal when a flush or compaction has
     410             :                         // completed. Used by the write-stall mechanism to wait for the stall
     411             :                         // condition to clear. See DB.makeRoomForWrite().
     412             :                         cond sync.Cond
     413             :                         // True when a flush is in progress.
     414             :                         flushing bool
     415             :                         // The number of ongoing compactions.
     416             :                         compactingCount int
     417             :                         // The list of deletion hints, suggesting ranges for delete-only
     418             :                         // compactions.
     419             :                         deletionHints []deleteCompactionHint
     420             :                         // The list of manual compactions. The next manual compaction to perform
     421             :                         // is at the start of the list. New entries are added to the end.
     422             :                         manual []*manualCompaction
     423             :                         // downloads is the list of suggested download tasks. The next download to
     424             :                         // perform is at the start of the list. New entries are added to the end.
     425             :                         downloads []*downloadSpan
     426             :                         // inProgress is the set of in-progress flushes and compactions.
     427             :                         // It's used in the calculation of some metrics and to initialize L0
     428             :                         // sublevels' state. Some of the compactions contained within this
     429             :                         // map may have already committed an edit to the version but are
     430             :                         // lingering performing cleanup, like deleting obsolete files.
     431             :                         inProgress map[*compaction]struct{}
     432             : 
     433             :                         // rescheduleReadCompaction indicates to an iterator that a read compaction
     434             :                         // should be scheduled.
     435             :                         rescheduleReadCompaction bool
     436             : 
     437             :                         // readCompactions is a readCompactionQueue which keeps track of the
     438             :                         // compactions which we might have to perform.
     439             :                         readCompactions readCompactionQueue
     440             : 
     441             :                         // The cumulative duration of all completed compactions since Open.
     442             :                         // Does not include flushes.
     443             :                         duration time.Duration
     444             :                         // Flush throughput metric.
     445             :                         flushWriteThroughput ThroughputMetric
     446             :                         // The idle start time for the flush "loop", i.e., when the flushing
     447             :                         // bool above transitions to false.
     448             :                         noOngoingFlushStartTime time.Time
     449             :                 }
     450             : 
     451             :                 // Non-zero when file cleaning is disabled. The disabled count acts as a
     452             :                 // reference count to prohibit file cleaning. See
     453             :                 // DB.{disable,Enable}FileDeletions().
     454             :                 disableFileDeletions int
     455             : 
     456             :                 snapshots struct {
     457             :                         // The list of active snapshots.
     458             :                         snapshotList
     459             : 
     460             :                         // The cumulative count and size of snapshot-pinned keys written to
     461             :                         // sstables.
     462             :                         cumulativePinnedCount uint64
     463             :                         cumulativePinnedSize  uint64
     464             :                 }
     465             : 
     466             :                 tableStats struct {
     467             :                         // Condition variable used to signal the completion of a
     468             :                         // job to collect table stats.
     469             :                         cond sync.Cond
     470             :                         // True when a stat collection operation is in progress.
     471             :                         loading bool
     472             :                         // True if stat collection has loaded statistics for all tables
     473             :                         // other than those listed explicitly in pending. This flag starts
     474             :                         // as false when a database is opened and flips to true once stat
     475             :                         // collection has caught up.
     476             :                         loadedInitial bool
     477             :                         // A slice of files for which stats have not been computed.
     478             :                         // Compactions, ingests, flushes append files to be processed. An
     479             :                         // active stat collection goroutine clears the list and processes
     480             :                         // them.
     481             :                         pending []manifest.NewFileEntry
     482             :                 }
     483             : 
     484             :                 tableValidation struct {
     485             :                         // cond is a condition variable used to signal the completion of a
     486             :                         // job to validate one or more sstables.
     487             :                         cond sync.Cond
     488             :                         // pending is a slice of metadata for sstables waiting to be
     489             :                         // validated. Only physical sstables should be added to the pending
     490             :                         // queue.
     491             :                         pending []newFileEntry
     492             :                         // validating is set to true when validation is running.
     493             :                         validating bool
     494             :                 }
     495             :         }
     496             : 
     497             :         // Normally equal to time.Now() but may be overridden in tests.
     498             :         timeNow func() time.Time
     499             :         // the time at database Open; may be used to compute metrics like effective
     500             :         // compaction concurrency
     501             :         openedAt time.Time
     502             : }
     503             : 
     504             : var _ Reader = (*DB)(nil)
     505             : var _ Writer = (*DB)(nil)
     506             : 
     507             : // TestOnlyWaitForCleaning MUST only be used in tests.
     508           1 : func (d *DB) TestOnlyWaitForCleaning() {
     509           1 :         d.cleanupManager.Wait()
     510           1 : }
     511             : 
     512             : // Get gets the value for the given key. It returns ErrNotFound if the DB does
     513             : // not contain the key.
     514             : //
     515             : // The caller should not modify the contents of the returned slice, but it is
     516             : // safe to modify the contents of the argument after Get returns. The returned
     517             : // slice will remain valid until the returned Closer is closed. On success, the
     518             : // caller MUST call closer.Close() or a memory leak will occur.
     519           1 : func (d *DB) Get(key []byte) ([]byte, io.Closer, error) {
     520           1 :         return d.getInternal(key, nil /* batch */, nil /* snapshot */)
     521           1 : }
     522             : 
     523             : type getIterAlloc struct {
     524             :         dbi    Iterator
     525             :         keyBuf []byte
     526             :         get    getIter
     527             : }
     528             : 
     529             : var getIterAllocPool = sync.Pool{
     530           1 :         New: func() interface{} {
     531           1 :                 return &getIterAlloc{}
     532           1 :         },
     533             : }
     534             : 
     535           1 : func (d *DB) getInternal(key []byte, b *Batch, s *Snapshot) ([]byte, io.Closer, error) {
     536           1 :         if err := d.closed.Load(); err != nil {
     537           1 :                 panic(err)
     538             :         }
     539             : 
     540             :         // Grab and reference the current readState. This prevents the underlying
     541             :         // files in the associated version from being deleted if there is a current
     542             :         // compaction. The readState is unref'd by Iterator.Close().
     543           1 :         readState := d.loadReadState()
     544           1 : 
     545           1 :         // Determine the seqnum to read at after grabbing the read state (current and
     546           1 :         // memtables) above.
     547           1 :         var seqNum uint64
     548           1 :         if s != nil {
     549           1 :                 seqNum = s.seqNum
     550           1 :         } else {
     551           1 :                 seqNum = d.mu.versions.visibleSeqNum.Load()
     552           1 :         }
     553             : 
     554           1 :         buf := getIterAllocPool.Get().(*getIterAlloc)
     555           1 : 
     556           1 :         get := &buf.get
     557           1 :         *get = getIter{
     558           1 :                 logger:   d.opts.Logger,
     559           1 :                 comparer: d.opts.Comparer,
     560           1 :                 newIters: d.newIters,
     561           1 :                 snapshot: seqNum,
     562           1 :                 key:      key,
     563           1 :                 batch:    b,
     564           1 :                 mem:      readState.memtables,
     565           1 :                 l0:       readState.current.L0SublevelFiles,
     566           1 :                 version:  readState.current,
     567           1 :         }
     568           1 : 
     569           1 :         // Strip off memtables which cannot possibly contain the seqNum being read
     570           1 :         // at.
     571           1 :         for len(get.mem) > 0 {
     572           1 :                 n := len(get.mem)
     573           1 :                 if logSeqNum := get.mem[n-1].logSeqNum; logSeqNum < seqNum {
     574           1 :                         break
     575             :                 }
     576           1 :                 get.mem = get.mem[:n-1]
     577             :         }
     578             : 
     579           1 :         i := &buf.dbi
     580           1 :         pointIter := get
     581           1 :         *i = Iterator{
     582           1 :                 ctx:          context.Background(),
     583           1 :                 getIterAlloc: buf,
     584           1 :                 iter:         pointIter,
     585           1 :                 pointIter:    pointIter,
     586           1 :                 merge:        d.merge,
     587           1 :                 comparer:     *d.opts.Comparer,
     588           1 :                 readState:    readState,
     589           1 :                 keyBuf:       buf.keyBuf,
     590           1 :         }
     591           1 : 
     592           1 :         if !i.First() {
     593           1 :                 err := i.Close()
     594           1 :                 if err != nil {
     595           1 :                         return nil, nil, err
     596           1 :                 }
     597           1 :                 return nil, nil, ErrNotFound
     598             :         }
     599           1 :         return i.Value(), i, nil
     600             : }
     601             : 
     602             : // Set sets the value for the given key. It overwrites any previous value
     603             : // for that key; a DB is not a multi-map.
     604             : //
     605             : // It is safe to modify the contents of the arguments after Set returns.
     606           1 : func (d *DB) Set(key, value []byte, opts *WriteOptions) error {
     607           1 :         b := newBatch(d)
     608           1 :         _ = b.Set(key, value, opts)
     609           1 :         if err := d.Apply(b, opts); err != nil {
     610           1 :                 return err
     611           1 :         }
     612             :         // Only release the batch on success.
     613           1 :         b.release()
     614           1 :         return nil
     615             : }
     616             : 
     617             : // Delete deletes the value for the given key. Deletes are blind all will
     618             : // succeed even if the given key does not exist.
     619             : //
     620             : // It is safe to modify the contents of the arguments after Delete returns.
     621           1 : func (d *DB) Delete(key []byte, opts *WriteOptions) error {
     622           1 :         b := newBatch(d)
     623           1 :         _ = b.Delete(key, opts)
     624           1 :         if err := d.Apply(b, opts); err != nil {
     625           1 :                 return err
     626           1 :         }
     627             :         // Only release the batch on success.
     628           1 :         b.release()
     629           1 :         return nil
     630             : }
     631             : 
     632             : // DeleteSized behaves identically to Delete, but takes an additional
     633             : // argument indicating the size of the value being deleted. DeleteSized
     634             : // should be preferred when the caller has the expectation that there exists
     635             : // a single internal KV pair for the key (eg, the key has not been
     636             : // overwritten recently), and the caller knows the size of its value.
     637             : //
     638             : // DeleteSized will record the value size within the tombstone and use it to
     639             : // inform compaction-picking heuristics which strive to reduce space
     640             : // amplification in the LSM. This "calling your shot" mechanic allows the
     641             : // storage engine to more accurately estimate and reduce space amplification.
     642             : //
     643             : // It is safe to modify the contents of the arguments after DeleteSized
     644             : // returns.
     645           0 : func (d *DB) DeleteSized(key []byte, valueSize uint32, opts *WriteOptions) error {
     646           0 :         b := newBatch(d)
     647           0 :         _ = b.DeleteSized(key, valueSize, opts)
     648           0 :         if err := d.Apply(b, opts); err != nil {
     649           0 :                 return err
     650           0 :         }
     651             :         // Only release the batch on success.
     652           0 :         b.release()
     653           0 :         return nil
     654             : }
     655             : 
     656             : // SingleDelete adds an action to the batch that single deletes the entry for key.
     657             : // See Writer.SingleDelete for more details on the semantics of SingleDelete.
     658             : //
     659             : // It is safe to modify the contents of the arguments after SingleDelete returns.
     660           1 : func (d *DB) SingleDelete(key []byte, opts *WriteOptions) error {
     661           1 :         b := newBatch(d)
     662           1 :         _ = b.SingleDelete(key, opts)
     663           1 :         if err := d.Apply(b, opts); err != nil {
     664           0 :                 return err
     665           0 :         }
     666             :         // Only release the batch on success.
     667           1 :         b.release()
     668           1 :         return nil
     669             : }
     670             : 
     671             : // DeleteRange deletes all of the keys (and values) in the range [start,end)
     672             : // (inclusive on start, exclusive on end).
     673             : //
     674             : // It is safe to modify the contents of the arguments after DeleteRange
     675             : // returns.
     676           1 : func (d *DB) DeleteRange(start, end []byte, opts *WriteOptions) error {
     677           1 :         b := newBatch(d)
     678           1 :         _ = b.DeleteRange(start, end, opts)
     679           1 :         if err := d.Apply(b, opts); err != nil {
     680           1 :                 return err
     681           1 :         }
     682             :         // Only release the batch on success.
     683           1 :         b.release()
     684           1 :         return nil
     685             : }
     686             : 
     687             : // Merge adds an action to the DB that merges the value at key with the new
     688             : // value. The details of the merge are dependent upon the configured merge
     689             : // operator.
     690             : //
     691             : // It is safe to modify the contents of the arguments after Merge returns.
     692           1 : func (d *DB) Merge(key, value []byte, opts *WriteOptions) error {
     693           1 :         b := newBatch(d)
     694           1 :         _ = b.Merge(key, value, opts)
     695           1 :         if err := d.Apply(b, opts); err != nil {
     696           1 :                 return err
     697           1 :         }
     698             :         // Only release the batch on success.
     699           1 :         b.release()
     700           1 :         return nil
     701             : }
     702             : 
     703             : // LogData adds the specified to the batch. The data will be written to the
     704             : // WAL, but not added to memtables or sstables. Log data is never indexed,
     705             : // which makes it useful for testing WAL performance.
     706             : //
     707             : // It is safe to modify the contents of the argument after LogData returns.
     708           1 : func (d *DB) LogData(data []byte, opts *WriteOptions) error {
     709           1 :         b := newBatch(d)
     710           1 :         _ = b.LogData(data, opts)
     711           1 :         if err := d.Apply(b, opts); err != nil {
     712           1 :                 return err
     713           1 :         }
     714             :         // Only release the batch on success.
     715           1 :         b.release()
     716           1 :         return nil
     717             : }
     718             : 
     719             : // RangeKeySet sets a range key mapping the key range [start, end) at the MVCC
     720             : // timestamp suffix to value. The suffix is optional. If any portion of the key
     721             : // range [start, end) is already set by a range key with the same suffix value,
     722             : // RangeKeySet overrides it.
     723             : //
     724             : // It is safe to modify the contents of the arguments after RangeKeySet returns.
     725           1 : func (d *DB) RangeKeySet(start, end, suffix, value []byte, opts *WriteOptions) error {
     726           1 :         b := newBatch(d)
     727           1 :         _ = b.RangeKeySet(start, end, suffix, value, opts)
     728           1 :         if err := d.Apply(b, opts); err != nil {
     729           0 :                 return err
     730           0 :         }
     731             :         // Only release the batch on success.
     732           1 :         b.release()
     733           1 :         return nil
     734             : }
     735             : 
     736             : // RangeKeyUnset removes a range key mapping the key range [start, end) at the
     737             : // MVCC timestamp suffix. The suffix may be omitted to remove an unsuffixed
     738             : // range key. RangeKeyUnset only removes portions of range keys that fall within
     739             : // the [start, end) key span, and only range keys with suffixes that exactly
     740             : // match the unset suffix.
     741             : //
     742             : // It is safe to modify the contents of the arguments after RangeKeyUnset
     743             : // returns.
     744           1 : func (d *DB) RangeKeyUnset(start, end, suffix []byte, opts *WriteOptions) error {
     745           1 :         b := newBatch(d)
     746           1 :         _ = b.RangeKeyUnset(start, end, suffix, opts)
     747           1 :         if err := d.Apply(b, opts); err != nil {
     748           0 :                 return err
     749           0 :         }
     750             :         // Only release the batch on success.
     751           1 :         b.release()
     752           1 :         return nil
     753             : }
     754             : 
     755             : // RangeKeyDelete deletes all of the range keys in the range [start,end)
     756             : // (inclusive on start, exclusive on end). It does not delete point keys (for
     757             : // that use DeleteRange). RangeKeyDelete removes all range keys within the
     758             : // bounds, including those with or without suffixes.
     759             : //
     760             : // It is safe to modify the contents of the arguments after RangeKeyDelete
     761             : // returns.
     762           1 : func (d *DB) RangeKeyDelete(start, end []byte, opts *WriteOptions) error {
     763           1 :         b := newBatch(d)
     764           1 :         _ = b.RangeKeyDelete(start, end, opts)
     765           1 :         if err := d.Apply(b, opts); err != nil {
     766           0 :                 return err
     767           0 :         }
     768             :         // Only release the batch on success.
     769           1 :         b.release()
     770           1 :         return nil
     771             : }
     772             : 
     773             : // Apply the operations contained in the batch to the DB. If the batch is large
     774             : // the contents of the batch may be retained by the database. If that occurs
     775             : // the batch contents will be cleared preventing the caller from attempting to
     776             : // reuse them.
     777             : //
     778             : // It is safe to modify the contents of the arguments after Apply returns.
     779             : //
     780             : // Apply returns ErrInvalidBatch if the provided batch is invalid in any way.
     781           1 : func (d *DB) Apply(batch *Batch, opts *WriteOptions) error {
     782           1 :         return d.applyInternal(batch, opts, false)
     783           1 : }
     784             : 
     785             : // ApplyNoSyncWait must only be used when opts.Sync is true and the caller
     786             : // does not want to wait for the WAL fsync to happen. The method will return
     787             : // once the mutation is applied to the memtable and is visible (note that a
     788             : // mutation is visible before the WAL sync even in the wait case, so we have
     789             : // not weakened the durability semantics). The caller must call Batch.SyncWait
     790             : // to wait for the WAL fsync. The caller must not Close the batch without
     791             : // first calling Batch.SyncWait.
     792             : //
     793             : // RECOMMENDATION: Prefer using Apply unless you really understand why you
     794             : // need ApplyNoSyncWait.
     795             : // EXPERIMENTAL: API/feature subject to change. Do not yet use outside
     796             : // CockroachDB.
     797           1 : func (d *DB) ApplyNoSyncWait(batch *Batch, opts *WriteOptions) error {
     798           1 :         if !opts.Sync {
     799           0 :                 return errors.Errorf("cannot request asynchonous apply when WriteOptions.Sync is false")
     800           0 :         }
     801           1 :         return d.applyInternal(batch, opts, true)
     802             : }
     803             : 
     804             : // REQUIRES: noSyncWait => opts.Sync
     805           1 : func (d *DB) applyInternal(batch *Batch, opts *WriteOptions, noSyncWait bool) error {
     806           1 :         if err := d.closed.Load(); err != nil {
     807           1 :                 panic(err)
     808             :         }
     809           1 :         if batch.committing {
     810           0 :                 panic("pebble: batch already committing")
     811             :         }
     812           1 :         if batch.applied.Load() {
     813           0 :                 panic("pebble: batch already applied")
     814             :         }
     815           1 :         if d.opts.ReadOnly {
     816           1 :                 return ErrReadOnly
     817           1 :         }
     818           1 :         if batch.db != nil && batch.db != d {
     819           1 :                 panic(fmt.Sprintf("pebble: batch db mismatch: %p != %p", batch.db, d))
     820             :         }
     821             : 
     822           1 :         sync := opts.GetSync()
     823           1 :         if sync && d.opts.DisableWAL {
     824           0 :                 return errors.New("pebble: WAL disabled")
     825           0 :         }
     826             : 
     827           1 :         if fmv := d.FormatMajorVersion(); fmv < batch.minimumFormatMajorVersion {
     828           0 :                 panic(fmt.Sprintf(
     829           0 :                         "pebble: batch requires at least format major version %d (current: %d)",
     830           0 :                         batch.minimumFormatMajorVersion, fmv,
     831           0 :                 ))
     832             :         }
     833             : 
     834           1 :         if batch.countRangeKeys > 0 {
     835           1 :                 if d.split == nil {
     836           0 :                         return errNoSplit
     837           0 :                 }
     838             :         }
     839           1 :         batch.committing = true
     840           1 : 
     841           1 :         if batch.db == nil {
     842           1 :                 if err := batch.refreshMemTableSize(); err != nil {
     843           0 :                         return err
     844           0 :                 }
     845             :         }
     846           1 :         if batch.memTableSize >= d.largeBatchThreshold {
     847           1 :                 var err error
     848           1 :                 batch.flushable, err = newFlushableBatch(batch, d.opts.Comparer)
     849           1 :                 if err != nil {
     850           0 :                         return err
     851           0 :                 }
     852             :         }
     853           1 :         if err := d.commit.Commit(batch, sync, noSyncWait); err != nil {
     854           0 :                 // There isn't much we can do on an error here. The commit pipeline will be
     855           0 :                 // horked at this point.
     856           0 :                 d.opts.Logger.Fatalf("pebble: fatal commit error: %v", err)
     857           0 :         }
     858             :         // If this is a large batch, we need to clear the batch contents as the
     859             :         // flushable batch may still be present in the flushables queue.
     860             :         //
     861             :         // TODO(peter): Currently large batches are written to the WAL. We could
     862             :         // skip the WAL write and instead wait for the large batch to be flushed to
     863             :         // an sstable. For a 100 MB batch, this might actually be faster. For a 1
     864             :         // GB batch this is almost certainly faster.
     865           1 :         if batch.flushable != nil {
     866           1 :                 batch.data = nil
     867           1 :         }
     868           1 :         return nil
     869             : }
     870             : 
     871           1 : func (d *DB) commitApply(b *Batch, mem *memTable) error {
     872           1 :         if b.flushable != nil {
     873           1 :                 // This is a large batch which was already added to the immutable queue.
     874           1 :                 return nil
     875           1 :         }
     876           1 :         err := mem.apply(b, b.SeqNum())
     877           1 :         if err != nil {
     878           0 :                 return err
     879           0 :         }
     880             : 
     881             :         // If the batch contains range tombstones and the database is configured
     882             :         // to flush range deletions, schedule a delayed flush so that disk space
     883             :         // may be reclaimed without additional writes or an explicit flush.
     884           1 :         if b.countRangeDels > 0 && d.opts.FlushDelayDeleteRange > 0 {
     885           1 :                 d.mu.Lock()
     886           1 :                 d.maybeScheduleDelayedFlush(mem, d.opts.FlushDelayDeleteRange)
     887           1 :                 d.mu.Unlock()
     888           1 :         }
     889             : 
     890             :         // If the batch contains range keys and the database is configured to flush
     891             :         // range keys, schedule a delayed flush so that the range keys are cleared
     892             :         // from the memtable.
     893           1 :         if b.countRangeKeys > 0 && d.opts.FlushDelayRangeKey > 0 {
     894           1 :                 d.mu.Lock()
     895           1 :                 d.maybeScheduleDelayedFlush(mem, d.opts.FlushDelayRangeKey)
     896           1 :                 d.mu.Unlock()
     897           1 :         }
     898             : 
     899           1 :         if mem.writerUnref() {
     900           1 :                 d.mu.Lock()
     901           1 :                 d.maybeScheduleFlush()
     902           1 :                 d.mu.Unlock()
     903           1 :         }
     904           1 :         return nil
     905             : }
     906             : 
     907           1 : func (d *DB) commitWrite(b *Batch, syncWG *sync.WaitGroup, syncErr *error) (*memTable, error) {
     908           1 :         var size int64
     909           1 :         repr := b.Repr()
     910           1 : 
     911           1 :         if b.flushable != nil {
     912           1 :                 // We have a large batch. Such batches are special in that they don't get
     913           1 :                 // added to the memtable, and are instead inserted into the queue of
     914           1 :                 // memtables. The call to makeRoomForWrite with this batch will force the
     915           1 :                 // current memtable to be flushed. We want the large batch to be part of
     916           1 :                 // the same log, so we add it to the WAL here, rather than after the call
     917           1 :                 // to makeRoomForWrite().
     918           1 :                 //
     919           1 :                 // Set the sequence number since it was not set to the correct value earlier
     920           1 :                 // (see comment in newFlushableBatch()).
     921           1 :                 b.flushable.setSeqNum(b.SeqNum())
     922           1 :                 if !d.opts.DisableWAL {
     923           1 :                         var err error
     924           1 :                         size, err = d.mu.log.writer.WriteRecord(repr, wal.SyncOptions{Done: syncWG, Err: syncErr})
     925           1 :                         if err != nil {
     926           0 :                                 panic(err)
     927             :                         }
     928             :                 }
     929             :         }
     930             : 
     931           1 :         d.mu.Lock()
     932           1 : 
     933           1 :         var err error
     934           1 :         if !b.ingestedSSTBatch {
     935           1 :                 // Batches which contain keys of kind InternalKeyKindIngestSST will
     936           1 :                 // never be applied to the memtable, so we don't need to make room for
     937           1 :                 // write. For the other cases, switch out the memtable if there was not
     938           1 :                 // enough room to store the batch.
     939           1 :                 err = d.makeRoomForWrite(b)
     940           1 :         }
     941             : 
     942           1 :         if err == nil && !d.opts.DisableWAL {
     943           1 :                 d.mu.log.bytesIn += uint64(len(repr))
     944           1 :         }
     945             : 
     946             :         // Grab a reference to the memtable while holding DB.mu. Note that for
     947             :         // non-flushable batches (b.flushable == nil) makeRoomForWrite() added a
     948             :         // reference to the memtable which will prevent it from being flushed until
     949             :         // we unreference it. This reference is dropped in DB.commitApply().
     950           1 :         mem := d.mu.mem.mutable
     951           1 : 
     952           1 :         d.mu.Unlock()
     953           1 :         if err != nil {
     954           0 :                 return nil, err
     955           0 :         }
     956             : 
     957           1 :         if d.opts.DisableWAL {
     958           1 :                 return mem, nil
     959           1 :         }
     960             : 
     961           1 :         if b.flushable == nil {
     962           1 :                 size, err = d.mu.log.writer.WriteRecord(repr, wal.SyncOptions{Done: syncWG, Err: syncErr})
     963           1 :                 if err != nil {
     964           0 :                         panic(err)
     965             :                 }
     966             :         }
     967             : 
     968           1 :         d.logSize.Store(uint64(size))
     969           1 :         return mem, err
     970             : }
     971             : 
     972             : type iterAlloc struct {
     973             :         dbi                 Iterator
     974             :         keyBuf              []byte
     975             :         boundsBuf           [2][]byte
     976             :         prefixOrFullSeekKey []byte
     977             :         merging             mergingIter
     978             :         mlevels             [3 + numLevels]mergingIterLevel
     979             :         levels              [3 + numLevels]levelIter
     980             :         levelsPositioned    [3 + numLevels]bool
     981             : }
     982             : 
     983             : var iterAllocPool = sync.Pool{
     984           1 :         New: func() interface{} {
     985           1 :                 return &iterAlloc{}
     986           1 :         },
     987             : }
     988             : 
     989             : // snapshotIterOpts denotes snapshot-related iterator options when calling
     990             : // newIter. These are the possible cases for a snapshotIterOpts:
     991             : //   - No snapshot: All fields are zero values.
     992             : //   - Classic snapshot: Only `seqNum` is set. The latest readState will be used
     993             : //     and the specified seqNum will be used as the snapshot seqNum.
     994             : //   - EventuallyFileOnlySnapshot (EFOS) behaving as a classic snapshot. Only
     995             : //     the `seqNum` is set. The latest readState will be used
     996             : //     and the specified seqNum will be used as the snapshot seqNum.
     997             : //   - EFOS in file-only state: Only `seqNum` and `vers` are set. All the
     998             : //     relevant SSTs are referenced by the *version.
     999             : //   - EFOS that has been excised but is in alwaysCreateIters mode (tests only).
    1000             : //     Only `seqNum` and `readState` are set.
    1001             : type snapshotIterOpts struct {
    1002             :         seqNum    uint64
    1003             :         vers      *version
    1004             :         readState *readState
    1005             : }
    1006             : 
    1007             : type batchIterOpts struct {
    1008             :         batchOnly bool
    1009             : }
    1010             : type newIterOpts struct {
    1011             :         snapshot snapshotIterOpts
    1012             :         batch    batchIterOpts
    1013             : }
    1014             : 
    1015             : // newIter constructs a new iterator, merging in batch iterators as an extra
    1016             : // level.
    1017             : func (d *DB) newIter(
    1018             :         ctx context.Context, batch *Batch, internalOpts newIterOpts, o *IterOptions,
    1019           1 : ) *Iterator {
    1020           1 :         if internalOpts.batch.batchOnly {
    1021           1 :                 if batch == nil {
    1022           0 :                         panic("batchOnly is true, but batch is nil")
    1023             :                 }
    1024           1 :                 if internalOpts.snapshot.vers != nil {
    1025           0 :                         panic("batchOnly is true, but snapshotIterOpts is initialized")
    1026             :                 }
    1027             :         }
    1028           1 :         if err := d.closed.Load(); err != nil {
    1029           1 :                 panic(err)
    1030             :         }
    1031           1 :         seqNum := internalOpts.snapshot.seqNum
    1032           1 :         if o != nil && o.RangeKeyMasking.Suffix != nil && o.KeyTypes != IterKeyTypePointsAndRanges {
    1033           0 :                 panic("pebble: range key masking requires IterKeyTypePointsAndRanges")
    1034             :         }
    1035           1 :         if (batch != nil || seqNum != 0) && (o != nil && o.OnlyReadGuaranteedDurable) {
    1036           1 :                 // We could add support for OnlyReadGuaranteedDurable on snapshots if
    1037           1 :                 // there was a need: this would require checking that the sequence number
    1038           1 :                 // of the snapshot has been flushed, by comparing with
    1039           1 :                 // DB.mem.queue[0].logSeqNum.
    1040           1 :                 panic("OnlyReadGuaranteedDurable is not supported for batches or snapshots")
    1041             :         }
    1042           1 :         var readState *readState
    1043           1 :         var newIters tableNewIters
    1044           1 :         var newIterRangeKey keyspanimpl.TableNewSpanIter
    1045           1 :         if !internalOpts.batch.batchOnly {
    1046           1 :                 // Grab and reference the current readState. This prevents the underlying
    1047           1 :                 // files in the associated version from being deleted if there is a current
    1048           1 :                 // compaction. The readState is unref'd by Iterator.Close().
    1049           1 :                 if internalOpts.snapshot.vers == nil {
    1050           1 :                         if internalOpts.snapshot.readState != nil {
    1051           0 :                                 readState = internalOpts.snapshot.readState
    1052           0 :                                 readState.ref()
    1053           1 :                         } else {
    1054           1 :                                 // NB: loadReadState() calls readState.ref().
    1055           1 :                                 readState = d.loadReadState()
    1056           1 :                         }
    1057           1 :                 } else {
    1058           1 :                         // vers != nil
    1059           1 :                         internalOpts.snapshot.vers.Ref()
    1060           1 :                 }
    1061             : 
    1062             :                 // Determine the seqnum to read at after grabbing the read state (current and
    1063             :                 // memtables) above.
    1064           1 :                 if seqNum == 0 {
    1065           1 :                         seqNum = d.mu.versions.visibleSeqNum.Load()
    1066           1 :                 }
    1067           1 :                 newIters = d.newIters
    1068           1 :                 newIterRangeKey = d.tableNewRangeKeyIter
    1069             :         }
    1070             : 
    1071             :         // Bundle various structures under a single umbrella in order to allocate
    1072             :         // them together.
    1073           1 :         buf := iterAllocPool.Get().(*iterAlloc)
    1074           1 :         dbi := &buf.dbi
    1075           1 :         *dbi = Iterator{
    1076           1 :                 ctx:                 ctx,
    1077           1 :                 alloc:               buf,
    1078           1 :                 merge:               d.merge,
    1079           1 :                 comparer:            *d.opts.Comparer,
    1080           1 :                 readState:           readState,
    1081           1 :                 version:             internalOpts.snapshot.vers,
    1082           1 :                 keyBuf:              buf.keyBuf,
    1083           1 :                 prefixOrFullSeekKey: buf.prefixOrFullSeekKey,
    1084           1 :                 boundsBuf:           buf.boundsBuf,
    1085           1 :                 batch:               batch,
    1086           1 :                 newIters:            newIters,
    1087           1 :                 newIterRangeKey:     newIterRangeKey,
    1088           1 :                 seqNum:              seqNum,
    1089           1 :                 batchOnlyIter:       internalOpts.batch.batchOnly,
    1090           1 :         }
    1091           1 :         if o != nil {
    1092           1 :                 dbi.opts = *o
    1093           1 :                 dbi.processBounds(o.LowerBound, o.UpperBound)
    1094           1 :         }
    1095           1 :         dbi.opts.logger = d.opts.Logger
    1096           1 :         if d.opts.private.disableLazyCombinedIteration {
    1097           0 :                 dbi.opts.disableLazyCombinedIteration = true
    1098           0 :         }
    1099           1 :         if batch != nil {
    1100           1 :                 dbi.batchSeqNum = dbi.batch.nextSeqNum()
    1101           1 :         }
    1102           1 :         return finishInitializingIter(ctx, buf)
    1103             : }
    1104             : 
    1105             : // finishInitializingIter is a helper for doing the non-trivial initialization
    1106             : // of an Iterator. It's invoked to perform the initial initialization of an
    1107             : // Iterator during NewIter or Clone, and to perform reinitialization due to a
    1108             : // change in IterOptions by a call to Iterator.SetOptions.
    1109           1 : func finishInitializingIter(ctx context.Context, buf *iterAlloc) *Iterator {
    1110           1 :         // Short-hand.
    1111           1 :         dbi := &buf.dbi
    1112           1 :         var memtables flushableList
    1113           1 :         if dbi.readState != nil {
    1114           1 :                 memtables = dbi.readState.memtables
    1115           1 :         }
    1116           1 :         if dbi.opts.OnlyReadGuaranteedDurable {
    1117           1 :                 memtables = nil
    1118           1 :         } else {
    1119           1 :                 // We only need to read from memtables which contain sequence numbers older
    1120           1 :                 // than seqNum. Trim off newer memtables.
    1121           1 :                 for i := len(memtables) - 1; i >= 0; i-- {
    1122           1 :                         if logSeqNum := memtables[i].logSeqNum; logSeqNum < dbi.seqNum {
    1123           1 :                                 break
    1124             :                         }
    1125           1 :                         memtables = memtables[:i]
    1126             :                 }
    1127             :         }
    1128             : 
    1129           1 :         if dbi.opts.pointKeys() {
    1130           1 :                 // Construct the point iterator, initializing dbi.pointIter to point to
    1131           1 :                 // dbi.merging. If this is called during a SetOptions call and this
    1132           1 :                 // Iterator has already initialized dbi.merging, constructPointIter is a
    1133           1 :                 // noop and an initialized pointIter already exists in dbi.pointIter.
    1134           1 :                 dbi.constructPointIter(ctx, memtables, buf)
    1135           1 :                 dbi.iter = dbi.pointIter
    1136           1 :         } else {
    1137           1 :                 dbi.iter = emptyIter
    1138           1 :         }
    1139             : 
    1140           1 :         if dbi.opts.rangeKeys() {
    1141           1 :                 dbi.rangeKeyMasking.init(dbi, dbi.comparer.Compare, dbi.comparer.Split)
    1142           1 : 
    1143           1 :                 // When iterating over both point and range keys, don't create the
    1144           1 :                 // range-key iterator stack immediately if we can avoid it. This
    1145           1 :                 // optimization takes advantage of the expected sparseness of range
    1146           1 :                 // keys, and configures the point-key iterator to dynamically switch to
    1147           1 :                 // combined iteration when it observes a file containing range keys.
    1148           1 :                 //
    1149           1 :                 // Lazy combined iteration is not possible if a batch or a memtable
    1150           1 :                 // contains any range keys.
    1151           1 :                 useLazyCombinedIteration := dbi.rangeKey == nil &&
    1152           1 :                         dbi.opts.KeyTypes == IterKeyTypePointsAndRanges &&
    1153           1 :                         (dbi.batch == nil || dbi.batch.countRangeKeys == 0) &&
    1154           1 :                         !dbi.opts.disableLazyCombinedIteration
    1155           1 :                 if useLazyCombinedIteration {
    1156           1 :                         // The user requested combined iteration, and there's no indexed
    1157           1 :                         // batch currently containing range keys that would prevent lazy
    1158           1 :                         // combined iteration. Check the memtables to see if they contain
    1159           1 :                         // any range keys.
    1160           1 :                         for i := range memtables {
    1161           1 :                                 if memtables[i].containsRangeKeys() {
    1162           1 :                                         useLazyCombinedIteration = false
    1163           1 :                                         break
    1164             :                                 }
    1165             :                         }
    1166             :                 }
    1167             : 
    1168           1 :                 if useLazyCombinedIteration {
    1169           1 :                         dbi.lazyCombinedIter = lazyCombinedIter{
    1170           1 :                                 parent:    dbi,
    1171           1 :                                 pointIter: dbi.pointIter,
    1172           1 :                                 combinedIterState: combinedIterState{
    1173           1 :                                         initialized: false,
    1174           1 :                                 },
    1175           1 :                         }
    1176           1 :                         dbi.iter = &dbi.lazyCombinedIter
    1177           1 :                         dbi.iter = invalidating.MaybeWrapIfInvariants(dbi.iter)
    1178           1 :                 } else {
    1179           1 :                         dbi.lazyCombinedIter.combinedIterState = combinedIterState{
    1180           1 :                                 initialized: true,
    1181           1 :                         }
    1182           1 :                         if dbi.rangeKey == nil {
    1183           1 :                                 dbi.rangeKey = iterRangeKeyStateAllocPool.Get().(*iteratorRangeKeyState)
    1184           1 :                                 dbi.rangeKey.init(dbi.comparer.Compare, dbi.comparer.Split, &dbi.opts)
    1185           1 :                                 dbi.constructRangeKeyIter()
    1186           1 :                         } else {
    1187           1 :                                 dbi.rangeKey.iterConfig.SetBounds(dbi.opts.LowerBound, dbi.opts.UpperBound)
    1188           1 :                         }
    1189             : 
    1190             :                         // Wrap the point iterator (currently dbi.iter) with an interleaving
    1191             :                         // iterator that interleaves range keys pulled from
    1192             :                         // dbi.rangeKey.rangeKeyIter.
    1193             :                         //
    1194             :                         // NB: The interleaving iterator is always reinitialized, even if
    1195             :                         // dbi already had an initialized range key iterator, in case the point
    1196             :                         // iterator changed or the range key masking suffix changed.
    1197           1 :                         dbi.rangeKey.iiter.Init(&dbi.comparer, dbi.iter, dbi.rangeKey.rangeKeyIter,
    1198           1 :                                 keyspan.InterleavingIterOpts{
    1199           1 :                                         Mask:       &dbi.rangeKeyMasking,
    1200           1 :                                         LowerBound: dbi.opts.LowerBound,
    1201           1 :                                         UpperBound: dbi.opts.UpperBound,
    1202           1 :                                 })
    1203           1 :                         dbi.iter = &dbi.rangeKey.iiter
    1204             :                 }
    1205           1 :         } else {
    1206           1 :                 // !dbi.opts.rangeKeys()
    1207           1 :                 //
    1208           1 :                 // Reset the combined iterator state. The initialized=true ensures the
    1209           1 :                 // iterator doesn't unnecessarily try to switch to combined iteration.
    1210           1 :                 dbi.lazyCombinedIter.combinedIterState = combinedIterState{initialized: true}
    1211           1 :         }
    1212           1 :         return dbi
    1213             : }
    1214             : 
    1215             : // ScanInternal scans all internal keys within the specified bounds, truncating
    1216             : // any rangedels and rangekeys to those bounds if they span past them. For use
    1217             : // when an external user needs to be aware of all internal keys that make up a
    1218             : // key range.
    1219             : //
    1220             : // Keys deleted by range deletions must not be returned or exposed by this
    1221             : // method, while the range deletion deleting that key must be exposed using
    1222             : // visitRangeDel. Keys that would be masked by range key masking (if an
    1223             : // appropriate prefix were set) should be exposed, alongside the range key
    1224             : // that would have masked it. This method also collapses all point keys into
    1225             : // one InternalKey; so only one internal key at most per user key is returned
    1226             : // to visitPointKey.
    1227             : //
    1228             : // If visitSharedFile is not nil, ScanInternal iterates in skip-shared iteration
    1229             : // mode. In this iteration mode, sstables in levels L5 and L6 are skipped, and
    1230             : // their metadatas truncated to [lower, upper) and passed into visitSharedFile.
    1231             : // ErrInvalidSkipSharedIteration is returned if visitSharedFile is not nil and an
    1232             : // sstable in L5 or L6 is found that is not in shared storage according to
    1233             : // provider.IsShared, or an sstable in those levels contains a newer key than the
    1234             : // snapshot sequence number (only applicable for snapshot.ScanInternal). Examples
    1235             : // of when this could happen could be if Pebble started writing sstables before a
    1236             : // creator ID was set (as creator IDs are necessary to enable shared storage)
    1237             : // resulting in some lower level SSTs being on non-shared storage. Skip-shared
    1238             : // iteration is invalid in those cases.
    1239             : func (d *DB) ScanInternal(
    1240             :         ctx context.Context,
    1241             :         categoryAndQoS sstable.CategoryAndQoS,
    1242             :         lower, upper []byte,
    1243             :         visitPointKey func(key *InternalKey, value LazyValue, iterInfo IteratorLevel) error,
    1244             :         visitRangeDel func(start, end []byte, seqNum uint64) error,
    1245             :         visitRangeKey func(start, end []byte, keys []rangekey.Key) error,
    1246             :         visitSharedFile func(sst *SharedSSTMeta) error,
    1247           1 : ) error {
    1248           1 :         scanInternalOpts := &scanInternalOptions{
    1249           1 :                 CategoryAndQoS:   categoryAndQoS,
    1250           1 :                 visitPointKey:    visitPointKey,
    1251           1 :                 visitRangeDel:    visitRangeDel,
    1252           1 :                 visitRangeKey:    visitRangeKey,
    1253           1 :                 visitSharedFile:  visitSharedFile,
    1254           1 :                 skipSharedLevels: visitSharedFile != nil,
    1255           1 :                 IterOptions: IterOptions{
    1256           1 :                         KeyTypes:   IterKeyTypePointsAndRanges,
    1257           1 :                         LowerBound: lower,
    1258           1 :                         UpperBound: upper,
    1259           1 :                 },
    1260           1 :         }
    1261           1 :         iter, err := d.newInternalIter(ctx, snapshotIterOpts{} /* snapshot */, scanInternalOpts)
    1262           1 :         if err != nil {
    1263           0 :                 return err
    1264           0 :         }
    1265           1 :         defer iter.close()
    1266           1 :         return scanInternalImpl(ctx, lower, upper, iter, scanInternalOpts)
    1267             : }
    1268             : 
    1269             : // newInternalIter constructs and returns a new scanInternalIterator on this db.
    1270             : // If o.skipSharedLevels is true, levels below sharedLevelsStart are *not* added
    1271             : // to the internal iterator.
    1272             : //
    1273             : // TODO(bilal): This method has a lot of similarities with db.newIter as well as
    1274             : // finishInitializingIter. Both pairs of methods should be refactored to reduce
    1275             : // this duplication.
    1276             : func (d *DB) newInternalIter(
    1277             :         ctx context.Context, sOpts snapshotIterOpts, o *scanInternalOptions,
    1278           1 : ) (*scanInternalIterator, error) {
    1279           1 :         if err := d.closed.Load(); err != nil {
    1280           0 :                 panic(err)
    1281             :         }
    1282             :         // Grab and reference the current readState. This prevents the underlying
    1283             :         // files in the associated version from being deleted if there is a current
    1284             :         // compaction. The readState is unref'd by Iterator.Close().
    1285           1 :         var readState *readState
    1286           1 :         if sOpts.vers == nil {
    1287           1 :                 if sOpts.readState != nil {
    1288           0 :                         readState = sOpts.readState
    1289           0 :                         readState.ref()
    1290           1 :                 } else {
    1291           1 :                         readState = d.loadReadState()
    1292           1 :                 }
    1293             :         }
    1294           1 :         if sOpts.vers != nil {
    1295           1 :                 sOpts.vers.Ref()
    1296           1 :         }
    1297             : 
    1298             :         // Determine the seqnum to read at after grabbing the read state (current and
    1299             :         // memtables) above.
    1300           1 :         seqNum := sOpts.seqNum
    1301           1 :         if seqNum == 0 {
    1302           1 :                 seqNum = d.mu.versions.visibleSeqNum.Load()
    1303           1 :         }
    1304             : 
    1305             :         // Bundle various structures under a single umbrella in order to allocate
    1306             :         // them together.
    1307           1 :         buf := iterAllocPool.Get().(*iterAlloc)
    1308           1 :         dbi := &scanInternalIterator{
    1309           1 :                 ctx:             ctx,
    1310           1 :                 db:              d,
    1311           1 :                 comparer:        d.opts.Comparer,
    1312           1 :                 merge:           d.opts.Merger.Merge,
    1313           1 :                 readState:       readState,
    1314           1 :                 version:         sOpts.vers,
    1315           1 :                 alloc:           buf,
    1316           1 :                 newIters:        d.newIters,
    1317           1 :                 newIterRangeKey: d.tableNewRangeKeyIter,
    1318           1 :                 seqNum:          seqNum,
    1319           1 :                 mergingIter:     &buf.merging,
    1320           1 :         }
    1321           1 :         dbi.opts = *o
    1322           1 :         dbi.opts.logger = d.opts.Logger
    1323           1 :         if d.opts.private.disableLazyCombinedIteration {
    1324           0 :                 dbi.opts.disableLazyCombinedIteration = true
    1325           0 :         }
    1326           1 :         return finishInitializingInternalIter(buf, dbi)
    1327             : }
    1328             : 
    1329             : func finishInitializingInternalIter(
    1330             :         buf *iterAlloc, i *scanInternalIterator,
    1331           1 : ) (*scanInternalIterator, error) {
    1332           1 :         // Short-hand.
    1333           1 :         var memtables flushableList
    1334           1 :         if i.readState != nil {
    1335           1 :                 memtables = i.readState.memtables
    1336           1 :         }
    1337             :         // We only need to read from memtables which contain sequence numbers older
    1338             :         // than seqNum. Trim off newer memtables.
    1339           1 :         for j := len(memtables) - 1; j >= 0; j-- {
    1340           1 :                 if logSeqNum := memtables[j].logSeqNum; logSeqNum < i.seqNum {
    1341           1 :                         break
    1342             :                 }
    1343           1 :                 memtables = memtables[:j]
    1344             :         }
    1345           1 :         i.initializeBoundBufs(i.opts.LowerBound, i.opts.UpperBound)
    1346           1 : 
    1347           1 :         i.constructPointIter(i.opts.CategoryAndQoS, memtables, buf)
    1348           1 : 
    1349           1 :         // For internal iterators, we skip the lazy combined iteration optimization
    1350           1 :         // entirely, and create the range key iterator stack directly.
    1351           1 :         i.rangeKey = iterRangeKeyStateAllocPool.Get().(*iteratorRangeKeyState)
    1352           1 :         i.rangeKey.init(i.comparer.Compare, i.comparer.Split, &i.opts.IterOptions)
    1353           1 :         if err := i.constructRangeKeyIter(); err != nil {
    1354           0 :                 return nil, err
    1355           0 :         }
    1356             : 
    1357             :         // Wrap the point iterator (currently i.iter) with an interleaving
    1358             :         // iterator that interleaves range keys pulled from
    1359             :         // i.rangeKey.rangeKeyIter.
    1360           1 :         i.rangeKey.iiter.Init(i.comparer, i.iter, i.rangeKey.rangeKeyIter,
    1361           1 :                 keyspan.InterleavingIterOpts{
    1362           1 :                         LowerBound: i.opts.LowerBound,
    1363           1 :                         UpperBound: i.opts.UpperBound,
    1364           1 :                 })
    1365           1 :         i.iter = &i.rangeKey.iiter
    1366           1 : 
    1367           1 :         return i, nil
    1368             : }
    1369             : 
    1370             : func (i *Iterator) constructPointIter(
    1371             :         ctx context.Context, memtables flushableList, buf *iterAlloc,
    1372           1 : ) {
    1373           1 :         if i.pointIter != nil {
    1374           1 :                 // Already have one.
    1375           1 :                 return
    1376           1 :         }
    1377           1 :         internalOpts := internalIterOpts{stats: &i.stats.InternalStats}
    1378           1 :         if i.opts.RangeKeyMasking.Filter != nil {
    1379           1 :                 internalOpts.boundLimitedFilter = &i.rangeKeyMasking
    1380           1 :         }
    1381             : 
    1382             :         // Merging levels and levels from iterAlloc.
    1383           1 :         mlevels := buf.mlevels[:0]
    1384           1 :         levels := buf.levels[:0]
    1385           1 : 
    1386           1 :         // We compute the number of levels needed ahead of time and reallocate a slice if
    1387           1 :         // the array from the iterAlloc isn't large enough. Doing this allocation once
    1388           1 :         // should improve the performance.
    1389           1 :         numMergingLevels := 0
    1390           1 :         numLevelIters := 0
    1391           1 :         if i.batch != nil {
    1392           1 :                 numMergingLevels++
    1393           1 :         }
    1394             : 
    1395           1 :         var current *version
    1396           1 :         if !i.batchOnlyIter {
    1397           1 :                 numMergingLevels += len(memtables)
    1398           1 : 
    1399           1 :                 current = i.version
    1400           1 :                 if current == nil {
    1401           1 :                         current = i.readState.current
    1402           1 :                 }
    1403           1 :                 numMergingLevels += len(current.L0SublevelFiles)
    1404           1 :                 numLevelIters += len(current.L0SublevelFiles)
    1405           1 :                 for level := 1; level < len(current.Levels); level++ {
    1406           1 :                         if current.Levels[level].Empty() {
    1407           1 :                                 continue
    1408             :                         }
    1409           1 :                         numMergingLevels++
    1410           1 :                         numLevelIters++
    1411             :                 }
    1412             :         }
    1413             : 
    1414           1 :         if numMergingLevels > cap(mlevels) {
    1415           1 :                 mlevels = make([]mergingIterLevel, 0, numMergingLevels)
    1416           1 :         }
    1417           1 :         if numLevelIters > cap(levels) {
    1418           1 :                 levels = make([]levelIter, 0, numLevelIters)
    1419           1 :         }
    1420             : 
    1421             :         // Top-level is the batch, if any.
    1422           1 :         if i.batch != nil {
    1423           1 :                 if i.batch.index == nil {
    1424           0 :                         // This isn't an indexed batch. We shouldn't have gotten this far.
    1425           0 :                         panic(errors.AssertionFailedf("creating an iterator over an unindexed batch"))
    1426           1 :                 } else {
    1427           1 :                         i.batch.initInternalIter(&i.opts, &i.batchPointIter)
    1428           1 :                         i.batch.initRangeDelIter(&i.opts, &i.batchRangeDelIter, i.batchSeqNum)
    1429           1 :                         // Only include the batch's rangedel iterator if it's non-empty.
    1430           1 :                         // This requires some subtle logic in the case a rangedel is later
    1431           1 :                         // written to the batch and the view of the batch is refreshed
    1432           1 :                         // during a call to SetOptions—in this case, we need to reconstruct
    1433           1 :                         // the point iterator to add the batch rangedel iterator.
    1434           1 :                         var rangeDelIter keyspan.FragmentIterator
    1435           1 :                         if i.batchRangeDelIter.Count() > 0 {
    1436           1 :                                 rangeDelIter = &i.batchRangeDelIter
    1437           1 :                         }
    1438           1 :                         mlevels = append(mlevels, mergingIterLevel{
    1439           1 :                                 iter:         &i.batchPointIter,
    1440           1 :                                 rangeDelIter: rangeDelIter,
    1441           1 :                         })
    1442             :                 }
    1443             :         }
    1444             : 
    1445           1 :         if !i.batchOnlyIter {
    1446           1 :                 // Next are the memtables.
    1447           1 :                 for j := len(memtables) - 1; j >= 0; j-- {
    1448           1 :                         mem := memtables[j]
    1449           1 :                         mlevels = append(mlevels, mergingIterLevel{
    1450           1 :                                 iter:         mem.newIter(&i.opts),
    1451           1 :                                 rangeDelIter: mem.newRangeDelIter(&i.opts),
    1452           1 :                         })
    1453           1 :                 }
    1454             : 
    1455             :                 // Next are the file levels: L0 sub-levels followed by lower levels.
    1456           1 :                 mlevelsIndex := len(mlevels)
    1457           1 :                 levelsIndex := len(levels)
    1458           1 :                 mlevels = mlevels[:numMergingLevels]
    1459           1 :                 levels = levels[:numLevelIters]
    1460           1 :                 i.opts.snapshotForHideObsoletePoints = buf.dbi.seqNum
    1461           1 :                 addLevelIterForFiles := func(files manifest.LevelIterator, level manifest.Level) {
    1462           1 :                         li := &levels[levelsIndex]
    1463           1 : 
    1464           1 :                         li.init(ctx, i.opts, &i.comparer, i.newIters, files, level, internalOpts)
    1465           1 :                         li.initRangeDel(&mlevels[mlevelsIndex].rangeDelIter)
    1466           1 :                         li.initBoundaryContext(&mlevels[mlevelsIndex].levelIterBoundaryContext)
    1467           1 :                         li.initCombinedIterState(&i.lazyCombinedIter.combinedIterState)
    1468           1 :                         mlevels[mlevelsIndex].levelIter = li
    1469           1 :                         mlevels[mlevelsIndex].iter = invalidating.MaybeWrapIfInvariants(li)
    1470           1 : 
    1471           1 :                         levelsIndex++
    1472           1 :                         mlevelsIndex++
    1473           1 :                 }
    1474             : 
    1475             :                 // Add level iterators for the L0 sublevels, iterating from newest to
    1476             :                 // oldest.
    1477           1 :                 for i := len(current.L0SublevelFiles) - 1; i >= 0; i-- {
    1478           1 :                         addLevelIterForFiles(current.L0SublevelFiles[i].Iter(), manifest.L0Sublevel(i))
    1479           1 :                 }
    1480             : 
    1481             :                 // Add level iterators for the non-empty non-L0 levels.
    1482           1 :                 for level := 1; level < len(current.Levels); level++ {
    1483           1 :                         if current.Levels[level].Empty() {
    1484           1 :                                 continue
    1485             :                         }
    1486           1 :                         addLevelIterForFiles(current.Levels[level].Iter(), manifest.Level(level))
    1487             :                 }
    1488             :         }
    1489           1 :         buf.merging.init(&i.opts, &i.stats.InternalStats, i.comparer.Compare, i.comparer.Split, mlevels...)
    1490           1 :         if len(mlevels) <= cap(buf.levelsPositioned) {
    1491           1 :                 buf.merging.levelsPositioned = buf.levelsPositioned[:len(mlevels)]
    1492           1 :         }
    1493           1 :         buf.merging.snapshot = i.seqNum
    1494           1 :         buf.merging.batchSnapshot = i.batchSeqNum
    1495           1 :         buf.merging.combinedIterState = &i.lazyCombinedIter.combinedIterState
    1496           1 :         i.pointIter = invalidating.MaybeWrapIfInvariants(&buf.merging)
    1497           1 :         i.merging = &buf.merging
    1498             : }
    1499             : 
    1500             : // NewBatch returns a new empty write-only batch. Any reads on the batch will
    1501             : // return an error. If the batch is committed it will be applied to the DB.
    1502           1 : func (d *DB) NewBatch() *Batch {
    1503           1 :         return newBatch(d)
    1504           1 : }
    1505             : 
    1506             : // NewBatchWithSize is mostly identical to NewBatch, but it will allocate the
    1507             : // the specified memory space for the internal slice in advance.
    1508           0 : func (d *DB) NewBatchWithSize(size int) *Batch {
    1509           0 :         return newBatchWithSize(d, size)
    1510           0 : }
    1511             : 
    1512             : // NewIndexedBatch returns a new empty read-write batch. Any reads on the batch
    1513             : // will read from both the batch and the DB. If the batch is committed it will
    1514             : // be applied to the DB. An indexed batch is slower that a non-indexed batch
    1515             : // for insert operations. If you do not need to perform reads on the batch, use
    1516             : // NewBatch instead.
    1517           1 : func (d *DB) NewIndexedBatch() *Batch {
    1518           1 :         return newIndexedBatch(d, d.opts.Comparer)
    1519           1 : }
    1520             : 
    1521             : // NewIndexedBatchWithSize is mostly identical to NewIndexedBatch, but it will
    1522             : // allocate the the specified memory space for the internal slice in advance.
    1523           0 : func (d *DB) NewIndexedBatchWithSize(size int) *Batch {
    1524           0 :         return newIndexedBatchWithSize(d, d.opts.Comparer, size)
    1525           0 : }
    1526             : 
    1527             : // NewIter returns an iterator that is unpositioned (Iterator.Valid() will
    1528             : // return false). The iterator can be positioned via a call to SeekGE, SeekLT,
    1529             : // First or Last. The iterator provides a point-in-time view of the current DB
    1530             : // state. This view is maintained by preventing file deletions and preventing
    1531             : // memtables referenced by the iterator from being deleted. Using an iterator
    1532             : // to maintain a long-lived point-in-time view of the DB state can lead to an
    1533             : // apparent memory and disk usage leak. Use snapshots (see NewSnapshot) for
    1534             : // point-in-time snapshots which avoids these problems.
    1535           1 : func (d *DB) NewIter(o *IterOptions) (*Iterator, error) {
    1536           1 :         return d.NewIterWithContext(context.Background(), o)
    1537           1 : }
    1538             : 
    1539             : // NewIterWithContext is like NewIter, and additionally accepts a context for
    1540             : // tracing.
    1541           1 : func (d *DB) NewIterWithContext(ctx context.Context, o *IterOptions) (*Iterator, error) {
    1542           1 :         return d.newIter(ctx, nil /* batch */, newIterOpts{}, o), nil
    1543           1 : }
    1544             : 
    1545             : // NewSnapshot returns a point-in-time view of the current DB state. Iterators
    1546             : // created with this handle will all observe a stable snapshot of the current
    1547             : // DB state. The caller must call Snapshot.Close() when the snapshot is no
    1548             : // longer needed. Snapshots are not persisted across DB restarts (close ->
    1549             : // open). Unlike the implicit snapshot maintained by an iterator, a snapshot
    1550             : // will not prevent memtables from being released or sstables from being
    1551             : // deleted. Instead, a snapshot prevents deletion of sequence numbers
    1552             : // referenced by the snapshot.
    1553           1 : func (d *DB) NewSnapshot() *Snapshot {
    1554           1 :         if err := d.closed.Load(); err != nil {
    1555           1 :                 panic(err)
    1556             :         }
    1557             : 
    1558           1 :         d.mu.Lock()
    1559           1 :         s := &Snapshot{
    1560           1 :                 db:     d,
    1561           1 :                 seqNum: d.mu.versions.visibleSeqNum.Load(),
    1562           1 :         }
    1563           1 :         d.mu.snapshots.pushBack(s)
    1564           1 :         d.mu.Unlock()
    1565           1 :         return s
    1566             : }
    1567             : 
    1568             : // NewEventuallyFileOnlySnapshot returns a point-in-time view of the current DB
    1569             : // state, similar to NewSnapshot, but with consistency constrained to the
    1570             : // provided set of key ranges. See the comment at EventuallyFileOnlySnapshot for
    1571             : // its semantics.
    1572           1 : func (d *DB) NewEventuallyFileOnlySnapshot(keyRanges []KeyRange) *EventuallyFileOnlySnapshot {
    1573           1 :         if err := d.closed.Load(); err != nil {
    1574           0 :                 panic(err)
    1575             :         }
    1576           1 :         for i := range keyRanges {
    1577           1 :                 if i > 0 && d.cmp(keyRanges[i-1].End, keyRanges[i].Start) > 0 {
    1578           0 :                         panic("pebble: key ranges for eventually-file-only-snapshot not in order")
    1579             :                 }
    1580             :         }
    1581           1 :         return d.makeEventuallyFileOnlySnapshot(keyRanges)
    1582             : }
    1583             : 
    1584             : // Close closes the DB.
    1585             : //
    1586             : // It is not safe to close a DB until all outstanding iterators are closed
    1587             : // or to call Close concurrently with any other DB method. It is not valid
    1588             : // to call any of a DB's methods after the DB has been closed.
    1589           1 : func (d *DB) Close() error {
    1590           1 :         // Lock the commit pipeline for the duration of Close. This prevents a race
    1591           1 :         // with makeRoomForWrite. Rotating the WAL in makeRoomForWrite requires
    1592           1 :         // dropping d.mu several times for I/O. If Close only holds d.mu, an
    1593           1 :         // in-progress WAL rotation may re-acquire d.mu only once the database is
    1594           1 :         // closed.
    1595           1 :         //
    1596           1 :         // Additionally, locking the commit pipeline makes it more likely that
    1597           1 :         // (illegal) concurrent writes will observe d.closed.Load() != nil, creating
    1598           1 :         // more understable panics if the database is improperly used concurrently
    1599           1 :         // during Close.
    1600           1 :         d.commit.mu.Lock()
    1601           1 :         defer d.commit.mu.Unlock()
    1602           1 :         d.mu.Lock()
    1603           1 :         defer d.mu.Unlock()
    1604           1 :         if err := d.closed.Load(); err != nil {
    1605           1 :                 panic(err)
    1606             :         }
    1607             : 
    1608             :         // Clear the finalizer that is used to check that an unreferenced DB has been
    1609             :         // closed. We're closing the DB here, so the check performed by that
    1610             :         // finalizer isn't necessary.
    1611             :         //
    1612             :         // Note: this is a no-op if invariants are disabled or race is enabled.
    1613           1 :         invariants.SetFinalizer(d.closed, nil)
    1614           1 : 
    1615           1 :         d.closed.Store(errors.WithStack(ErrClosed))
    1616           1 :         close(d.closedCh)
    1617           1 : 
    1618           1 :         defer d.opts.Cache.Unref()
    1619           1 : 
    1620           1 :         for d.mu.compact.compactingCount > 0 || d.mu.compact.flushing {
    1621           1 :                 d.mu.compact.cond.Wait()
    1622           1 :         }
    1623           1 :         for d.mu.tableStats.loading {
    1624           1 :                 d.mu.tableStats.cond.Wait()
    1625           1 :         }
    1626           1 :         for d.mu.tableValidation.validating {
    1627           0 :                 d.mu.tableValidation.cond.Wait()
    1628           0 :         }
    1629             : 
    1630           1 :         var err error
    1631           1 :         if n := len(d.mu.compact.inProgress); n > 0 {
    1632           1 :                 err = errors.Errorf("pebble: %d unexpected in-progress compactions", errors.Safe(n))
    1633           1 :         }
    1634           1 :         err = firstError(err, d.mu.formatVers.marker.Close())
    1635           1 :         err = firstError(err, d.tableCache.close())
    1636           1 :         if !d.opts.ReadOnly {
    1637           1 :                 if d.mu.log.writer != nil {
    1638           1 :                         _, err2 := d.mu.log.writer.Close()
    1639           1 :                         err = firstError(err, err2)
    1640           1 :                 }
    1641           1 :         } else if d.mu.log.writer != nil {
    1642           0 :                 panic("pebble: log-writer should be nil in read-only mode")
    1643             :         }
    1644           1 :         err = firstError(err, d.mu.log.manager.Close())
    1645           1 :         err = firstError(err, d.fileLock.Close())
    1646           1 : 
    1647           1 :         // Note that versionSet.close() only closes the MANIFEST. The versions list
    1648           1 :         // is still valid for the checks below.
    1649           1 :         err = firstError(err, d.mu.versions.close())
    1650           1 : 
    1651           1 :         err = firstError(err, d.dataDir.Close())
    1652           1 : 
    1653           1 :         d.readState.val.unrefLocked()
    1654           1 : 
    1655           1 :         current := d.mu.versions.currentVersion()
    1656           1 :         for v := d.mu.versions.versions.Front(); true; v = v.Next() {
    1657           1 :                 refs := v.Refs()
    1658           1 :                 if v == current {
    1659           1 :                         if refs != 1 {
    1660           1 :                                 err = firstError(err, errors.Errorf("leaked iterators: current\n%s", v))
    1661           1 :                         }
    1662           1 :                         break
    1663             :                 }
    1664           0 :                 if refs != 0 {
    1665           0 :                         err = firstError(err, errors.Errorf("leaked iterators:\n%s", v))
    1666           0 :                 }
    1667             :         }
    1668             : 
    1669           1 :         for _, mem := range d.mu.mem.queue {
    1670           1 :                 // Usually, we'd want to delete the files returned by readerUnref. But
    1671           1 :                 // in this case, even if we're unreferencing the flushables, the
    1672           1 :                 // flushables aren't obsolete. They will be reconstructed during WAL
    1673           1 :                 // replay.
    1674           1 :                 mem.readerUnrefLocked(false)
    1675           1 :         }
    1676             :         // If there's an unused, recycled memtable, we need to release its memory.
    1677           1 :         if obsoleteMemTable := d.memTableRecycle.Swap(nil); obsoleteMemTable != nil {
    1678           1 :                 d.freeMemTable(obsoleteMemTable)
    1679           1 :         }
    1680           1 :         if reserved := d.memTableReserved.Load(); reserved != 0 {
    1681           1 :                 err = firstError(err, errors.Errorf("leaked memtable reservation: %d", errors.Safe(reserved)))
    1682           1 :         }
    1683             : 
    1684             :         // Since we called d.readState.val.unrefLocked() above, we are expected to
    1685             :         // manually schedule deletion of obsolete files.
    1686           1 :         if len(d.mu.versions.obsoleteTables) > 0 {
    1687           1 :                 d.deleteObsoleteFiles(d.mu.nextJobID)
    1688           1 :         }
    1689             : 
    1690           1 :         d.mu.Unlock()
    1691           1 :         d.compactionSchedulers.Wait()
    1692           1 : 
    1693           1 :         // Wait for all cleaning jobs to finish.
    1694           1 :         d.cleanupManager.Close()
    1695           1 : 
    1696           1 :         // Sanity check metrics.
    1697           1 :         if invariants.Enabled {
    1698           1 :                 m := d.Metrics()
    1699           1 :                 if m.Compact.NumInProgress > 0 || m.Compact.InProgressBytes > 0 {
    1700           0 :                         d.mu.Lock()
    1701           0 :                         panic(fmt.Sprintf("invalid metrics on close:\n%s", m))
    1702             :                 }
    1703             :         }
    1704             : 
    1705           1 :         d.mu.Lock()
    1706           1 : 
    1707           1 :         // As a sanity check, ensure that there are no zombie tables. A non-zero count
    1708           1 :         // hints at a reference count leak.
    1709           1 :         if ztbls := len(d.mu.versions.zombieTables); ztbls > 0 {
    1710           0 :                 err = firstError(err, errors.Errorf("non-zero zombie file count: %d", ztbls))
    1711           0 :         }
    1712             : 
    1713           1 :         err = firstError(err, d.objProvider.Close())
    1714           1 : 
    1715           1 :         // If the options include a closer to 'close' the filesystem, close it.
    1716           1 :         if d.opts.private.fsCloser != nil {
    1717           1 :                 d.opts.private.fsCloser.Close()
    1718           1 :         }
    1719             : 
    1720             :         // Return an error if the user failed to close all open snapshots.
    1721           1 :         if v := d.mu.snapshots.count(); v > 0 {
    1722           0 :                 err = firstError(err, errors.Errorf("leaked snapshots: %d open snapshots on DB %p", v, d))
    1723           0 :         }
    1724             : 
    1725           1 :         return err
    1726             : }
    1727             : 
    1728             : // Compact the specified range of keys in the database.
    1729           1 : func (d *DB) Compact(start, end []byte, parallelize bool) error {
    1730           1 :         if err := d.closed.Load(); err != nil {
    1731           1 :                 panic(err)
    1732             :         }
    1733           1 :         if d.opts.ReadOnly {
    1734           1 :                 return ErrReadOnly
    1735           1 :         }
    1736           1 :         if d.cmp(start, end) >= 0 {
    1737           1 :                 return errors.Errorf("Compact start %s is not less than end %s",
    1738           1 :                         d.opts.Comparer.FormatKey(start), d.opts.Comparer.FormatKey(end))
    1739           1 :         }
    1740             : 
    1741           1 :         d.mu.Lock()
    1742           1 :         maxLevelWithFiles := 1
    1743           1 :         cur := d.mu.versions.currentVersion()
    1744           1 :         for level := 0; level < numLevels; level++ {
    1745           1 :                 overlaps := cur.Overlaps(level, start, end, false)
    1746           1 :                 if !overlaps.Empty() {
    1747           1 :                         maxLevelWithFiles = level + 1
    1748           1 :                 }
    1749             :         }
    1750             : 
    1751             :         // Determine if any memtable overlaps with the compaction range. We wait for
    1752             :         // any such overlap to flush (initiating a flush if necessary).
    1753           1 :         mem, err := func() (*flushableEntry, error) {
    1754           1 :                 // Check to see if any files overlap with any of the memtables. The queue
    1755           1 :                 // is ordered from oldest to newest with the mutable memtable being the
    1756           1 :                 // last element in the slice. We want to wait for the newest table that
    1757           1 :                 // overlaps.
    1758           1 :                 for i := len(d.mu.mem.queue) - 1; i >= 0; i-- {
    1759           1 :                         mem := d.mu.mem.queue[i]
    1760           1 :                         var anyOverlaps bool
    1761           1 :                         mem.computePossibleOverlaps(func(b bounded) shouldContinue {
    1762           1 :                                 anyOverlaps = true
    1763           1 :                                 return stopIteration
    1764           1 :                         }, KeyRange{Start: start, End: end})
    1765           1 :                         if !anyOverlaps {
    1766           1 :                                 continue
    1767             :                         }
    1768           1 :                         var err error
    1769           1 :                         if mem.flushable == d.mu.mem.mutable {
    1770           1 :                                 // We have to hold both commitPipeline.mu and DB.mu when calling
    1771           1 :                                 // makeRoomForWrite(). Lock order requirements elsewhere force us to
    1772           1 :                                 // unlock DB.mu in order to grab commitPipeline.mu first.
    1773           1 :                                 d.mu.Unlock()
    1774           1 :                                 d.commit.mu.Lock()
    1775           1 :                                 d.mu.Lock()
    1776           1 :                                 defer d.commit.mu.Unlock()
    1777           1 :                                 if mem.flushable == d.mu.mem.mutable {
    1778           1 :                                         // Only flush if the active memtable is unchanged.
    1779           1 :                                         err = d.makeRoomForWrite(nil)
    1780           1 :                                 }
    1781             :                         }
    1782           1 :                         mem.flushForced = true
    1783           1 :                         d.maybeScheduleFlush()
    1784           1 :                         return mem, err
    1785             :                 }
    1786           1 :                 return nil, nil
    1787             :         }()
    1788             : 
    1789           1 :         d.mu.Unlock()
    1790           1 : 
    1791           1 :         if err != nil {
    1792           0 :                 return err
    1793           0 :         }
    1794           1 :         if mem != nil {
    1795           1 :                 <-mem.flushed
    1796           1 :         }
    1797             : 
    1798           1 :         for level := 0; level < maxLevelWithFiles; {
    1799           1 :                 for {
    1800           1 :                         if err := d.manualCompact(
    1801           1 :                                 start, end, level, parallelize); err != nil {
    1802           1 :                                 if errors.Is(err, ErrCancelledCompaction) {
    1803           1 :                                         continue
    1804             :                                 }
    1805           1 :                                 return err
    1806             :                         }
    1807           1 :                         break
    1808             :                 }
    1809           1 :                 level++
    1810           1 :                 if level == numLevels-1 {
    1811           1 :                         // A manual compaction of the bottommost level occurred.
    1812           1 :                         // There is no next level to try and compact.
    1813           1 :                         break
    1814             :                 }
    1815             :         }
    1816           1 :         return nil
    1817             : }
    1818             : 
    1819           1 : func (d *DB) manualCompact(start, end []byte, level int, parallelize bool) error {
    1820           1 :         d.mu.Lock()
    1821           1 :         curr := d.mu.versions.currentVersion()
    1822           1 :         files := curr.Overlaps(level, start, end, false)
    1823           1 :         if files.Empty() {
    1824           1 :                 d.mu.Unlock()
    1825           1 :                 return nil
    1826           1 :         }
    1827             : 
    1828           1 :         var compactions []*manualCompaction
    1829           1 :         if parallelize {
    1830           1 :                 compactions = append(compactions, d.splitManualCompaction(start, end, level)...)
    1831           1 :         } else {
    1832           1 :                 compactions = append(compactions, &manualCompaction{
    1833           1 :                         level: level,
    1834           1 :                         done:  make(chan error, 1),
    1835           1 :                         start: start,
    1836           1 :                         end:   end,
    1837           1 :                 })
    1838           1 :         }
    1839           1 :         d.mu.compact.manual = append(d.mu.compact.manual, compactions...)
    1840           1 :         d.maybeScheduleCompaction()
    1841           1 :         d.mu.Unlock()
    1842           1 : 
    1843           1 :         // Each of the channels is guaranteed to be eventually sent to once. After a
    1844           1 :         // compaction is possibly picked in d.maybeScheduleCompaction(), either the
    1845           1 :         // compaction is dropped, executed after being scheduled, or retried later.
    1846           1 :         // Assuming eventual progress when a compaction is retried, all outcomes send
    1847           1 :         // a value to the done channel. Since the channels are buffered, it is not
    1848           1 :         // necessary to read from each channel, and so we can exit early in the event
    1849           1 :         // of an error.
    1850           1 :         for _, compaction := range compactions {
    1851           1 :                 if err := <-compaction.done; err != nil {
    1852           1 :                         return err
    1853           1 :                 }
    1854             :         }
    1855           1 :         return nil
    1856             : }
    1857             : 
    1858             : // splitManualCompaction splits a manual compaction over [start,end] on level
    1859             : // such that the resulting compactions have no key overlap.
    1860             : func (d *DB) splitManualCompaction(
    1861             :         start, end []byte, level int,
    1862           1 : ) (splitCompactions []*manualCompaction) {
    1863           1 :         curr := d.mu.versions.currentVersion()
    1864           1 :         endLevel := level + 1
    1865           1 :         baseLevel := d.mu.versions.picker.getBaseLevel()
    1866           1 :         if level == 0 {
    1867           1 :                 endLevel = baseLevel
    1868           1 :         }
    1869           1 :         keyRanges := curr.CalculateInuseKeyRanges(level, endLevel, start, end)
    1870           1 :         for _, keyRange := range keyRanges {
    1871           1 :                 splitCompactions = append(splitCompactions, &manualCompaction{
    1872           1 :                         level: level,
    1873           1 :                         done:  make(chan error, 1),
    1874           1 :                         start: keyRange.Start,
    1875           1 :                         end:   keyRange.End,
    1876           1 :                         split: true,
    1877           1 :                 })
    1878           1 :         }
    1879           1 :         return splitCompactions
    1880             : }
    1881             : 
    1882             : // DownloadSpan is a key range passed to the Download method.
    1883             : type DownloadSpan struct {
    1884             :         StartKey []byte
    1885             :         // EndKey is exclusive.
    1886             :         EndKey []byte
    1887             :         // ViaBackingFileDownload, if true, indicates the span should be downloaded by
    1888             :         // downloading any remote backing files byte-for-byte and replacing them with
    1889             :         // the downloaded local files, while otherwise leaving the virtual SSTables
    1890             :         // as-is. If false, a "normal" rewriting compaction of the span, that iterates
    1891             :         // the keys and produces a new SSTable, is used instead. Downloading raw files
    1892             :         // can be faster when the whole file is being downloaded, as it avoids some
    1893             :         // cpu-intensive steps involved in iteration and new file construction such as
    1894             :         // compression, however it can also be wasteful when only a small portion of a
    1895             :         // larger backing file is being used by a virtual file. Additionally, if the
    1896             :         // virtual file has expensive read-time transformations, such as prefix
    1897             :         // replacement, rewriting once can persist the result of these for future use
    1898             :         // while copying only the backing file will obligate future reads to continue
    1899             :         // to compute such transforms.
    1900             :         ViaBackingFileDownload bool
    1901             : }
    1902             : 
    1903           1 : func (d *DB) downloadSpan(ctx context.Context, span DownloadSpan) error {
    1904           1 :         dSpan := &downloadSpan{
    1905           1 :                 start: span.StartKey,
    1906           1 :                 end:   span.EndKey,
    1907           1 :                 // Protected by d.mu.
    1908           1 :                 doneChans: make([]chan error, 1),
    1909           1 :                 kind:      compactionKindRewrite,
    1910           1 :         }
    1911           1 :         if span.ViaBackingFileDownload {
    1912           1 :                 dSpan.kind = compactionKindCopy
    1913           1 :         }
    1914           1 :         dSpan.doneChans[0] = make(chan error, 1)
    1915           1 :         doneChan := dSpan.doneChans[0]
    1916           1 :         compactionIdx := 0
    1917           1 : 
    1918           1 :         func() {
    1919           1 :                 d.mu.Lock()
    1920           1 :                 defer d.mu.Unlock()
    1921           1 : 
    1922           1 :                 d.mu.compact.downloads = append(d.mu.compact.downloads, dSpan)
    1923           1 :                 d.maybeScheduleCompaction()
    1924           1 :         }()
    1925             : 
    1926             :         // Requires d.mu to be held.
    1927           1 :         noExternalFilesInSpan := func() (noExternalFiles bool) {
    1928           1 :                 vers := d.mu.versions.currentVersion()
    1929           1 : 
    1930           1 :                 for i := 0; i < len(vers.Levels); i++ {
    1931           1 :                         if vers.Levels[i].Empty() {
    1932           1 :                                 continue
    1933             :                         }
    1934           1 :                         overlap := vers.Overlaps(i, span.StartKey, span.EndKey, true /* exclusiveEnd */)
    1935           1 :                         foundExternalFile := false
    1936           1 :                         overlap.Each(func(metadata *manifest.FileMetadata) {
    1937           1 :                                 objMeta, err := d.objProvider.Lookup(fileTypeTable, metadata.FileBacking.DiskFileNum)
    1938           1 :                                 if err != nil {
    1939           0 :                                         return
    1940           0 :                                 }
    1941           1 :                                 if objMeta.IsExternal() {
    1942           1 :                                         foundExternalFile = true
    1943           1 :                                 }
    1944             :                         })
    1945           1 :                         if foundExternalFile {
    1946           1 :                                 return false
    1947           1 :                         }
    1948             :                 }
    1949           1 :                 return true
    1950             :         }
    1951             : 
    1952             :         // Requires d.mu to be held.
    1953           1 :         removeUsFromList := func() {
    1954           1 :                 // Check where we are in d.mu.compact.downloads. Remove us from the
    1955           1 :                 // list.
    1956           1 :                 for i := range d.mu.compact.downloads {
    1957           0 :                         if d.mu.compact.downloads[i] != dSpan {
    1958           0 :                                 continue
    1959             :                         }
    1960           0 :                         copy(d.mu.compact.downloads[i:], d.mu.compact.downloads[i+1:])
    1961           0 :                         d.mu.compact.downloads = d.mu.compact.downloads[:len(d.mu.compact.downloads)-1]
    1962           0 :                         break
    1963             :                 }
    1964             :         }
    1965             : 
    1966           1 :         for {
    1967           1 :                 select {
    1968           0 :                 case <-ctx.Done():
    1969           0 :                         d.mu.Lock()
    1970           0 :                         defer d.mu.Unlock()
    1971           0 :                         removeUsFromList()
    1972           0 :                         return ctx.Err()
    1973           1 :                 case err := <-doneChan:
    1974           1 :                         if err != nil {
    1975           0 :                                 d.mu.Lock()
    1976           0 :                                 defer d.mu.Unlock()
    1977           0 :                                 removeUsFromList()
    1978           0 :                                 return err
    1979           0 :                         }
    1980           1 :                         compactionIdx++
    1981           1 :                         // Grab the next doneCh to wait on.
    1982           1 :                         func() {
    1983           1 :                                 d.mu.Lock()
    1984           1 :                                 defer d.mu.Unlock()
    1985           1 :                                 doneChan = dSpan.doneChans[compactionIdx]
    1986           1 :                         }()
    1987           1 :                 default:
    1988           1 :                         doneSpan := func() bool {
    1989           1 :                                 d.mu.Lock()
    1990           1 :                                 defer d.mu.Unlock()
    1991           1 :                                 // It's possible to have downloaded all files without writing to any
    1992           1 :                                 // doneChans. This is expected if there are a significant amount
    1993           1 :                                 // of overlapping writes that schedule regular, non-download compactions.
    1994           1 :                                 if noExternalFilesInSpan() {
    1995           1 :                                         removeUsFromList()
    1996           1 :                                         return true
    1997           1 :                                 }
    1998           1 :                                 d.maybeScheduleCompaction()
    1999           1 :                                 if d.mu.compact.compactingCount == 0 {
    2000           0 :                                         // No compactions were scheduled above. Waiting on the cond lock below
    2001           0 :                                         // could possibly lead to a forever-wait. Return true if the db is
    2002           0 :                                         // closed so we exit out of this method.
    2003           0 :                                         return d.closed.Load() != nil
    2004           0 :                                 }
    2005           1 :                                 d.mu.compact.cond.Wait()
    2006           1 :                                 return false
    2007             :                         }()
    2008           1 :                         if doneSpan {
    2009           1 :                                 return nil
    2010           1 :                         }
    2011             :                 }
    2012             :         }
    2013             : }
    2014             : 
    2015             : // Download ensures that the LSM does not use any external sstables for the
    2016             : // given key ranges. It does so by performing appropriate compactions so that
    2017             : // all external data becomes available locally.
    2018             : //
    2019             : // Note that calling this method does not imply that all other compactions stop;
    2020             : // it simply informs Pebble of a list of spans for which external data should be
    2021             : // downloaded with high priority.
    2022             : //
    2023             : // The method returns once no external sstasbles overlap the given spans, the
    2024             : // context is canceled, the db is closed, or an error is hit.
    2025             : //
    2026             : // TODO(radu): consider passing a priority/impact knob to express how important
    2027             : // the download is (versus live traffic performance, LSM health).
    2028           1 : func (d *DB) Download(ctx context.Context, spans []DownloadSpan) error {
    2029           1 :         ctx, cancel := context.WithCancel(ctx)
    2030           1 :         defer cancel()
    2031           1 :         if err := d.closed.Load(); err != nil {
    2032           0 :                 panic(err)
    2033             :         }
    2034           1 :         if d.opts.ReadOnly {
    2035           0 :                 return ErrReadOnly
    2036           0 :         }
    2037           1 :         for i := range spans {
    2038           1 :                 if err := ctx.Err(); err != nil {
    2039           0 :                         return err
    2040           0 :                 }
    2041           1 :                 if err := d.downloadSpan(ctx, spans[i]); err != nil {
    2042           0 :                         return err
    2043           0 :                 }
    2044             :         }
    2045           1 :         return nil
    2046             : }
    2047             : 
    2048             : // Flush the memtable to stable storage.
    2049           1 : func (d *DB) Flush() error {
    2050           1 :         flushDone, err := d.AsyncFlush()
    2051           1 :         if err != nil {
    2052           1 :                 return err
    2053           1 :         }
    2054           1 :         <-flushDone
    2055           1 :         return nil
    2056             : }
    2057             : 
    2058             : // AsyncFlush asynchronously flushes the memtable to stable storage.
    2059             : //
    2060             : // If no error is returned, the caller can receive from the returned channel in
    2061             : // order to wait for the flush to complete.
    2062           1 : func (d *DB) AsyncFlush() (<-chan struct{}, error) {
    2063           1 :         if err := d.closed.Load(); err != nil {
    2064           1 :                 panic(err)
    2065             :         }
    2066           1 :         if d.opts.ReadOnly {
    2067           1 :                 return nil, ErrReadOnly
    2068           1 :         }
    2069             : 
    2070           1 :         d.commit.mu.Lock()
    2071           1 :         defer d.commit.mu.Unlock()
    2072           1 :         d.mu.Lock()
    2073           1 :         defer d.mu.Unlock()
    2074           1 :         flushed := d.mu.mem.queue[len(d.mu.mem.queue)-1].flushed
    2075           1 :         err := d.makeRoomForWrite(nil)
    2076           1 :         if err != nil {
    2077           0 :                 return nil, err
    2078           0 :         }
    2079           1 :         return flushed, nil
    2080             : }
    2081             : 
    2082             : // Metrics returns metrics about the database.
    2083           1 : func (d *DB) Metrics() *Metrics {
    2084           1 :         metrics := &Metrics{}
    2085           1 :         walStats := d.mu.log.manager.Stats()
    2086           1 : 
    2087           1 :         d.mu.Lock()
    2088           1 :         vers := d.mu.versions.currentVersion()
    2089           1 :         *metrics = d.mu.versions.metrics
    2090           1 :         metrics.Compact.EstimatedDebt = d.mu.versions.picker.estimatedCompactionDebt(0)
    2091           1 :         metrics.Compact.InProgressBytes = d.mu.versions.atomicInProgressBytes.Load()
    2092           1 :         metrics.Compact.NumInProgress = int64(d.mu.compact.compactingCount)
    2093           1 :         metrics.Compact.MarkedFiles = vers.Stats.MarkedForCompaction
    2094           1 :         metrics.Compact.Duration = d.mu.compact.duration
    2095           1 :         for c := range d.mu.compact.inProgress {
    2096           1 :                 if c.kind != compactionKindFlush {
    2097           1 :                         metrics.Compact.Duration += d.timeNow().Sub(c.beganAt)
    2098           1 :                 }
    2099             :         }
    2100             : 
    2101           1 :         for _, m := range d.mu.mem.queue {
    2102           1 :                 metrics.MemTable.Size += m.totalBytes()
    2103           1 :         }
    2104           1 :         metrics.Snapshots.Count = d.mu.snapshots.count()
    2105           1 :         if metrics.Snapshots.Count > 0 {
    2106           0 :                 metrics.Snapshots.EarliestSeqNum = d.mu.snapshots.earliest()
    2107           0 :         }
    2108           1 :         metrics.Snapshots.PinnedKeys = d.mu.snapshots.cumulativePinnedCount
    2109           1 :         metrics.Snapshots.PinnedSize = d.mu.snapshots.cumulativePinnedSize
    2110           1 :         metrics.MemTable.Count = int64(len(d.mu.mem.queue))
    2111           1 :         metrics.MemTable.ZombieCount = d.memTableCount.Load() - metrics.MemTable.Count
    2112           1 :         metrics.MemTable.ZombieSize = uint64(d.memTableReserved.Load()) - metrics.MemTable.Size
    2113           1 :         metrics.WAL.ObsoleteFiles = int64(walStats.ObsoleteFileCount)
    2114           1 :         metrics.WAL.ObsoletePhysicalSize = walStats.ObsoleteFileSize
    2115           1 :         metrics.WAL.Files = int64(walStats.LiveFileCount)
    2116           1 :         // The current WAL's size (d.logSize) is the logical size, which may be less
    2117           1 :         // than the WAL's physical size if it was recycled. walStats.LiveFileSize
    2118           1 :         // includes the physical size of all live WALs, but for the current WAL it
    2119           1 :         // reflects the physical size when it was opened. So it is possible that
    2120           1 :         // d.atomic.logSize has exceeded that physical size. We allow for this
    2121           1 :         // anomaly.
    2122           1 :         metrics.WAL.PhysicalSize = walStats.LiveFileSize
    2123           1 :         metrics.WAL.BytesIn = d.mu.log.bytesIn // protected by d.mu
    2124           1 :         metrics.WAL.Size = d.logSize.Load()
    2125           1 :         for i, n := 0, len(d.mu.mem.queue)-1; i < n; i++ {
    2126           1 :                 metrics.WAL.Size += d.mu.mem.queue[i].logSize
    2127           1 :         }
    2128           1 :         metrics.WAL.BytesWritten = metrics.Levels[0].BytesIn + metrics.WAL.Size
    2129           1 :         metrics.WAL.Failover = walStats.Failover
    2130           1 : 
    2131           1 :         if p := d.mu.versions.picker; p != nil {
    2132           1 :                 compactions := d.getInProgressCompactionInfoLocked(nil)
    2133           1 :                 for level, score := range p.getScores(compactions) {
    2134           1 :                         metrics.Levels[level].Score = score
    2135           1 :                 }
    2136             :         }
    2137           1 :         metrics.Table.ZombieCount = int64(len(d.mu.versions.zombieTables))
    2138           1 :         for _, size := range d.mu.versions.zombieTables {
    2139           1 :                 metrics.Table.ZombieSize += size
    2140           1 :         }
    2141           1 :         metrics.private.optionsFileSize = d.optionsFileSize
    2142           1 : 
    2143           1 :         // TODO(jackson): Consider making these metrics optional.
    2144           1 :         metrics.Keys.RangeKeySetsCount = countRangeKeySetFragments(vers)
    2145           1 :         metrics.Keys.TombstoneCount = countTombstones(vers)
    2146           1 : 
    2147           1 :         d.mu.versions.logLock()
    2148           1 :         metrics.private.manifestFileSize = uint64(d.mu.versions.manifest.Size())
    2149           1 :         backingCount, backingTotalSize := d.mu.versions.fileBackings.Stats()
    2150           1 :         metrics.Table.BackingTableCount = uint64(backingCount)
    2151           1 :         metrics.Table.BackingTableSize = backingTotalSize
    2152           1 :         d.mu.versions.logUnlock()
    2153           1 : 
    2154           1 :         metrics.LogWriter.FsyncLatency = d.mu.log.metrics.fsyncLatency
    2155           1 :         if err := metrics.LogWriter.Merge(&d.mu.log.metrics.LogWriterMetrics); err != nil {
    2156           0 :                 d.opts.Logger.Errorf("metrics error: %s", err)
    2157           0 :         }
    2158           1 :         metrics.Flush.WriteThroughput = d.mu.compact.flushWriteThroughput
    2159           1 :         if d.mu.compact.flushing {
    2160           1 :                 metrics.Flush.NumInProgress = 1
    2161           1 :         }
    2162           1 :         for i := 0; i < numLevels; i++ {
    2163           1 :                 metrics.Levels[i].Additional.ValueBlocksSize = valueBlocksSizeForLevel(vers, i)
    2164           1 :         }
    2165             : 
    2166           1 :         d.mu.Unlock()
    2167           1 : 
    2168           1 :         metrics.BlockCache = d.opts.Cache.Metrics()
    2169           1 :         metrics.TableCache, metrics.Filter = d.tableCache.metrics()
    2170           1 :         metrics.TableIters = int64(d.tableCache.iterCount())
    2171           1 :         metrics.CategoryStats = d.tableCache.dbOpts.sstStatsCollector.GetStats()
    2172           1 : 
    2173           1 :         metrics.SecondaryCacheMetrics = d.objProvider.Metrics()
    2174           1 : 
    2175           1 :         metrics.Uptime = d.timeNow().Sub(d.openedAt)
    2176           1 : 
    2177           1 :         return metrics
    2178             : }
    2179             : 
    2180             : // sstablesOptions hold the optional parameters to retrieve TableInfo for all sstables.
    2181             : type sstablesOptions struct {
    2182             :         // set to true will return the sstable properties in TableInfo
    2183             :         withProperties bool
    2184             : 
    2185             :         // if set, return sstables that overlap the key range (end-exclusive)
    2186             :         start []byte
    2187             :         end   []byte
    2188             : 
    2189             :         withApproximateSpanBytes bool
    2190             : }
    2191             : 
    2192             : // SSTablesOption set optional parameter used by `DB.SSTables`.
    2193             : type SSTablesOption func(*sstablesOptions)
    2194             : 
    2195             : // WithProperties enable return sstable properties in each TableInfo.
    2196             : //
    2197             : // NOTE: if most of the sstable properties need to be read from disk,
    2198             : // this options may make method `SSTables` quite slow.
    2199           1 : func WithProperties() SSTablesOption {
    2200           1 :         return func(opt *sstablesOptions) {
    2201           1 :                 opt.withProperties = true
    2202           1 :         }
    2203             : }
    2204             : 
    2205             : // WithKeyRangeFilter ensures returned sstables overlap start and end (end-exclusive)
    2206             : // if start and end are both nil these properties have no effect.
    2207           1 : func WithKeyRangeFilter(start, end []byte) SSTablesOption {
    2208           1 :         return func(opt *sstablesOptions) {
    2209           1 :                 opt.end = end
    2210           1 :                 opt.start = start
    2211           1 :         }
    2212             : }
    2213             : 
    2214             : // WithApproximateSpanBytes enables capturing the approximate number of bytes that
    2215             : // overlap the provided key span for each sstable.
    2216             : // NOTE: this option can only be used with WithKeyRangeFilter and WithProperties
    2217             : // provided.
    2218           1 : func WithApproximateSpanBytes() SSTablesOption {
    2219           1 :         return func(opt *sstablesOptions) {
    2220           1 :                 opt.withApproximateSpanBytes = true
    2221           1 :         }
    2222             : }
    2223             : 
    2224             : // BackingType denotes the type of storage backing a given sstable.
    2225             : type BackingType int
    2226             : 
    2227             : const (
    2228             :         // BackingTypeLocal denotes an sstable stored on local disk according to the
    2229             :         // objprovider. This file is completely owned by us.
    2230             :         BackingTypeLocal BackingType = iota
    2231             :         // BackingTypeShared denotes an sstable stored on shared storage, created
    2232             :         // by this Pebble instance and possibly shared by other Pebble instances.
    2233             :         // These types of files have lifecycle managed by Pebble.
    2234             :         BackingTypeShared
    2235             :         // BackingTypeSharedForeign denotes an sstable stored on shared storage,
    2236             :         // created by a Pebble instance other than this one. These types of files have
    2237             :         // lifecycle managed by Pebble.
    2238             :         BackingTypeSharedForeign
    2239             :         // BackingTypeExternal denotes an sstable stored on external storage,
    2240             :         // not owned by any Pebble instance and with no refcounting/cleanup methods
    2241             :         // or lifecycle management. An example of an external file is a file restored
    2242             :         // from a backup.
    2243             :         BackingTypeExternal
    2244             : )
    2245             : 
    2246             : // SSTableInfo export manifest.TableInfo with sstable.Properties alongside
    2247             : // other file backing info.
    2248             : type SSTableInfo struct {
    2249             :         manifest.TableInfo
    2250             :         // Virtual indicates whether the sstable is virtual.
    2251             :         Virtual bool
    2252             :         // BackingSSTNum is the disk file number associated with the backing sstable.
    2253             :         // If Virtual is false, BackingSSTNum == PhysicalTableDiskFileNum(FileNum).
    2254             :         BackingSSTNum base.DiskFileNum
    2255             :         // BackingType is the type of storage backing this sstable.
    2256             :         BackingType BackingType
    2257             :         // Locator is the remote.Locator backing this sstable, if the backing type is
    2258             :         // not BackingTypeLocal.
    2259             :         Locator remote.Locator
    2260             : 
    2261             :         // Properties is the sstable properties of this table. If Virtual is true,
    2262             :         // then the Properties are associated with the backing sst.
    2263             :         Properties *sstable.Properties
    2264             : }
    2265             : 
    2266             : // SSTables retrieves the current sstables. The returned slice is indexed by
    2267             : // level and each level is indexed by the position of the sstable within the
    2268             : // level. Note that this information may be out of date due to concurrent
    2269             : // flushes and compactions.
    2270           1 : func (d *DB) SSTables(opts ...SSTablesOption) ([][]SSTableInfo, error) {
    2271           1 :         opt := &sstablesOptions{}
    2272           1 :         for _, fn := range opts {
    2273           1 :                 fn(opt)
    2274           1 :         }
    2275             : 
    2276           1 :         if opt.withApproximateSpanBytes && !opt.withProperties {
    2277           1 :                 return nil, errors.Errorf("Cannot use WithApproximateSpanBytes without WithProperties option.")
    2278           1 :         }
    2279           1 :         if opt.withApproximateSpanBytes && (opt.start == nil || opt.end == nil) {
    2280           1 :                 return nil, errors.Errorf("Cannot use WithApproximateSpanBytes without WithKeyRangeFilter option.")
    2281           1 :         }
    2282             : 
    2283             :         // Grab and reference the current readState.
    2284           1 :         readState := d.loadReadState()
    2285           1 :         defer readState.unref()
    2286           1 : 
    2287           1 :         // TODO(peter): This is somewhat expensive, especially on a large
    2288           1 :         // database. It might be worthwhile to unify TableInfo and FileMetadata and
    2289           1 :         // then we could simply return current.Files. Note that RocksDB is doing
    2290           1 :         // something similar to the current code, so perhaps it isn't too bad.
    2291           1 :         srcLevels := readState.current.Levels
    2292           1 :         var totalTables int
    2293           1 :         for i := range srcLevels {
    2294           1 :                 totalTables += srcLevels[i].Len()
    2295           1 :         }
    2296             : 
    2297           1 :         destTables := make([]SSTableInfo, totalTables)
    2298           1 :         destLevels := make([][]SSTableInfo, len(srcLevels))
    2299           1 :         for i := range destLevels {
    2300           1 :                 iter := srcLevels[i].Iter()
    2301           1 :                 j := 0
    2302           1 :                 for m := iter.First(); m != nil; m = iter.Next() {
    2303           1 :                         if opt.start != nil && opt.end != nil && !m.Overlaps(d.opts.Comparer.Compare, opt.start, opt.end, true /* exclusive end */) {
    2304           1 :                                 continue
    2305             :                         }
    2306           1 :                         destTables[j] = SSTableInfo{TableInfo: m.TableInfo()}
    2307           1 :                         if opt.withProperties {
    2308           1 :                                 p, err := d.tableCache.getTableProperties(
    2309           1 :                                         m,
    2310           1 :                                 )
    2311           1 :                                 if err != nil {
    2312           0 :                                         return nil, err
    2313           0 :                                 }
    2314           1 :                                 destTables[j].Properties = p
    2315             :                         }
    2316           1 :                         destTables[j].Virtual = m.Virtual
    2317           1 :                         destTables[j].BackingSSTNum = m.FileBacking.DiskFileNum
    2318           1 :                         objMeta, err := d.objProvider.Lookup(fileTypeTable, m.FileBacking.DiskFileNum)
    2319           1 :                         if err != nil {
    2320           0 :                                 return nil, err
    2321           0 :                         }
    2322           1 :                         if objMeta.IsRemote() {
    2323           0 :                                 if objMeta.IsShared() {
    2324           0 :                                         if d.objProvider.IsSharedForeign(objMeta) {
    2325           0 :                                                 destTables[j].BackingType = BackingTypeSharedForeign
    2326           0 :                                         } else {
    2327           0 :                                                 destTables[j].BackingType = BackingTypeShared
    2328           0 :                                         }
    2329           0 :                                 } else {
    2330           0 :                                         destTables[j].BackingType = BackingTypeExternal
    2331           0 :                                 }
    2332           0 :                                 destTables[j].Locator = objMeta.Remote.Locator
    2333           1 :                         } else {
    2334           1 :                                 destTables[j].BackingType = BackingTypeLocal
    2335           1 :                         }
    2336             : 
    2337           1 :                         if opt.withApproximateSpanBytes {
    2338           1 :                                 var spanBytes uint64
    2339           1 :                                 if m.ContainedWithinSpan(d.opts.Comparer.Compare, opt.start, opt.end) {
    2340           1 :                                         spanBytes = m.Size
    2341           1 :                                 } else {
    2342           1 :                                         size, err := d.tableCache.estimateSize(m, opt.start, opt.end)
    2343           1 :                                         if err != nil {
    2344           0 :                                                 return nil, err
    2345           0 :                                         }
    2346           1 :                                         spanBytes = size
    2347             :                                 }
    2348           1 :                                 propertiesCopy := *destTables[j].Properties
    2349           1 : 
    2350           1 :                                 // Deep copy user properties so approximate span bytes can be added.
    2351           1 :                                 propertiesCopy.UserProperties = make(map[string]string, len(destTables[j].Properties.UserProperties)+1)
    2352           1 :                                 for k, v := range destTables[j].Properties.UserProperties {
    2353           0 :                                         propertiesCopy.UserProperties[k] = v
    2354           0 :                                 }
    2355           1 :                                 propertiesCopy.UserProperties["approximate-span-bytes"] = strconv.FormatUint(spanBytes, 10)
    2356           1 :                                 destTables[j].Properties = &propertiesCopy
    2357             :                         }
    2358           1 :                         j++
    2359             :                 }
    2360           1 :                 destLevels[i] = destTables[:j]
    2361           1 :                 destTables = destTables[j:]
    2362             :         }
    2363             : 
    2364           1 :         return destLevels, nil
    2365             : }
    2366             : 
    2367             : // EstimateDiskUsage returns the estimated filesystem space used in bytes for
    2368             : // storing the range `[start, end]`. The estimation is computed as follows:
    2369             : //
    2370             : //   - For sstables fully contained in the range the whole file size is included.
    2371             : //   - For sstables partially contained in the range the overlapping data block sizes
    2372             : //     are included. Even if a data block partially overlaps, or we cannot determine
    2373             : //     overlap due to abbreviated index keys, the full data block size is included in
    2374             : //     the estimation. Note that unlike fully contained sstables, none of the
    2375             : //     meta-block space is counted for partially overlapped files.
    2376             : //   - For virtual sstables, we use the overlap between start, end and the virtual
    2377             : //     sstable bounds to determine disk usage.
    2378             : //   - There may also exist WAL entries for unflushed keys in this range. This
    2379             : //     estimation currently excludes space used for the range in the WAL.
    2380           1 : func (d *DB) EstimateDiskUsage(start, end []byte) (uint64, error) {
    2381           1 :         bytes, _, _, err := d.EstimateDiskUsageByBackingType(start, end)
    2382           1 :         return bytes, err
    2383           1 : }
    2384             : 
    2385             : // EstimateDiskUsageByBackingType is like EstimateDiskUsage but additionally
    2386             : // returns the subsets of that size in remote ane external files.
    2387             : func (d *DB) EstimateDiskUsageByBackingType(
    2388             :         start, end []byte,
    2389           1 : ) (totalSize, remoteSize, externalSize uint64, _ error) {
    2390           1 :         if err := d.closed.Load(); err != nil {
    2391           0 :                 panic(err)
    2392             :         }
    2393           1 :         if d.opts.Comparer.Compare(start, end) > 0 {
    2394           0 :                 return 0, 0, 0, errors.New("invalid key-range specified (start > end)")
    2395           0 :         }
    2396             : 
    2397             :         // Grab and reference the current readState. This prevents the underlying
    2398             :         // files in the associated version from being deleted if there is a concurrent
    2399             :         // compaction.
    2400           1 :         readState := d.loadReadState()
    2401           1 :         defer readState.unref()
    2402           1 : 
    2403           1 :         for level, files := range readState.current.Levels {
    2404           1 :                 iter := files.Iter()
    2405           1 :                 if level > 0 {
    2406           1 :                         // We can only use `Overlaps` to restrict `files` at L1+ since at L0 it
    2407           1 :                         // expands the range iteratively until it has found a set of files that
    2408           1 :                         // do not overlap any other L0 files outside that set.
    2409           1 :                         overlaps := readState.current.Overlaps(level, start, end, false /* exclusiveEnd */)
    2410           1 :                         iter = overlaps.Iter()
    2411           1 :                 }
    2412           1 :                 for file := iter.First(); file != nil; file = iter.Next() {
    2413           1 :                         if d.opts.Comparer.Compare(start, file.Smallest.UserKey) <= 0 &&
    2414           1 :                                 d.opts.Comparer.Compare(file.Largest.UserKey, end) <= 0 {
    2415           1 :                                 // The range fully contains the file, so skip looking it up in
    2416           1 :                                 // table cache/looking at its indexes, and add the full file size.
    2417           1 :                                 meta, err := d.objProvider.Lookup(fileTypeTable, file.FileBacking.DiskFileNum)
    2418           1 :                                 if err != nil {
    2419           0 :                                         return 0, 0, 0, err
    2420           0 :                                 }
    2421           1 :                                 if meta.IsRemote() {
    2422           0 :                                         remoteSize += file.Size
    2423           0 :                                         if meta.Remote.CleanupMethod == objstorage.SharedNoCleanup {
    2424           0 :                                                 externalSize += file.Size
    2425           0 :                                         }
    2426             :                                 }
    2427           1 :                                 totalSize += file.Size
    2428           1 :                         } else if d.opts.Comparer.Compare(file.Smallest.UserKey, end) <= 0 &&
    2429           1 :                                 d.opts.Comparer.Compare(start, file.Largest.UserKey) <= 0 {
    2430           1 :                                 var size uint64
    2431           1 :                                 var err error
    2432           1 :                                 if file.Virtual {
    2433           0 :                                         err = d.tableCache.withVirtualReader(
    2434           0 :                                                 file.VirtualMeta(),
    2435           0 :                                                 func(r sstable.VirtualReader) (err error) {
    2436           0 :                                                         size, err = r.EstimateDiskUsage(start, end)
    2437           0 :                                                         return err
    2438           0 :                                                 },
    2439             :                                         )
    2440           1 :                                 } else {
    2441           1 :                                         err = d.tableCache.withReader(
    2442           1 :                                                 file.PhysicalMeta(),
    2443           1 :                                                 func(r *sstable.Reader) (err error) {
    2444           1 :                                                         size, err = r.EstimateDiskUsage(start, end)
    2445           1 :                                                         return err
    2446           1 :                                                 },
    2447             :                                         )
    2448             :                                 }
    2449           1 :                                 if err != nil {
    2450           0 :                                         return 0, 0, 0, err
    2451           0 :                                 }
    2452           1 :                                 meta, err := d.objProvider.Lookup(fileTypeTable, file.FileBacking.DiskFileNum)
    2453           1 :                                 if err != nil {
    2454           0 :                                         return 0, 0, 0, err
    2455           0 :                                 }
    2456           1 :                                 if meta.IsRemote() {
    2457           0 :                                         remoteSize += size
    2458           0 :                                         if meta.Remote.CleanupMethod == objstorage.SharedNoCleanup {
    2459           0 :                                                 externalSize += size
    2460           0 :                                         }
    2461             :                                 }
    2462           1 :                                 totalSize += size
    2463             :                         }
    2464             :                 }
    2465             :         }
    2466           1 :         return totalSize, remoteSize, externalSize, nil
    2467             : }
    2468             : 
    2469           1 : func (d *DB) walPreallocateSize() int {
    2470           1 :         // Set the WAL preallocate size to 110% of the memtable size. Note that there
    2471           1 :         // is a bit of apples and oranges in units here as the memtabls size
    2472           1 :         // corresponds to the memory usage of the memtable while the WAL size is the
    2473           1 :         // size of the batches (plus overhead) stored in the WAL.
    2474           1 :         //
    2475           1 :         // TODO(peter): 110% of the memtable size is quite hefty for a block
    2476           1 :         // size. This logic is taken from GetWalPreallocateBlockSize in
    2477           1 :         // RocksDB. Could a smaller preallocation block size be used?
    2478           1 :         size := d.opts.MemTableSize
    2479           1 :         size = (size / 10) + size
    2480           1 :         return int(size)
    2481           1 : }
    2482             : 
    2483           1 : func (d *DB) newMemTable(logNum base.DiskFileNum, logSeqNum uint64) (*memTable, *flushableEntry) {
    2484           1 :         size := d.mu.mem.nextSize
    2485           1 :         if d.mu.mem.nextSize < d.opts.MemTableSize {
    2486           1 :                 d.mu.mem.nextSize *= 2
    2487           1 :                 if d.mu.mem.nextSize > d.opts.MemTableSize {
    2488           1 :                         d.mu.mem.nextSize = d.opts.MemTableSize
    2489           1 :                 }
    2490             :         }
    2491             : 
    2492           1 :         memtblOpts := memTableOptions{
    2493           1 :                 Options:   d.opts,
    2494           1 :                 logSeqNum: logSeqNum,
    2495           1 :         }
    2496           1 : 
    2497           1 :         // Before attempting to allocate a new memtable, check if there's one
    2498           1 :         // available for recycling in memTableRecycle. Large contiguous allocations
    2499           1 :         // can be costly as fragmentation makes it more difficult to find a large
    2500           1 :         // contiguous free space. We've observed 64MB allocations taking 10ms+.
    2501           1 :         //
    2502           1 :         // To reduce these costly allocations, up to 1 obsolete memtable is stashed
    2503           1 :         // in `d.memTableRecycle` to allow a future memtable rotation to reuse
    2504           1 :         // existing memory.
    2505           1 :         var mem *memTable
    2506           1 :         mem = d.memTableRecycle.Swap(nil)
    2507           1 :         if mem != nil && uint64(len(mem.arenaBuf)) != size {
    2508           1 :                 d.freeMemTable(mem)
    2509           1 :                 mem = nil
    2510           1 :         }
    2511           1 :         if mem != nil {
    2512           1 :                 // Carry through the existing buffer and memory reservation.
    2513           1 :                 memtblOpts.arenaBuf = mem.arenaBuf
    2514           1 :                 memtblOpts.releaseAccountingReservation = mem.releaseAccountingReservation
    2515           1 :         } else {
    2516           1 :                 mem = new(memTable)
    2517           1 :                 memtblOpts.arenaBuf = manual.New(int(size))
    2518           1 :                 memtblOpts.releaseAccountingReservation = d.opts.Cache.Reserve(int(size))
    2519           1 :                 d.memTableCount.Add(1)
    2520           1 :                 d.memTableReserved.Add(int64(size))
    2521           1 : 
    2522           1 :                 // Note: this is a no-op if invariants are disabled or race is enabled.
    2523           1 :                 invariants.SetFinalizer(mem, checkMemTable)
    2524           1 :         }
    2525           1 :         mem.init(memtblOpts)
    2526           1 : 
    2527           1 :         entry := d.newFlushableEntry(mem, logNum, logSeqNum)
    2528           1 :         entry.releaseMemAccounting = func() {
    2529           1 :                 // If the user leaks iterators, we may be releasing the memtable after
    2530           1 :                 // the DB is already closed. In this case, we want to just release the
    2531           1 :                 // memory because DB.Close won't come along to free it for us.
    2532           1 :                 if err := d.closed.Load(); err != nil {
    2533           1 :                         d.freeMemTable(mem)
    2534           1 :                         return
    2535           1 :                 }
    2536             : 
    2537             :                 // The next memtable allocation might be able to reuse this memtable.
    2538             :                 // Stash it on d.memTableRecycle.
    2539           1 :                 if unusedMem := d.memTableRecycle.Swap(mem); unusedMem != nil {
    2540           1 :                         // There was already a memtable waiting to be recycled. We're now
    2541           1 :                         // responsible for freeing it.
    2542           1 :                         d.freeMemTable(unusedMem)
    2543           1 :                 }
    2544             :         }
    2545           1 :         return mem, entry
    2546             : }
    2547             : 
    2548           1 : func (d *DB) freeMemTable(m *memTable) {
    2549           1 :         d.memTableCount.Add(-1)
    2550           1 :         d.memTableReserved.Add(-int64(len(m.arenaBuf)))
    2551           1 :         m.free()
    2552           1 : }
    2553             : 
    2554             : func (d *DB) newFlushableEntry(
    2555             :         f flushable, logNum base.DiskFileNum, logSeqNum uint64,
    2556           1 : ) *flushableEntry {
    2557           1 :         fe := &flushableEntry{
    2558           1 :                 flushable:      f,
    2559           1 :                 flushed:        make(chan struct{}),
    2560           1 :                 logNum:         logNum,
    2561           1 :                 logSeqNum:      logSeqNum,
    2562           1 :                 deleteFn:       d.mu.versions.addObsolete,
    2563           1 :                 deleteFnLocked: d.mu.versions.addObsoleteLocked,
    2564           1 :         }
    2565           1 :         fe.readerRefs.Store(1)
    2566           1 :         return fe
    2567           1 : }
    2568             : 
    2569             : // makeRoomForWrite ensures that the memtable has room to hold the contents of
    2570             : // Batch. It reserves the space in the memtable and adds a reference to the
    2571             : // memtable. The caller must later ensure that the memtable is unreferenced. If
    2572             : // the memtable is full, or a nil Batch is provided, the current memtable is
    2573             : // rotated (marked as immutable) and a new mutable memtable is allocated. This
    2574             : // memtable rotation also causes a log rotation.
    2575             : //
    2576             : // Both DB.mu and commitPipeline.mu must be held by the caller. Note that DB.mu
    2577             : // may be released and reacquired.
    2578           1 : func (d *DB) makeRoomForWrite(b *Batch) error {
    2579           1 :         if b != nil && b.ingestedSSTBatch {
    2580           0 :                 panic("pebble: invalid function call")
    2581             :         }
    2582             : 
    2583           1 :         force := b == nil || b.flushable != nil
    2584           1 :         stalled := false
    2585           1 :         for {
    2586           1 :                 if b != nil && b.flushable == nil {
    2587           1 :                         err := d.mu.mem.mutable.prepare(b)
    2588           1 :                         if err != arenaskl.ErrArenaFull {
    2589           1 :                                 if stalled {
    2590           1 :                                         d.opts.EventListener.WriteStallEnd()
    2591           1 :                                 }
    2592           1 :                                 return err
    2593             :                         }
    2594           1 :                 } else if !force {
    2595           1 :                         if stalled {
    2596           1 :                                 d.opts.EventListener.WriteStallEnd()
    2597           1 :                         }
    2598           1 :                         return nil
    2599             :                 }
    2600             :                 // force || err == ErrArenaFull, so we need to rotate the current memtable.
    2601           1 :                 {
    2602           1 :                         var size uint64
    2603           1 :                         for i := range d.mu.mem.queue {
    2604           1 :                                 size += d.mu.mem.queue[i].totalBytes()
    2605           1 :                         }
    2606           1 :                         if size >= uint64(d.opts.MemTableStopWritesThreshold)*d.opts.MemTableSize {
    2607           1 :                                 // We have filled up the current memtable, but already queued memtables
    2608           1 :                                 // are still flushing, so we wait.
    2609           1 :                                 if !stalled {
    2610           1 :                                         stalled = true
    2611           1 :                                         d.opts.EventListener.WriteStallBegin(WriteStallBeginInfo{
    2612           1 :                                                 Reason: "memtable count limit reached",
    2613           1 :                                         })
    2614           1 :                                 }
    2615           1 :                                 now := time.Now()
    2616           1 :                                 d.mu.compact.cond.Wait()
    2617           1 :                                 if b != nil {
    2618           1 :                                         b.commitStats.MemTableWriteStallDuration += time.Since(now)
    2619           1 :                                 }
    2620           1 :                                 continue
    2621             :                         }
    2622             :                 }
    2623           1 :                 l0ReadAmp := d.mu.versions.currentVersion().L0Sublevels.ReadAmplification()
    2624           1 :                 if l0ReadAmp >= d.opts.L0StopWritesThreshold {
    2625           1 :                         // There are too many level-0 files, so we wait.
    2626           1 :                         if !stalled {
    2627           1 :                                 stalled = true
    2628           1 :                                 d.opts.EventListener.WriteStallBegin(WriteStallBeginInfo{
    2629           1 :                                         Reason: "L0 file count limit exceeded",
    2630           1 :                                 })
    2631           1 :                         }
    2632           1 :                         now := time.Now()
    2633           1 :                         d.mu.compact.cond.Wait()
    2634           1 :                         if b != nil {
    2635           1 :                                 b.commitStats.L0ReadAmpWriteStallDuration += time.Since(now)
    2636           1 :                         }
    2637           1 :                         continue
    2638             :                 }
    2639             : 
    2640           1 :                 var newLogNum base.DiskFileNum
    2641           1 :                 var prevLogSize uint64
    2642           1 :                 if !d.opts.DisableWAL {
    2643           1 :                         now := time.Now()
    2644           1 :                         newLogNum, prevLogSize = d.recycleWAL()
    2645           1 :                         if b != nil {
    2646           1 :                                 b.commitStats.WALRotationDuration += time.Since(now)
    2647           1 :                         }
    2648             :                 }
    2649             : 
    2650           1 :                 immMem := d.mu.mem.mutable
    2651           1 :                 imm := d.mu.mem.queue[len(d.mu.mem.queue)-1]
    2652           1 :                 imm.logSize = prevLogSize
    2653           1 :                 imm.flushForced = imm.flushForced || (b == nil)
    2654           1 : 
    2655           1 :                 // If we are manually flushing and we used less than half of the bytes in
    2656           1 :                 // the memtable, don't increase the size for the next memtable. This
    2657           1 :                 // reduces memtable memory pressure when an application is frequently
    2658           1 :                 // manually flushing.
    2659           1 :                 if (b == nil) && uint64(immMem.availBytes()) > immMem.totalBytes()/2 {
    2660           1 :                         d.mu.mem.nextSize = immMem.totalBytes()
    2661           1 :                 }
    2662             : 
    2663           1 :                 if b != nil && b.flushable != nil {
    2664           1 :                         // The batch is too large to fit in the memtable so add it directly to
    2665           1 :                         // the immutable queue. The flushable batch is associated with the same
    2666           1 :                         // log as the immutable memtable, but logically occurs after it in
    2667           1 :                         // seqnum space. We ensure while flushing that the flushable batch
    2668           1 :                         // is flushed along with the previous memtable in the flushable
    2669           1 :                         // queue. See the top level comment in DB.flush1 to learn how this
    2670           1 :                         // is ensured.
    2671           1 :                         //
    2672           1 :                         // See DB.commitWrite for the special handling of log writes for large
    2673           1 :                         // batches. In particular, the large batch has already written to
    2674           1 :                         // imm.logNum.
    2675           1 :                         entry := d.newFlushableEntry(b.flushable, imm.logNum, b.SeqNum())
    2676           1 :                         // The large batch is by definition large. Reserve space from the cache
    2677           1 :                         // for it until it is flushed.
    2678           1 :                         entry.releaseMemAccounting = d.opts.Cache.Reserve(int(b.flushable.totalBytes()))
    2679           1 :                         d.mu.mem.queue = append(d.mu.mem.queue, entry)
    2680           1 :                 }
    2681             : 
    2682           1 :                 var logSeqNum uint64
    2683           1 :                 if b != nil {
    2684           1 :                         logSeqNum = b.SeqNum()
    2685           1 :                         if b.flushable != nil {
    2686           1 :                                 logSeqNum += uint64(b.Count())
    2687           1 :                         }
    2688           1 :                 } else {
    2689           1 :                         logSeqNum = d.mu.versions.logSeqNum.Load()
    2690           1 :                 }
    2691           1 :                 d.rotateMemtable(newLogNum, logSeqNum, immMem)
    2692           1 :                 force = false
    2693             :         }
    2694             : }
    2695             : 
    2696             : // Both DB.mu and commitPipeline.mu must be held by the caller.
    2697           1 : func (d *DB) rotateMemtable(newLogNum base.DiskFileNum, logSeqNum uint64, prev *memTable) {
    2698           1 :         // Create a new memtable, scheduling the previous one for flushing. We do
    2699           1 :         // this even if the previous memtable was empty because the DB.Flush
    2700           1 :         // mechanism is dependent on being able to wait for the empty memtable to
    2701           1 :         // flush. We can't just mark the empty memtable as flushed here because we
    2702           1 :         // also have to wait for all previous immutable tables to
    2703           1 :         // flush. Additionally, the memtable is tied to particular WAL file and we
    2704           1 :         // want to go through the flush path in order to recycle that WAL file.
    2705           1 :         //
    2706           1 :         // NB: newLogNum corresponds to the WAL that contains mutations that are
    2707           1 :         // present in the new memtable. When immutable memtables are flushed to
    2708           1 :         // disk, a VersionEdit will be created telling the manifest the minimum
    2709           1 :         // unflushed log number (which will be the next one in d.mu.mem.mutable
    2710           1 :         // that was not flushed).
    2711           1 :         //
    2712           1 :         // NB: prev should be the current mutable memtable.
    2713           1 :         var entry *flushableEntry
    2714           1 :         d.mu.mem.mutable, entry = d.newMemTable(newLogNum, logSeqNum)
    2715           1 :         d.mu.mem.queue = append(d.mu.mem.queue, entry)
    2716           1 :         d.updateReadStateLocked(nil)
    2717           1 :         if prev.writerUnref() {
    2718           1 :                 d.maybeScheduleFlush()
    2719           1 :         }
    2720             : }
    2721             : 
    2722             : // Both DB.mu and commitPipeline.mu must be held by the caller. Note that DB.mu
    2723             : // may be released and reacquired.
    2724           1 : func (d *DB) recycleWAL() (newLogNum base.DiskFileNum, prevLogSize uint64) {
    2725           1 :         if d.opts.DisableWAL {
    2726           0 :                 panic("pebble: invalid function call")
    2727             :         }
    2728           1 :         jobID := d.mu.nextJobID
    2729           1 :         d.mu.nextJobID++
    2730           1 :         newLogNum = d.mu.versions.getNextDiskFileNum()
    2731           1 : 
    2732           1 :         d.mu.Unlock()
    2733           1 :         // Close the previous log first. This writes an EOF trailer
    2734           1 :         // signifying the end of the file and syncs it to disk. We must
    2735           1 :         // close the previous log before linking the new log file,
    2736           1 :         // otherwise a crash could leave both logs with unclean tails, and
    2737           1 :         // Open will treat the previous log as corrupt.
    2738           1 :         offset, err := d.mu.log.writer.Close()
    2739           1 :         if err != nil {
    2740           0 :                 // What to do here? Stumbling on doesn't seem worthwhile. If we failed to
    2741           0 :                 // close the previous log it is possible we lost a write.
    2742           0 :                 panic(err)
    2743             :         }
    2744           1 :         prevLogSize = uint64(offset)
    2745           1 :         metrics := d.mu.log.writer.Metrics()
    2746           1 : 
    2747           1 :         d.mu.Lock()
    2748           1 :         if err := d.mu.log.metrics.LogWriterMetrics.Merge(&metrics); err != nil {
    2749           0 :                 d.opts.Logger.Errorf("metrics error: %s", err)
    2750           0 :         }
    2751             : 
    2752           1 :         d.mu.Unlock()
    2753           1 :         writer, err := d.mu.log.manager.Create(wal.NumWAL(newLogNum), jobID)
    2754           1 :         if err != nil {
    2755           0 :                 panic(err)
    2756             :         }
    2757             : 
    2758           1 :         d.mu.Lock()
    2759           1 :         d.mu.log.writer = writer
    2760           1 :         return newLogNum, prevLogSize
    2761             : }
    2762             : 
    2763           1 : func (d *DB) getEarliestUnflushedSeqNumLocked() uint64 {
    2764           1 :         seqNum := InternalKeySeqNumMax
    2765           1 :         for i := range d.mu.mem.queue {
    2766           1 :                 logSeqNum := d.mu.mem.queue[i].logSeqNum
    2767           1 :                 if seqNum > logSeqNum {
    2768           1 :                         seqNum = logSeqNum
    2769           1 :                 }
    2770             :         }
    2771           1 :         return seqNum
    2772             : }
    2773             : 
    2774           1 : func (d *DB) getInProgressCompactionInfoLocked(finishing *compaction) (rv []compactionInfo) {
    2775           1 :         for c := range d.mu.compact.inProgress {
    2776           1 :                 if len(c.flushing) == 0 && (finishing == nil || c != finishing) {
    2777           1 :                         info := compactionInfo{
    2778           1 :                                 versionEditApplied: c.versionEditApplied,
    2779           1 :                                 inputs:             c.inputs,
    2780           1 :                                 smallest:           c.smallest,
    2781           1 :                                 largest:            c.largest,
    2782           1 :                                 outputLevel:        -1,
    2783           1 :                         }
    2784           1 :                         if c.outputLevel != nil {
    2785           1 :                                 info.outputLevel = c.outputLevel.level
    2786           1 :                         }
    2787           1 :                         rv = append(rv, info)
    2788             :                 }
    2789             :         }
    2790           1 :         return
    2791             : }
    2792             : 
    2793           1 : func inProgressL0Compactions(inProgress []compactionInfo) []manifest.L0Compaction {
    2794           1 :         var compactions []manifest.L0Compaction
    2795           1 :         for _, info := range inProgress {
    2796           1 :                 // Skip in-progress compactions that have already committed; the L0
    2797           1 :                 // sublevels initialization code requires the set of in-progress
    2798           1 :                 // compactions to be consistent with the current version. Compactions
    2799           1 :                 // with versionEditApplied=true are already applied to the current
    2800           1 :                 // version and but are performing cleanup without the database mutex.
    2801           1 :                 if info.versionEditApplied {
    2802           1 :                         continue
    2803             :                 }
    2804           1 :                 l0 := false
    2805           1 :                 for _, cl := range info.inputs {
    2806           1 :                         l0 = l0 || cl.level == 0
    2807           1 :                 }
    2808           1 :                 if !l0 {
    2809           1 :                         continue
    2810             :                 }
    2811           1 :                 compactions = append(compactions, manifest.L0Compaction{
    2812           1 :                         Smallest:  info.smallest,
    2813           1 :                         Largest:   info.largest,
    2814           1 :                         IsIntraL0: info.outputLevel == 0,
    2815           1 :                 })
    2816             :         }
    2817           1 :         return compactions
    2818             : }
    2819             : 
    2820             : // firstError returns the first non-nil error of err0 and err1, or nil if both
    2821             : // are nil.
    2822           1 : func firstError(err0, err1 error) error {
    2823           1 :         if err0 != nil {
    2824           1 :                 return err0
    2825           1 :         }
    2826           1 :         return err1
    2827             : }
    2828             : 
    2829             : // SetCreatorID sets the CreatorID which is needed in order to use shared objects.
    2830             : // Remote object usage is disabled until this method is called the first time.
    2831             : // Once set, the Creator ID is persisted and cannot change.
    2832             : //
    2833             : // Does nothing if SharedStorage was not set in the options when the DB was
    2834             : // opened or if the DB is in read-only mode.
    2835           1 : func (d *DB) SetCreatorID(creatorID uint64) error {
    2836           1 :         if d.opts.Experimental.RemoteStorage == nil || d.opts.ReadOnly {
    2837           0 :                 return nil
    2838           0 :         }
    2839           1 :         return d.objProvider.SetCreatorID(objstorage.CreatorID(creatorID))
    2840             : }
    2841             : 
    2842             : // KeyStatistics keeps track of the number of keys that have been pinned by a
    2843             : // snapshot as well as counts of the different key kinds in the lsm.
    2844             : //
    2845             : // One way of using the accumulated stats, when we only have sets and dels,
    2846             : // and say the counts are represented as del_count, set_count,
    2847             : // del_latest_count, set_latest_count, snapshot_pinned_count.
    2848             : //
    2849             : //   - del_latest_count + set_latest_count is the set of unique user keys
    2850             : //     (unique).
    2851             : //
    2852             : //   - set_latest_count is the set of live unique user keys (live_unique).
    2853             : //
    2854             : //   - Garbage is del_count + set_count - live_unique.
    2855             : //
    2856             : //   - If everything were in the LSM, del_count+set_count-snapshot_pinned_count
    2857             : //     would also be the set of unique user keys (note that
    2858             : //     snapshot_pinned_count is counting something different -- see comment below).
    2859             : //     But snapshot_pinned_count only counts keys in the LSM so the excess here
    2860             : //     must be keys in memtables.
    2861             : type KeyStatistics struct {
    2862             :         // TODO(sumeer): the SnapshotPinned* are incorrect in that these older
    2863             :         // versions can be in a different level. Either fix the accounting or
    2864             :         // rename these fields.
    2865             : 
    2866             :         // SnapshotPinnedKeys represents obsolete keys that cannot be elided during
    2867             :         // a compaction, because they are required by an open snapshot.
    2868             :         SnapshotPinnedKeys int
    2869             :         // SnapshotPinnedKeysBytes is the total number of bytes of all snapshot
    2870             :         // pinned keys.
    2871             :         SnapshotPinnedKeysBytes uint64
    2872             :         // KindsCount is the count for each kind of key. It includes point keys,
    2873             :         // range deletes and range keys.
    2874             :         KindsCount [InternalKeyKindMax + 1]int
    2875             :         // LatestKindsCount is the count for each kind of key when it is the latest
    2876             :         // kind for a user key. It is only populated for point keys.
    2877             :         LatestKindsCount [InternalKeyKindMax + 1]int
    2878             : }
    2879             : 
    2880             : // LSMKeyStatistics is used by DB.ScanStatistics.
    2881             : type LSMKeyStatistics struct {
    2882             :         Accumulated KeyStatistics
    2883             :         // Levels contains statistics only for point keys. Range deletions and range keys will
    2884             :         // appear in Accumulated but not Levels.
    2885             :         Levels [numLevels]KeyStatistics
    2886             :         // BytesRead represents the logical, pre-compression size of keys and values read
    2887             :         BytesRead uint64
    2888             : }
    2889             : 
    2890             : // ScanStatisticsOptions is used by DB.ScanStatistics.
    2891             : type ScanStatisticsOptions struct {
    2892             :         // LimitBytesPerSecond indicates the number of bytes that are able to be read
    2893             :         // per second using ScanInternal.
    2894             :         // A value of 0 indicates that there is no limit set.
    2895             :         LimitBytesPerSecond int64
    2896             : }
    2897             : 
    2898             : // ScanStatistics returns the count of different key kinds within the lsm for a
    2899             : // key span [lower, upper) as well as the number of snapshot keys.
    2900             : func (d *DB) ScanStatistics(
    2901             :         ctx context.Context, lower, upper []byte, opts ScanStatisticsOptions,
    2902           1 : ) (LSMKeyStatistics, error) {
    2903           1 :         stats := LSMKeyStatistics{}
    2904           1 :         var prevKey InternalKey
    2905           1 :         var rateLimitFunc func(key *InternalKey, val LazyValue) error
    2906           1 :         tb := tokenbucket.TokenBucket{}
    2907           1 : 
    2908           1 :         if opts.LimitBytesPerSecond != 0 {
    2909           0 :                 // Each "token" roughly corresponds to a byte that was read.
    2910           0 :                 tb.Init(tokenbucket.TokensPerSecond(opts.LimitBytesPerSecond), tokenbucket.Tokens(1024))
    2911           0 :                 rateLimitFunc = func(key *InternalKey, val LazyValue) error {
    2912           0 :                         return tb.WaitCtx(ctx, tokenbucket.Tokens(key.Size()+val.Len()))
    2913           0 :                 }
    2914             :         }
    2915             : 
    2916           1 :         scanInternalOpts := &scanInternalOptions{
    2917           1 :                 visitPointKey: func(key *InternalKey, value LazyValue, iterInfo IteratorLevel) error {
    2918           1 :                         // If the previous key is equal to the current point key, the current key was
    2919           1 :                         // pinned by a snapshot.
    2920           1 :                         size := uint64(key.Size())
    2921           1 :                         kind := key.Kind()
    2922           1 :                         sameKey := d.equal(prevKey.UserKey, key.UserKey)
    2923           1 :                         if iterInfo.Kind == IteratorLevelLSM && sameKey {
    2924           1 :                                 stats.Levels[iterInfo.Level].SnapshotPinnedKeys++
    2925           1 :                                 stats.Levels[iterInfo.Level].SnapshotPinnedKeysBytes += size
    2926           1 :                                 stats.Accumulated.SnapshotPinnedKeys++
    2927           1 :                                 stats.Accumulated.SnapshotPinnedKeysBytes += size
    2928           1 :                         }
    2929           1 :                         if iterInfo.Kind == IteratorLevelLSM {
    2930           1 :                                 stats.Levels[iterInfo.Level].KindsCount[kind]++
    2931           1 :                         }
    2932           1 :                         if !sameKey {
    2933           1 :                                 if iterInfo.Kind == IteratorLevelLSM {
    2934           1 :                                         stats.Levels[iterInfo.Level].LatestKindsCount[kind]++
    2935           1 :                                 }
    2936           1 :                                 stats.Accumulated.LatestKindsCount[kind]++
    2937             :                         }
    2938             : 
    2939           1 :                         stats.Accumulated.KindsCount[kind]++
    2940           1 :                         prevKey.CopyFrom(*key)
    2941           1 :                         stats.BytesRead += uint64(key.Size() + value.Len())
    2942           1 :                         return nil
    2943             :                 },
    2944           0 :                 visitRangeDel: func(start, end []byte, seqNum uint64) error {
    2945           0 :                         stats.Accumulated.KindsCount[InternalKeyKindRangeDelete]++
    2946           0 :                         stats.BytesRead += uint64(len(start) + len(end))
    2947           0 :                         return nil
    2948           0 :                 },
    2949           0 :                 visitRangeKey: func(start, end []byte, keys []rangekey.Key) error {
    2950           0 :                         stats.BytesRead += uint64(len(start) + len(end))
    2951           0 :                         for _, key := range keys {
    2952           0 :                                 stats.Accumulated.KindsCount[key.Kind()]++
    2953           0 :                                 stats.BytesRead += uint64(len(key.Value) + len(key.Suffix))
    2954           0 :                         }
    2955           0 :                         return nil
    2956             :                 },
    2957             :                 includeObsoleteKeys: true,
    2958             :                 IterOptions: IterOptions{
    2959             :                         KeyTypes:   IterKeyTypePointsAndRanges,
    2960             :                         LowerBound: lower,
    2961             :                         UpperBound: upper,
    2962             :                 },
    2963             :                 rateLimitFunc: rateLimitFunc,
    2964             :         }
    2965           1 :         iter, err := d.newInternalIter(ctx, snapshotIterOpts{}, scanInternalOpts)
    2966           1 :         if err != nil {
    2967           0 :                 return LSMKeyStatistics{}, err
    2968           0 :         }
    2969           1 :         defer iter.close()
    2970           1 : 
    2971           1 :         err = scanInternalImpl(ctx, lower, upper, iter, scanInternalOpts)
    2972           1 : 
    2973           1 :         if err != nil {
    2974           0 :                 return LSMKeyStatistics{}, err
    2975           0 :         }
    2976             : 
    2977           1 :         return stats, nil
    2978             : }
    2979             : 
    2980             : // ObjProvider returns the objstorage.Provider for this database. Meant to be
    2981             : // used for internal purposes only.
    2982           1 : func (d *DB) ObjProvider() objstorage.Provider {
    2983           1 :         return d.objProvider
    2984           1 : }
    2985             : 
    2986           1 : func (d *DB) checkVirtualBounds(m *fileMetadata) {
    2987           1 :         if !invariants.Enabled {
    2988           0 :                 return
    2989           0 :         }
    2990             : 
    2991           1 :         objMeta, err := d.objProvider.Lookup(fileTypeTable, m.FileBacking.DiskFileNum)
    2992           1 :         if err != nil {
    2993           0 :                 panic(err)
    2994             :         }
    2995           1 :         if objMeta.IsExternal() {
    2996           0 :                 // Nothing to do; bounds are expected to be loose.
    2997           0 :                 return
    2998           0 :         }
    2999             : 
    3000           1 :         iters, err := d.newIters(context.TODO(), m, nil, internalIterOpts{}, iterPointKeys|iterRangeDeletions|iterRangeKeys)
    3001           1 :         if err != nil {
    3002           0 :                 panic(errors.Wrap(err, "pebble: error creating iterators"))
    3003             :         }
    3004           1 :         defer iters.CloseAll()
    3005           1 : 
    3006           1 :         if m.HasPointKeys {
    3007           1 :                 pointIter := iters.Point()
    3008           1 :                 rangeDelIter := iters.RangeDeletion()
    3009           1 : 
    3010           1 :                 // Check that the lower bound is tight.
    3011           1 :                 pointKey, _ := pointIter.First()
    3012           1 :                 rangeDel, err := rangeDelIter.First()
    3013           1 :                 if err != nil {
    3014           0 :                         panic(err)
    3015             :                 }
    3016           1 :                 if (rangeDel == nil || d.cmp(rangeDel.SmallestKey().UserKey, m.SmallestPointKey.UserKey) != 0) &&
    3017           1 :                         (pointKey == nil || d.cmp(pointKey.UserKey, m.SmallestPointKey.UserKey) != 0) {
    3018           0 :                         panic(errors.Newf("pebble: virtual sstable %s lower point key bound is not tight", m.FileNum))
    3019             :                 }
    3020             : 
    3021             :                 // Check that the upper bound is tight.
    3022           1 :                 pointKey, _ = pointIter.Last()
    3023           1 :                 rangeDel, err = rangeDelIter.Last()
    3024           1 :                 if err != nil {
    3025           0 :                         panic(err)
    3026             :                 }
    3027           1 :                 if (rangeDel == nil || d.cmp(rangeDel.LargestKey().UserKey, m.LargestPointKey.UserKey) != 0) &&
    3028           1 :                         (pointKey == nil || d.cmp(pointKey.UserKey, m.LargestPointKey.UserKey) != 0) {
    3029           0 :                         panic(errors.Newf("pebble: virtual sstable %s upper point key bound is not tight", m.FileNum))
    3030             :                 }
    3031             : 
    3032             :                 // Check that iterator keys are within bounds.
    3033           1 :                 for key, _ := pointIter.First(); key != nil; key, _ = pointIter.Next() {
    3034           1 :                         if d.cmp(key.UserKey, m.SmallestPointKey.UserKey) < 0 || d.cmp(key.UserKey, m.LargestPointKey.UserKey) > 0 {
    3035           0 :                                 panic(errors.Newf("pebble: virtual sstable %s point key %s is not within bounds", m.FileNum, key.UserKey))
    3036             :                         }
    3037             :                 }
    3038           1 :                 s, err := rangeDelIter.First()
    3039           1 :                 for ; s != nil; s, err = rangeDelIter.Next() {
    3040           1 :                         if d.cmp(s.SmallestKey().UserKey, m.SmallestPointKey.UserKey) < 0 {
    3041           0 :                                 panic(errors.Newf("pebble: virtual sstable %s point key %s is not within bounds", m.FileNum, s.SmallestKey().UserKey))
    3042             :                         }
    3043           1 :                         if d.cmp(s.LargestKey().UserKey, m.LargestPointKey.UserKey) > 0 {
    3044           0 :                                 panic(errors.Newf("pebble: virtual sstable %s point key %s is not within bounds", m.FileNum, s.LargestKey().UserKey))
    3045             :                         }
    3046             :                 }
    3047           1 :                 if err != nil {
    3048           0 :                         panic(err)
    3049             :                 }
    3050             :         }
    3051             : 
    3052           1 :         if !m.HasRangeKeys {
    3053           1 :                 return
    3054           1 :         }
    3055           0 :         rangeKeyIter := iters.RangeKey()
    3056           0 : 
    3057           0 :         // Check that the lower bound is tight.
    3058           0 :         if s, err := rangeKeyIter.First(); err != nil {
    3059           0 :                 panic(err)
    3060           0 :         } else if d.cmp(s.SmallestKey().UserKey, m.SmallestRangeKey.UserKey) != 0 {
    3061           0 :                 panic(errors.Newf("pebble: virtual sstable %s lower range key bound is not tight", m.FileNum))
    3062             :         }
    3063             : 
    3064             :         // Check that upper bound is tight.
    3065           0 :         if s, err := rangeKeyIter.Last(); err != nil {
    3066           0 :                 panic(err)
    3067           0 :         } else if d.cmp(s.LargestKey().UserKey, m.LargestRangeKey.UserKey) != 0 {
    3068           0 :                 panic(errors.Newf("pebble: virtual sstable %s upper range key bound is not tight", m.FileNum))
    3069             :         }
    3070             : 
    3071           0 :         s, err := rangeKeyIter.First()
    3072           0 :         for ; s != nil; s, err = rangeKeyIter.Next() {
    3073           0 :                 if d.cmp(s.SmallestKey().UserKey, m.SmallestRangeKey.UserKey) < 0 {
    3074           0 :                         panic(errors.Newf("pebble: virtual sstable %s point key %s is not within bounds", m.FileNum, s.SmallestKey().UserKey))
    3075             :                 }
    3076           0 :                 if d.cmp(s.LargestKey().UserKey, m.LargestRangeKey.UserKey) > 0 {
    3077           0 :                         panic(errors.Newf("pebble: virtual sstable %s point key %s is not within bounds", m.FileNum, s.LargestKey().UserKey))
    3078             :                 }
    3079             :         }
    3080           0 :         if err != nil {
    3081           0 :                 panic(err)
    3082             :         }
    3083             : }
    3084             : 
    3085             : // DebugString returns a debugging string describing the LSM.
    3086           0 : func (d *DB) DebugString() string {
    3087           0 :         d.mu.Lock()
    3088           0 :         defer d.mu.Unlock()
    3089           0 :         return d.mu.versions.currentVersion().DebugString()
    3090           0 : }

Generated by: LCOV version 1.14