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