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