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