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