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