Line data Source code
1 : // Copyright 2011 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
6 :
7 : import (
8 : "bytes"
9 : "fmt"
10 : "io"
11 : "regexp"
12 : "runtime"
13 : "slices"
14 : "sort"
15 : "strconv"
16 : "strings"
17 : "time"
18 : "unicode"
19 :
20 : "github.com/cockroachdb/crlib/fifo"
21 : "github.com/cockroachdb/errors"
22 : "github.com/cockroachdb/pebble/internal/base"
23 : "github.com/cockroachdb/pebble/internal/cache"
24 : "github.com/cockroachdb/pebble/internal/humanize"
25 : "github.com/cockroachdb/pebble/internal/keyspan"
26 : "github.com/cockroachdb/pebble/internal/manifest"
27 : "github.com/cockroachdb/pebble/internal/testkeys"
28 : "github.com/cockroachdb/pebble/objstorage/objstorageprovider"
29 : "github.com/cockroachdb/pebble/objstorage/remote"
30 : "github.com/cockroachdb/pebble/rangekey"
31 : "github.com/cockroachdb/pebble/sstable"
32 : "github.com/cockroachdb/pebble/sstable/blob"
33 : "github.com/cockroachdb/pebble/sstable/block"
34 : "github.com/cockroachdb/pebble/sstable/colblk"
35 : "github.com/cockroachdb/pebble/vfs"
36 : "github.com/cockroachdb/pebble/wal"
37 : "github.com/cockroachdb/redact"
38 : )
39 :
40 : const (
41 : cacheDefaultSize = 8 << 20 // 8 MB
42 : defaultLevelMultiplier = 10
43 : )
44 :
45 : // FilterType exports the base.FilterType type.
46 : type FilterType = base.FilterType
47 :
48 : // Exported TableFilter constants.
49 : const (
50 : TableFilter = base.TableFilter
51 : )
52 :
53 : // FilterWriter exports the base.FilterWriter type.
54 : type FilterWriter = base.FilterWriter
55 :
56 : // FilterPolicy exports the base.FilterPolicy type.
57 : type FilterPolicy = base.FilterPolicy
58 :
59 : var NoFilterPolicy = base.NoFilterPolicy
60 :
61 : // KeySchema exports the colblk.KeySchema type.
62 : type KeySchema = colblk.KeySchema
63 :
64 : // BlockPropertyCollector exports the sstable.BlockPropertyCollector type.
65 : type BlockPropertyCollector = sstable.BlockPropertyCollector
66 :
67 : // BlockPropertyFilter exports the sstable.BlockPropertyFilter type.
68 : type BlockPropertyFilter = base.BlockPropertyFilter
69 :
70 : // ShortAttributeExtractor exports the base.ShortAttributeExtractor type.
71 : type ShortAttributeExtractor = base.ShortAttributeExtractor
72 :
73 : // UserKeyPrefixBound exports the sstable.UserKeyPrefixBound type.
74 : type UserKeyPrefixBound = sstable.UserKeyPrefixBound
75 :
76 : // IterKeyType configures which types of keys an iterator should surface.
77 : type IterKeyType int8
78 :
79 : // DirLock represents a file lock on a directory. It may be passed to Open through
80 : // Options.Lock to elide lock aquisition during Open.
81 : type DirLock = base.DirLock
82 :
83 : // LockDirectory acquires the directory lock in the named directory, preventing
84 : // another process from opening the database. LockDirectory returns a
85 : // handle to the held lock that may be passed to Open, skipping lock acquisition
86 : // during Open.
87 : //
88 : // LockDirectory may be used to expand the critical section protected by the
89 : // database lock to include setup before the call to Open.
90 0 : func LockDirectory(dirname string, fs vfs.FS) (*DirLock, error) {
91 0 : return base.LockDirectory(dirname, fs)
92 0 : }
93 :
94 : const (
95 : // IterKeyTypePointsOnly configures an iterator to iterate over point keys
96 : // only.
97 : IterKeyTypePointsOnly IterKeyType = iota
98 : // IterKeyTypeRangesOnly configures an iterator to iterate over range keys
99 : // only.
100 : IterKeyTypeRangesOnly
101 : // IterKeyTypePointsAndRanges configures an iterator iterate over both point
102 : // keys and range keys simultaneously.
103 : IterKeyTypePointsAndRanges
104 : )
105 :
106 : // String implements fmt.Stringer.
107 1 : func (t IterKeyType) String() string {
108 1 : switch t {
109 1 : case IterKeyTypePointsOnly:
110 1 : return "points-only"
111 1 : case IterKeyTypeRangesOnly:
112 1 : return "ranges-only"
113 1 : case IterKeyTypePointsAndRanges:
114 1 : return "points-and-ranges"
115 0 : default:
116 0 : panic(fmt.Sprintf("unknown key type %d", t))
117 : }
118 : }
119 :
120 : // IterOptions hold the optional per-query parameters for NewIter.
121 : //
122 : // Like Options, a nil *IterOptions is valid and means to use the default
123 : // values.
124 : type IterOptions struct {
125 : // LowerBound specifies the smallest key (inclusive) that the iterator will
126 : // return during iteration. If the iterator is seeked or iterated past this
127 : // boundary the iterator will return Valid()==false. Setting LowerBound
128 : // effectively truncates the key space visible to the iterator.
129 : LowerBound []byte
130 : // UpperBound specifies the largest key (exclusive) that the iterator will
131 : // return during iteration. If the iterator is seeked or iterated past this
132 : // boundary the iterator will return Valid()==false. Setting UpperBound
133 : // effectively truncates the key space visible to the iterator.
134 : UpperBound []byte
135 : // SkipPoint may be used to skip over point keys that don't match an
136 : // arbitrary predicate during iteration. If set, the Iterator invokes
137 : // SkipPoint for keys encountered. If SkipPoint returns true, the iterator
138 : // will skip the key without yielding it to the iterator operation in
139 : // progress.
140 : //
141 : // SkipPoint must be a pure function and always return the same result when
142 : // provided the same arguments. The iterator may call SkipPoint multiple
143 : // times for the same user key.
144 : SkipPoint func(userKey []byte) bool
145 : // PointKeyFilters can be used to avoid scanning tables and blocks in tables
146 : // when iterating over point keys. This slice represents an intersection
147 : // across all filters, i.e., all filters must indicate that the block is
148 : // relevant.
149 : //
150 : // Performance note: When len(PointKeyFilters) > 0, the caller should ensure
151 : // that cap(PointKeyFilters) is at least len(PointKeyFilters)+1. This helps
152 : // avoid allocations in Pebble internal code that mutates the slice.
153 : PointKeyFilters []BlockPropertyFilter
154 : // RangeKeyFilters can be usefd to avoid scanning tables and blocks in tables
155 : // when iterating over range keys. The same requirements that apply to
156 : // PointKeyFilters apply here too.
157 : RangeKeyFilters []BlockPropertyFilter
158 : // KeyTypes configures which types of keys to iterate over: point keys,
159 : // range keys, or both.
160 : KeyTypes IterKeyType
161 : // RangeKeyMasking can be used to enable automatic masking of point keys by
162 : // range keys. Range key masking is only supported during combined range key
163 : // and point key iteration mode (IterKeyTypePointsAndRanges).
164 : RangeKeyMasking RangeKeyMasking
165 :
166 : // OnlyReadGuaranteedDurable is an advanced option that is only supported by
167 : // the Reader implemented by DB. When set to true, only the guaranteed to be
168 : // durable state is visible in the iterator.
169 : // - This definition is made under the assumption that the FS implementation
170 : // is providing a durability guarantee when data is synced.
171 : // - The visible state represents a consistent point in the history of the
172 : // DB.
173 : // - The implementation is free to choose a conservative definition of what
174 : // is guaranteed durable. For simplicity, the current implementation
175 : // ignores memtables. A more sophisticated implementation could track the
176 : // highest seqnum that is synced to the WAL and published and use that as
177 : // the visible seqnum for an iterator. Note that the latter approach is
178 : // not strictly better than the former since we can have DBs that are (a)
179 : // synced more rarely than memtable flushes, (b) have no WAL. (a) is
180 : // likely to be true in a future CockroachDB context where the DB
181 : // containing the state machine may be rarely synced.
182 : // NB: this current implementation relies on the fact that memtables are
183 : // flushed in seqnum order, and any ingested sstables that happen to have a
184 : // lower seqnum than a non-flushed memtable don't have any overlapping keys.
185 : // This is the fundamental level invariant used in other code too, like when
186 : // merging iterators.
187 : //
188 : // Semantically, using this option provides the caller a "snapshot" as of
189 : // the time the most recent memtable was flushed. An alternate interface
190 : // would be to add a NewSnapshot variant. Creating a snapshot is heavier
191 : // weight than creating an iterator, so we have opted to support this
192 : // iterator option.
193 : OnlyReadGuaranteedDurable bool
194 : // UseL6Filters allows the caller to opt into reading filter blocks for L6
195 : // sstables. Helpful if a lot of SeekPrefixGEs are expected in quick
196 : // succession, that are also likely to not yield a single key. Filter blocks in
197 : // L6 can be relatively large, often larger than data blocks, so the benefit of
198 : // loading them in the cache is minimized if the probability of the key
199 : // existing is not low or if we just expect a one-time Seek (where loading the
200 : // data block directly is better).
201 : UseL6Filters bool
202 : // Category is used for categorized iterator stats. This should not be
203 : // changed by calling SetOptions.
204 : Category block.Category
205 :
206 : DebugRangeKeyStack bool
207 :
208 : // Internal options.
209 :
210 : logger Logger
211 : // Layer corresponding to this file. Only passed in if constructed by a
212 : // levelIter.
213 : layer manifest.Layer
214 : // disableLazyCombinedIteration is an internal testing option.
215 : disableLazyCombinedIteration bool
216 : // snapshotForHideObsoletePoints is specified for/by levelIter when opening
217 : // files and is used to decide whether to hide obsolete points. A value of 0
218 : // implies obsolete points should not be hidden.
219 : snapshotForHideObsoletePoints base.SeqNum
220 :
221 : // NB: If adding new Options, you must account for them in iterator
222 : // construction and Iterator.SetOptions.
223 : }
224 :
225 : // GetLowerBound returns the LowerBound or nil if the receiver is nil.
226 2 : func (o *IterOptions) GetLowerBound() []byte {
227 2 : if o == nil {
228 2 : return nil
229 2 : }
230 2 : return o.LowerBound
231 : }
232 :
233 : // GetUpperBound returns the UpperBound or nil if the receiver is nil.
234 2 : func (o *IterOptions) GetUpperBound() []byte {
235 2 : if o == nil {
236 2 : return nil
237 2 : }
238 2 : return o.UpperBound
239 : }
240 :
241 2 : func (o *IterOptions) pointKeys() bool {
242 2 : if o == nil {
243 0 : return true
244 0 : }
245 2 : return o.KeyTypes == IterKeyTypePointsOnly || o.KeyTypes == IterKeyTypePointsAndRanges
246 : }
247 :
248 2 : func (o *IterOptions) rangeKeys() bool {
249 2 : if o == nil {
250 0 : return false
251 0 : }
252 2 : return o.KeyTypes == IterKeyTypeRangesOnly || o.KeyTypes == IterKeyTypePointsAndRanges
253 : }
254 :
255 2 : func (o *IterOptions) getLogger() Logger {
256 2 : if o == nil || o.logger == nil {
257 2 : return DefaultLogger
258 2 : }
259 2 : return o.logger
260 : }
261 :
262 : // SpanIterOptions creates a SpanIterOptions from this IterOptions.
263 2 : func (o *IterOptions) SpanIterOptions() keyspan.SpanIterOptions {
264 2 : if o == nil {
265 2 : return keyspan.SpanIterOptions{}
266 2 : }
267 2 : return keyspan.SpanIterOptions{
268 2 : RangeKeyFilters: o.RangeKeyFilters,
269 2 : }
270 : }
271 :
272 : // ScanInternalOptions is similar to IterOptions, meant for use with
273 : // scanInternalIterator.
274 : type ScanInternalOptions struct {
275 : IterOptions
276 :
277 : Category block.Category
278 :
279 : VisitPointKey func(key *InternalKey, value LazyValue, iterInfo IteratorLevel) error
280 : VisitRangeDel func(start, end []byte, seqNum SeqNum) error
281 : VisitRangeKey func(start, end []byte, keys []rangekey.Key) error
282 : VisitSharedFile func(sst *SharedSSTMeta) error
283 : VisitExternalFile func(sst *ExternalFile) error
284 :
285 : // IncludeObsoleteKeys specifies whether keys shadowed by newer internal keys
286 : // are exposed. If false, only one internal key per user key is exposed.
287 : IncludeObsoleteKeys bool
288 :
289 : // RateLimitFunc is used to limit the amount of bytes read per second.
290 : RateLimitFunc func(key *InternalKey, value LazyValue) error
291 : }
292 :
293 : // RangeKeyMasking configures automatic hiding of point keys by range keys. A
294 : // non-nil Suffix enables range-key masking. When enabled, range keys with
295 : // suffixes ≥ Suffix behave as masks. All point keys that are contained within a
296 : // masking range key's bounds and have suffixes greater than the range key's
297 : // suffix are automatically skipped.
298 : //
299 : // Specifically, when configured with a RangeKeyMasking.Suffix _s_, and there
300 : // exists a range key with suffix _r_ covering a point key with suffix _p_, and
301 : //
302 : // _s_ ≤ _r_ < _p_
303 : //
304 : // then the point key is elided.
305 : //
306 : // Range-key masking may only be used when iterating over both point keys and
307 : // range keys with IterKeyTypePointsAndRanges.
308 : type RangeKeyMasking struct {
309 : // Suffix configures which range keys may mask point keys. Only range keys
310 : // that are defined at suffixes greater than or equal to Suffix will mask
311 : // point keys.
312 : Suffix []byte
313 : // Filter is an optional field that may be used to improve performance of
314 : // range-key masking through a block-property filter defined over key
315 : // suffixes. If non-nil, Filter is called by Pebble to construct a
316 : // block-property filter mask at iterator creation. The filter is used to
317 : // skip whole point-key blocks containing point keys with suffixes greater
318 : // than a covering range-key's suffix.
319 : //
320 : // To use this functionality, the caller must create and configure (through
321 : // Options.BlockPropertyCollectors) a block-property collector that records
322 : // the maxmimum suffix contained within a block. The caller then must write
323 : // and provide a BlockPropertyFilterMask implementation on that same
324 : // property. See the BlockPropertyFilterMask type for more information.
325 : Filter func() BlockPropertyFilterMask
326 : }
327 :
328 : // BlockPropertyFilterMask extends the BlockPropertyFilter interface for use
329 : // with range-key masking. Unlike an ordinary block property filter, a
330 : // BlockPropertyFilterMask's filtering criteria is allowed to change when Pebble
331 : // invokes its SetSuffix method.
332 : //
333 : // When a Pebble iterator steps into a range key's bounds and the range key has
334 : // a suffix greater than or equal to RangeKeyMasking.Suffix, the range key acts
335 : // as a mask. The masking range key hides all point keys that fall within the
336 : // range key's bounds and have suffixes > the range key's suffix. Without a
337 : // filter mask configured, Pebble performs this hiding by stepping through point
338 : // keys and comparing suffixes. If large numbers of point keys are masked, this
339 : // requires Pebble to load, iterate through and discard a large number of
340 : // sstable blocks containing masked point keys.
341 : //
342 : // If a block-property collector and a filter mask are configured, Pebble may
343 : // skip loading some point-key blocks altogether. If a block's keys are known to
344 : // all fall within the bounds of the masking range key and the block was
345 : // annotated by a block-property collector with the maximal suffix, Pebble can
346 : // ask the filter mask to compare the property to the current masking range
347 : // key's suffix. If the mask reports no intersection, the block may be skipped.
348 : //
349 : // If unsuffixed and suffixed keys are written to the database, care must be
350 : // taken to avoid unintentionally masking un-suffixed keys located in the same
351 : // block as suffixed keys. One solution is to interpret unsuffixed keys as
352 : // containing the maximal suffix value, ensuring that blocks containing
353 : // unsuffixed keys are always loaded.
354 : type BlockPropertyFilterMask interface {
355 : BlockPropertyFilter
356 :
357 : // SetSuffix configures the mask with the suffix of a range key. The filter
358 : // should return false from Intersects whenever it's provided with a
359 : // property encoding a block's minimum suffix that's greater (according to
360 : // Compare) than the provided suffix.
361 : SetSuffix(suffix []byte) error
362 : }
363 :
364 : // WriteOptions hold the optional per-query parameters for Set and Delete
365 : // operations.
366 : //
367 : // Like Options, a nil *WriteOptions is valid and means to use the default
368 : // values.
369 : type WriteOptions struct {
370 : // Sync is whether to sync writes through the OS buffer cache and down onto
371 : // the actual disk, if applicable. Setting Sync is required for durability of
372 : // individual write operations but can result in slower writes.
373 : //
374 : // If false, and the process or machine crashes, then a recent write may be
375 : // lost. This is due to the recently written data being buffered inside the
376 : // process running Pebble. This differs from the semantics of a write system
377 : // call in which the data is buffered in the OS buffer cache and would thus
378 : // survive a process crash.
379 : //
380 : // The default value is true.
381 : Sync bool
382 : }
383 :
384 : // Sync specifies the default write options for writes which synchronize to
385 : // disk.
386 : var Sync = &WriteOptions{Sync: true}
387 :
388 : // NoSync specifies the default write options for writes which do not
389 : // synchronize to disk.
390 : var NoSync = &WriteOptions{Sync: false}
391 :
392 : // GetSync returns the Sync value or true if the receiver is nil.
393 2 : func (o *WriteOptions) GetSync() bool {
394 2 : return o == nil || o.Sync
395 2 : }
396 :
397 : // LevelOptions holds the optional per-level parameters.
398 : type LevelOptions struct {
399 : // BlockRestartInterval is the number of keys between restart points
400 : // for delta encoding of keys.
401 : //
402 : // The default value is 16 for L0, and the value from the previous level for
403 : // all other levels.
404 : BlockRestartInterval int
405 :
406 : // BlockSize is the target uncompressed size in bytes of each table block.
407 : //
408 : // The default value is 4096 for L0, and the value from the previous level for
409 : // all other levels.
410 : BlockSize int
411 :
412 : // BlockSizeThreshold finishes a block if the block size is larger than the
413 : // specified percentage of the target block size and adding the next entry
414 : // would cause the block to be larger than the target block size.
415 : //
416 : // The default value is 90 for L0, and the value from the previous level for
417 : // all other levels.
418 : BlockSizeThreshold int
419 :
420 : // Compression defines the per-block compression to use.
421 : //
422 : // The default value is Snappy for L0, or the function from the previous level
423 : // for all other levels.
424 : //
425 : // ApplyCompressionSettings can be used to initialize this field for all levels.
426 : Compression func() *sstable.CompressionProfile
427 :
428 : // FilterPolicy defines a filter algorithm (such as a Bloom filter) that can
429 : // reduce disk reads for Get calls.
430 : //
431 : // One such implementation is bloom.FilterPolicy(10) from the pebble/bloom
432 : // package.
433 : //
434 : // The default value for L0 is NoFilterPolicy (no filter), and the value from
435 : // the previous level for all other levels.
436 : FilterPolicy FilterPolicy
437 :
438 : // FilterType is a legacy field. The default and only possible value is
439 : // TableFilter.
440 : FilterType FilterType
441 :
442 : // IndexBlockSize is the target uncompressed size in bytes of each index
443 : // block. When the index block size is larger than this target, two-level
444 : // indexes are automatically enabled. Setting this option to a large value
445 : // (such as math.MaxInt32) disables the automatic creation of two-level
446 : // indexes.
447 : //
448 : // The default value is the value of BlockSize for L0, or the value from the
449 : // previous level for all other levels.
450 : IndexBlockSize int
451 : }
452 :
453 : // EnsureL0Defaults ensures that the L0 default values for the options have been
454 : // initialized.
455 2 : func (o *LevelOptions) EnsureL0Defaults() {
456 2 : if o.BlockRestartInterval <= 0 {
457 1 : o.BlockRestartInterval = base.DefaultBlockRestartInterval
458 1 : }
459 2 : if o.BlockSize <= 0 {
460 1 : o.BlockSize = base.DefaultBlockSize
461 2 : } else if o.BlockSize > sstable.MaximumRestartOffset {
462 0 : panic(errors.Errorf("BlockSize %d exceeds MaximumRestartOffset", o.BlockSize))
463 : }
464 2 : if o.BlockSizeThreshold <= 0 {
465 1 : o.BlockSizeThreshold = base.DefaultBlockSizeThreshold
466 1 : }
467 2 : if o.Compression == nil {
468 1 : o.Compression = func() *sstable.CompressionProfile { return sstable.SnappyCompression }
469 : }
470 2 : if o.FilterPolicy == nil {
471 1 : o.FilterPolicy = NoFilterPolicy
472 1 : }
473 2 : if o.IndexBlockSize <= 0 {
474 1 : o.IndexBlockSize = o.BlockSize
475 1 : }
476 : }
477 :
478 : // EnsureL1PlusDefaults ensures that the L1+ default values for the options have
479 : // been initialized. Requires the fully initialized options for the level above.
480 2 : func (o *LevelOptions) EnsureL1PlusDefaults(previousLevel *LevelOptions) {
481 2 : if o.BlockRestartInterval <= 0 {
482 1 : o.BlockRestartInterval = previousLevel.BlockRestartInterval
483 1 : }
484 2 : if o.BlockSize <= 0 {
485 1 : o.BlockSize = previousLevel.BlockSize
486 2 : } else if o.BlockSize > sstable.MaximumRestartOffset {
487 0 : panic(errors.Errorf("BlockSize %d exceeds MaximumRestartOffset", o.BlockSize))
488 : }
489 2 : if o.BlockSizeThreshold <= 0 {
490 1 : o.BlockSizeThreshold = previousLevel.BlockSizeThreshold
491 1 : }
492 2 : if o.Compression == nil {
493 1 : o.Compression = previousLevel.Compression
494 1 : }
495 2 : if o.FilterPolicy == nil {
496 1 : o.FilterPolicy = previousLevel.FilterPolicy
497 1 : }
498 2 : if o.IndexBlockSize <= 0 {
499 1 : o.IndexBlockSize = previousLevel.IndexBlockSize
500 1 : }
501 : }
502 :
503 : // Options holds the optional parameters for configuring pebble. These options
504 : // apply to the DB at large; per-query options are defined by the IterOptions
505 : // and WriteOptions types.
506 : type Options struct {
507 : // Sync sstables periodically in order to smooth out writes to disk. This
508 : // option does not provide any persistency guarantee, but is used to avoid
509 : // latency spikes if the OS automatically decides to write out a large chunk
510 : // of dirty filesystem buffers. This option only controls SSTable syncs; WAL
511 : // syncs are controlled by WALBytesPerSync.
512 : //
513 : // The default value is 512KB.
514 : BytesPerSync int
515 :
516 : // Cache is used to cache uncompressed blocks from sstables. If it is nil,
517 : // a block cache of CacheSize will be created for each DB.
518 : Cache *cache.Cache
519 : // CacheSize is used when Cache is not set. The default value is 8 MB.
520 : CacheSize int64
521 :
522 : // LoadBlockSema, if set, is used to limit the number of blocks that can be
523 : // loaded (i.e. read from the filesystem) in parallel. Each load acquires one
524 : // unit from the semaphore for the duration of the read.
525 : LoadBlockSema *fifo.Semaphore
526 :
527 : // Cleaner cleans obsolete files.
528 : //
529 : // The default cleaner uses the DeleteCleaner.
530 : Cleaner Cleaner
531 :
532 : // Local contains option that pertain to files stored on the local filesystem.
533 : Local struct {
534 : // ReadaheadConfig is used to retrieve the current readahead mode; it is
535 : // consulted whenever a read handle is initialized.
536 : ReadaheadConfig *ReadaheadConfig
537 :
538 : // TODO(radu): move BytesPerSync, LoadBlockSema, Cleaner here.
539 : }
540 :
541 : // Comparer defines a total ordering over the space of []byte keys: a 'less
542 : // than' relationship. The same comparison algorithm must be used for reads
543 : // and writes over the lifetime of the DB.
544 : //
545 : // The default value uses the same ordering as bytes.Compare.
546 : Comparer *Comparer
547 :
548 : // DebugCheck is invoked, if non-nil, whenever a new version is being
549 : // installed. Typically, this is set to pebble.DebugCheckLevels in tests
550 : // or tools only, to check invariants over all the data in the database.
551 : DebugCheck func(*DB) error
552 :
553 : // Disable the write-ahead log (WAL). Disabling the write-ahead log prohibits
554 : // crash recovery, but can improve performance if crash recovery is not
555 : // needed (e.g. when only temporary state is being stored in the database).
556 : //
557 : // TODO(peter): untested
558 : DisableWAL bool
559 :
560 : // ErrorIfExists causes an error on Open if the database already exists.
561 : // The error can be checked with errors.Is(err, ErrDBAlreadyExists).
562 : //
563 : // The default value is false.
564 : ErrorIfExists bool
565 :
566 : // ErrorIfNotExists causes an error on Open if the database does not already
567 : // exist. The error can be checked with errors.Is(err, ErrDBDoesNotExist).
568 : //
569 : // The default value is false which will cause a database to be created if it
570 : // does not already exist.
571 : ErrorIfNotExists bool
572 :
573 : // ErrorIfNotPristine causes an error on Open if the database already exists
574 : // and any operations have been performed on the database. The error can be
575 : // checked with errors.Is(err, ErrDBNotPristine).
576 : //
577 : // Note that a database that contained keys that were all subsequently deleted
578 : // may or may not trigger the error. Currently, we check if there are any live
579 : // SSTs or log records to replay.
580 : ErrorIfNotPristine bool
581 :
582 : // EventListener provides hooks to listening to significant DB events such as
583 : // flushes, compactions, and table deletion.
584 : EventListener *EventListener
585 :
586 : // Experimental contains experimental options which are off by default.
587 : // These options are temporary and will eventually either be deleted, moved
588 : // out of the experimental group, or made the non-adjustable default. These
589 : // options may change at any time, so do not rely on them.
590 : Experimental struct {
591 : // The threshold of L0 read-amplification at which compaction concurrency
592 : // is enabled (if CompactionDebtConcurrency was not already exceeded).
593 : // Every multiple of this value enables another concurrent
594 : // compaction up to CompactionConcurrencyRange.
595 : L0CompactionConcurrency int
596 :
597 : // CompactionDebtConcurrency controls the threshold of compaction debt
598 : // at which additional compaction concurrency slots are added. For every
599 : // multiple of this value in compaction debt bytes, an additional
600 : // concurrent compaction is added. This works "on top" of
601 : // L0CompactionConcurrency, so the higher of the count of compaction
602 : // concurrency slots as determined by the two options is chosen.
603 : CompactionDebtConcurrency uint64
604 :
605 : // CompactionGarbageFractionForMaxConcurrency is the fraction of garbage
606 : // due to DELs and RANGEDELs that causes MaxConcurrentCompactions to be
607 : // allowed. Concurrent compactions are allowed in a linear manner upto
608 : // this limit being reached. A value <= 0.0 disables adding concurrency
609 : // due to garbage.
610 : CompactionGarbageFractionForMaxConcurrency func() float64
611 :
612 : // UseDeprecatedCompensatedScore is a temporary option to revert the
613 : // compaction picker to the previous behavior of only considering
614 : // compaction out of a level if its compensated fill factor divided by
615 : // the next level's fill factor is >= 1.0. The details of this setting
616 : // are documented within its use within the compaction picker.
617 : //
618 : // The default value is false.
619 : UseDeprecatedCompensatedScore func() bool
620 :
621 : // IngestSplit, if it returns true, allows for ingest-time splitting of
622 : // existing sstables into two virtual sstables to allow ingestion sstables to
623 : // slot into a lower level than they otherwise would have.
624 : IngestSplit func() bool
625 :
626 : // ReadCompactionRate controls the frequency of read triggered
627 : // compactions by adjusting `AllowedSeeks` in manifest.TableMetadata:
628 : //
629 : // AllowedSeeks = FileSize / ReadCompactionRate
630 : //
631 : // From LevelDB:
632 : // ```
633 : // We arrange to automatically compact this file after
634 : // a certain number of seeks. Let's assume:
635 : // (1) One seek costs 10ms
636 : // (2) Writing or reading 1MB costs 10ms (100MB/s)
637 : // (3) A compaction of 1MB does 25MB of IO:
638 : // 1MB read from this level
639 : // 10-12MB read from next level (boundaries may be misaligned)
640 : // 10-12MB written to next level
641 : // This implies that 25 seeks cost the same as the compaction
642 : // of 1MB of data. I.e., one seek costs approximately the
643 : // same as the compaction of 40KB of data. We are a little
644 : // conservative and allow approximately one seek for every 16KB
645 : // of data before triggering a compaction.
646 : // ```
647 : ReadCompactionRate int64
648 :
649 : // ReadSamplingMultiplier is a multiplier for the readSamplingPeriod in
650 : // iterator.maybeSampleRead() to control the frequency of read sampling
651 : // to trigger a read triggered compaction. A value of -1 prevents sampling
652 : // and disables read triggered compactions. The default is 1 << 4. which
653 : // gets multiplied with a constant of 1 << 16 to yield 1 << 20 (1MB).
654 : ReadSamplingMultiplier int64
655 :
656 : // NumDeletionsThreshold defines the minimum number of point tombstones
657 : // that must be present in a single data block for that block to be
658 : // considered tombstone-dense for the purposes of triggering a
659 : // tombstone density compaction. Data blocks may also be considered
660 : // tombstone-dense if they meet the criteria defined by
661 : // DeletionSizeRatioThreshold below. Tombstone-dense blocks are identified
662 : // when sstables are written, and so this is effectively an option for
663 : // sstable writers. The default value is 100.
664 : NumDeletionsThreshold int
665 :
666 : // DeletionSizeRatioThreshold defines the minimum ratio of the size of
667 : // point tombstones to the size of a data block that must be reached
668 : // for that block to be considered tombstone-dense for the purposes of
669 : // triggering a tombstone density compaction. Data blocks may also be
670 : // considered tombstone-dense if they meet the criteria defined by
671 : // NumDeletionsThreshold above. Tombstone-dense blocks are identified
672 : // when sstables are written, and so this is effectively an option for
673 : // sstable writers. The default value is 0.5.
674 : DeletionSizeRatioThreshold float32
675 :
676 : // TombstoneDenseCompactionThreshold is the minimum percent of data
677 : // blocks in a table that must be tombstone-dense for that table to be
678 : // eligible for a tombstone density compaction. It should be defined as a
679 : // ratio out of 1. The default value is 0.10.
680 : //
681 : // If multiple tables are eligible for a tombstone density compaction, then
682 : // tables with a higher percent of tombstone-dense blocks are still
683 : // prioritized for compaction.
684 : //
685 : // A zero or negative value disables tombstone density compactions.
686 : TombstoneDenseCompactionThreshold float64
687 :
688 : // FileCacheShards is the number of shards per file cache.
689 : // Reducing the value can reduce the number of idle goroutines per DB
690 : // instance which can be useful in scenarios with a lot of DB instances
691 : // and a large number of CPUs, but doing so can lead to higher contention
692 : // in the file cache and reduced performance.
693 : //
694 : // The default value is the number of logical CPUs, which can be
695 : // limited by runtime.GOMAXPROCS.
696 : FileCacheShards int
697 :
698 : // ValidateOnIngest schedules validation of sstables after they have
699 : // been ingested.
700 : //
701 : // By default, this value is false.
702 : ValidateOnIngest bool
703 :
704 : // LevelMultiplier configures the size multiplier used to determine the
705 : // desired size of each level of the LSM. Defaults to 10.
706 : LevelMultiplier int
707 :
708 : // MultiLevelCompactionHeuristic determines whether to add an additional
709 : // level to a conventional two level compaction.
710 : MultiLevelCompactionHeuristic func() MultiLevelHeuristic
711 :
712 : // EnableValueBlocks is used to decide whether to enable writing
713 : // TableFormatPebblev3 sstables. This setting is only respected by a
714 : // specific subset of format major versions: FormatSSTableValueBlocks,
715 : // FormatFlushableIngest and FormatPrePebblev1MarkedCompacted. In lower
716 : // format major versions, value blocks are never enabled. In higher
717 : // format major versions, value blocks are always enabled.
718 : EnableValueBlocks func() bool
719 :
720 : // ShortAttributeExtractor is used iff EnableValueBlocks() returns true
721 : // (else ignored). If non-nil, a ShortAttribute can be extracted from the
722 : // value and stored with the key, when the value is stored elsewhere.
723 : ShortAttributeExtractor ShortAttributeExtractor
724 :
725 : // DisableIngestAsFlushable disables lazy ingestion of sstables through
726 : // a WAL write and memtable rotation. Only effectual if the format
727 : // major version is at least `FormatFlushableIngest`.
728 : DisableIngestAsFlushable func() bool
729 :
730 : // RemoteStorage enables use of remote storage (e.g. S3) for storing
731 : // sstables. Setting this option enables use of CreateOnShared option and
732 : // allows ingestion of external files.
733 : RemoteStorage remote.StorageFactory
734 :
735 : // If CreateOnShared is non-zero, new sstables are created on remote storage
736 : // (using CreateOnSharedLocator and with the appropriate
737 : // CreateOnSharedStrategy). These sstables can be shared between different
738 : // Pebble instances; the lifecycle of such objects is managed by the
739 : // remote.Storage constructed by options.RemoteStorage.
740 : //
741 : // Can only be used when RemoteStorage is set (and recognizes
742 : // CreateOnSharedLocator).
743 : CreateOnShared remote.CreateOnSharedStrategy
744 : CreateOnSharedLocator remote.Locator
745 :
746 : // CacheSizeBytesBytes is the size of the on-disk block cache for objects
747 : // on shared storage in bytes. If it is 0, no cache is used.
748 : SecondaryCacheSizeBytes int64
749 :
750 : // EnableDeleteOnlyCompactionExcises enables delete-only compactions to also
751 : // apply delete-only compaction hints on sstables that partially overlap
752 : // with it. This application happens through an excise, similar to
753 : // the excise phase of IngestAndExcise.
754 : EnableDeleteOnlyCompactionExcises func() bool
755 :
756 : // CompactionScheduler, if set, is used to create a scheduler to limit
757 : // concurrent compactions as well as to pace compactions already chosen. If
758 : // nil, a default scheduler is created and used.
759 : CompactionScheduler func() CompactionScheduler
760 :
761 : UserKeyCategories UserKeyCategories
762 :
763 : // ValueSeparationPolicy controls the policy for separating values into
764 : // external blob files. If nil, value separation defaults to disabled.
765 : // The value separation policy is ignored if EnableColumnarBlocks() is
766 : // false.
767 : ValueSeparationPolicy func() ValueSeparationPolicy
768 :
769 : // SpanPolicyFunc is used to determine the SpanPolicy for a key region.
770 : SpanPolicyFunc SpanPolicyFunc
771 : }
772 :
773 : // Filters is a map from filter policy name to filter policy. It is used for
774 : // debugging tools which may be used on multiple databases configured with
775 : // different filter policies. It is not necessary to populate this filters
776 : // map during normal usage of a DB (it will be done automatically by
777 : // EnsureDefaults).
778 : Filters map[string]FilterPolicy
779 :
780 : // FlushDelayDeleteRange configures how long the database should wait before
781 : // forcing a flush of a memtable that contains a range deletion. Disk space
782 : // cannot be reclaimed until the range deletion is flushed. No automatic
783 : // flush occurs if zero.
784 : FlushDelayDeleteRange time.Duration
785 :
786 : // FlushDelayRangeKey configures how long the database should wait before
787 : // forcing a flush of a memtable that contains a range key. Range keys in
788 : // the memtable prevent lazy combined iteration, so it's desirable to flush
789 : // range keys promptly. No automatic flush occurs if zero.
790 : FlushDelayRangeKey time.Duration
791 :
792 : // FlushSplitBytes denotes the target number of bytes per sublevel in
793 : // each flush split interval (i.e. range between two flush split keys)
794 : // in L0 sstables. When set to zero, only a single sstable is generated
795 : // by each flush. When set to a non-zero value, flushes are split at
796 : // points to meet L0's TargetFileSize, any grandparent-related overlap
797 : // options, and at boundary keys of L0 flush split intervals (which are
798 : // targeted to contain around FlushSplitBytes bytes in each sublevel
799 : // between pairs of boundary keys). Splitting sstables during flush
800 : // allows increased compaction flexibility and concurrency when those
801 : // tables are compacted to lower levels.
802 : FlushSplitBytes int64
803 :
804 : // FormatMajorVersion sets the format of on-disk files. It is
805 : // recommended to set the format major version to an explicit
806 : // version, as the default may change over time.
807 : //
808 : // At Open if the existing database is formatted using a later
809 : // format major version that is known to this version of Pebble,
810 : // Pebble will continue to use the later format major version. If
811 : // the existing database's version is unknown, the caller may use
812 : // FormatMostCompatible and will be able to open the database
813 : // regardless of its actual version.
814 : //
815 : // If the existing database is formatted using a format major
816 : // version earlier than the one specified, Open will automatically
817 : // ratchet the database to the specified format major version.
818 : FormatMajorVersion FormatMajorVersion
819 :
820 : // FS provides the interface for persistent file storage.
821 : //
822 : // The default value uses the underlying operating system's file system.
823 : FS vfs.FS
824 :
825 : // KeySchema is the name of the key schema that should be used when writing
826 : // new sstables. There must be a key schema with this name defined in
827 : // KeySchemas. If not set, colblk.DefaultKeySchema is used to construct a
828 : // default key schema.
829 : KeySchema string
830 :
831 : // KeySchemas defines the set of known schemas of user keys. When columnar
832 : // blocks are in use (see FormatColumnarBlocks), the user may specify how a
833 : // key should be decomposed into columns. Each KeySchema must have a unique
834 : // name. The schema named by Options.KeySchema is used while writing
835 : // sstables during flushes and compactions.
836 : //
837 : // Multiple KeySchemas may be used over the lifetime of a database. Once a
838 : // KeySchema is used, it must be provided in KeySchemas in subsequent calls
839 : // to Open for perpetuity.
840 : KeySchemas sstable.KeySchemas
841 :
842 : // Lock, if set, must be a database lock acquired through LockDirectory for
843 : // the same directory passed to Open. If provided, Open will skip locking
844 : // the directory. Closing the database will not release the lock, and it's
845 : // the responsibility of the caller to release the lock after closing the
846 : // database.
847 : //
848 : // Open will enforce that the Lock passed locks the same directory passed to
849 : // Open. Concurrent calls to Open using the same Lock are detected and
850 : // prohibited.
851 : Lock *base.DirLock
852 :
853 : // The count of L0 files necessary to trigger an L0 compaction.
854 : L0CompactionFileThreshold int
855 :
856 : // The amount of L0 read-amplification necessary to trigger an L0 compaction.
857 : L0CompactionThreshold int
858 :
859 : // Hard limit on L0 read-amplification, computed as the number of L0
860 : // sublevels. Writes are stopped when this threshold is reached.
861 : L0StopWritesThreshold int
862 :
863 : // The maximum number of bytes for LBase. The base level is the level which
864 : // L0 is compacted into. The base level is determined dynamically based on
865 : // the existing data in the LSM. The maximum number of bytes for other levels
866 : // is computed dynamically based on the base level's maximum size. When the
867 : // maximum number of bytes for a level is exceeded, compaction is requested.
868 : LBaseMaxBytes int64
869 :
870 : // TargetFileSizes contains the target file size for each level, ignoring
871 : // unpopulated levels. Specifically:
872 : // - TargetFileSizes[0] is the target file size for L0;
873 : // - TargetFileSizes[1] is the target file size for Lbase;
874 : // - TargetFileSizes[2] is the target file size for Lbase+1;
875 : // and so on.
876 : //
877 : // The default value for TargetFileSizes[0] is 2MB.
878 : // The default value for TargetFileSizes[i] is TargetFileSizes[i-1] * 2.
879 : TargetFileSizes [manifest.NumLevels]int64
880 :
881 : // Per-level options. Levels[i] contains the options for Li (regardless of
882 : // what Lbase is).
883 : Levels [manifest.NumLevels]LevelOptions
884 :
885 : // LoggerAndTracer will be used, if non-nil, else Logger will be used and
886 : // tracing will be a noop.
887 :
888 : // Logger used to write log messages.
889 : //
890 : // The default logger uses the Go standard library log package.
891 : Logger Logger
892 : // LoggerAndTracer is used for writing log messages and traces.
893 : LoggerAndTracer LoggerAndTracer
894 :
895 : // MaxManifestFileSize is the maximum size the MANIFEST file is allowed to
896 : // become. When the MANIFEST exceeds this size it is rolled over and a new
897 : // MANIFEST is created.
898 : MaxManifestFileSize int64
899 :
900 : // MaxOpenFiles is a soft limit on the number of open files that can be
901 : // used by the DB.
902 : //
903 : // The default value is 1000.
904 : MaxOpenFiles int
905 :
906 : // The size of a MemTable in steady state. The actual MemTable size starts at
907 : // min(256KB, MemTableSize) and doubles for each subsequent MemTable up to
908 : // MemTableSize. This reduces the memory pressure caused by MemTables for
909 : // short lived (test) DB instances. Note that more than one MemTable can be
910 : // in existence since flushing a MemTable involves creating a new one and
911 : // writing the contents of the old one in the
912 : // background. MemTableStopWritesThreshold places a hard limit on the size of
913 : // the queued MemTables.
914 : //
915 : // The default value is 4MB.
916 : MemTableSize uint64
917 :
918 : // Hard limit on the number of queued of MemTables. Writes are stopped when
919 : // the sum of the queued memtable sizes exceeds:
920 : // MemTableStopWritesThreshold * MemTableSize.
921 : //
922 : // This value should be at least 2 or writes will stop whenever a MemTable is
923 : // being flushed.
924 : //
925 : // The default value is 2.
926 : MemTableStopWritesThreshold int
927 :
928 : // Merger defines the associative merge operation to use for merging values
929 : // written with {Batch,DB}.Merge.
930 : //
931 : // The default merger concatenates values.
932 : Merger *Merger
933 :
934 : // CompactionConcurrencyRange returns a [lower, upper] range for the number of
935 : // compactions Pebble runs in parallel (with the caveats below), not including
936 : // download compactions (which have a separate limit specified by
937 : // MaxConcurrentDownloads).
938 : //
939 : // The lower value is the concurrency allowed under normal circumstances.
940 : // Pebble can dynamically increase the concurrency based on heuristics (like
941 : // high read amplification or compaction debt) up to the maximum.
942 : //
943 : // The upper value is a rough upper bound since delete-only compactions (a) do
944 : // not use the CompactionScheduler, and (b) the CompactionScheduler may use
945 : // other criteria to decide on how many compactions to permit.
946 : //
947 : // Elaborating on (b), when the ConcurrencyLimitScheduler is being used, the
948 : // value returned by DB.GetAllowedWithoutPermission fully controls how many
949 : // compactions get to run. Other CompactionSchedulers may use additional
950 : // criteria, like resource availability.
951 : //
952 : // Elaborating on (a), we don't use the CompactionScheduler to schedule
953 : // delete-only compactions since they are expected to be almost free from a
954 : // CPU and disk usage perspective. Since the CompactionScheduler does not
955 : // know about their existence, the total running count can exceed this
956 : // value. For example, consider CompactionConcurrencyRange returns 3, and the
957 : // current value returned from DB.GetAllowedWithoutPermission is also 3. Say
958 : // 3 delete-only compactions are also running. Then the
959 : // ConcurrencyLimitScheduler can also start 3 other compactions, for a total
960 : // of 6.
961 : //
962 : // DB.GetAllowedWithoutPermission returns a value in the interval
963 : // [lower, upper]. A value > lower is returned:
964 : // - when L0 read-amplification passes the L0CompactionConcurrency threshold;
965 : // - when compaction debt passes the CompactionDebtConcurrency threshold;
966 : // - when there are multiple manual compactions waiting to run.
967 : //
968 : // lower and upper must be greater than 0. If lower > upper, then upper is
969 : // used for both.
970 : //
971 : // The default values are 1, 1.
972 : CompactionConcurrencyRange func() (lower, upper int)
973 :
974 : // MaxConcurrentDownloads specifies the maximum number of download
975 : // compactions. These are compactions that copy an external file to the local
976 : // store.
977 : //
978 : // This limit is independent of CompactionConcurrencyRange; at any point in
979 : // time, we may be running CompactionConcurrencyRange non-download compactions
980 : // and MaxConcurrentDownloads download compactions.
981 : //
982 : // MaxConcurrentDownloads() must be greater than 0.
983 : //
984 : // The default value is 1.
985 : MaxConcurrentDownloads func() int
986 :
987 : // DisableAutomaticCompactions dictates whether automatic compactions are
988 : // scheduled or not. The default is false (enabled). This option is only used
989 : // externally when running a manual compaction, and internally for tests.
990 : DisableAutomaticCompactions bool
991 :
992 : // DisableConsistencyCheck disables the consistency check that is performed on
993 : // open. Should only be used when a database cannot be opened normally (e.g.
994 : // some of the tables don't exist / aren't accessible).
995 : DisableConsistencyCheck bool
996 :
997 : // DisableTableStats dictates whether tables should be loaded asynchronously
998 : // to compute statistics that inform compaction heuristics. The collection
999 : // of table stats improves compaction of tombstones, reclaiming disk space
1000 : // more quickly and in some cases reducing write amplification in the
1001 : // presence of tombstones. Disabling table stats may be useful in tests
1002 : // that require determinism as the asynchronicity of table stats collection
1003 : // introduces significant nondeterminism.
1004 : DisableTableStats bool
1005 :
1006 : // NoSyncOnClose decides whether the Pebble instance will enforce a
1007 : // close-time synchronization (e.g., fdatasync() or sync_file_range())
1008 : // on files it writes to. Setting this to true removes the guarantee for a
1009 : // sync on close. Some implementations can still issue a non-blocking sync.
1010 : NoSyncOnClose bool
1011 :
1012 : // NumPrevManifest is the number of non-current or older manifests which
1013 : // we want to keep around for debugging purposes. By default, we're going
1014 : // to keep one older manifest.
1015 : NumPrevManifest int
1016 :
1017 : // ReadOnly indicates that the DB should be opened in read-only mode. Writes
1018 : // to the DB will return an error, background compactions are disabled, and
1019 : // the flush that normally occurs after replaying the WAL at startup is
1020 : // disabled.
1021 : ReadOnly bool
1022 :
1023 : // FileCache is an initialized FileCache which should be set as an
1024 : // option if the DB needs to be initialized with a pre-existing file cache.
1025 : // If FileCache is nil, then a file cache which is unique to the DB instance
1026 : // is created. FileCache can be shared between db instances by setting it here.
1027 : // The FileCache set here must use the same underlying cache as Options.Cache
1028 : // and pebble will panic otherwise.
1029 : FileCache *FileCache
1030 :
1031 : // BlockPropertyCollectors is a list of BlockPropertyCollector creation
1032 : // functions. A new BlockPropertyCollector is created for each sstable
1033 : // built and lives for the lifetime of writing that table.
1034 : BlockPropertyCollectors []func() BlockPropertyCollector
1035 :
1036 : // WALBytesPerSync sets the number of bytes to write to a WAL before calling
1037 : // Sync on it in the background. Just like with BytesPerSync above, this
1038 : // helps smooth out disk write latencies, and avoids cases where the OS
1039 : // writes a lot of buffered data to disk at once. However, this is less
1040 : // necessary with WALs, as many write operations already pass in
1041 : // Sync = true.
1042 : //
1043 : // The default value is 0, i.e. no background syncing. This matches the
1044 : // default behaviour in RocksDB.
1045 : WALBytesPerSync int
1046 :
1047 : // WALDir specifies the directory to store write-ahead logs (WALs) in. If
1048 : // empty (the default), WALs will be stored in the same directory as sstables
1049 : // (i.e. the directory passed to pebble.Open).
1050 : WALDir string
1051 :
1052 : // WALDirLock, if set, must be a directory lock acquired through LockDirectory
1053 : // for the same directory set on WALDir passed to Open. If provided, Open will
1054 : // skip locking the directory. Closing the database will not release the lock,
1055 : // and it's the responsibility of the caller to release the lock after closing the
1056 : // database.
1057 : //
1058 : // Open will enforce that the Lock passed locks the same WAL directory passed to
1059 : // Open. Concurrent calls to Open using the same Lock are detected and
1060 : // prohibited.
1061 : WALDirLock *base.DirLock
1062 :
1063 : // WALFailover may be set to configure Pebble to monitor writes to its
1064 : // write-ahead log and failover to writing write-ahead log entries to a
1065 : // secondary location (eg, a separate physical disk). WALFailover may be
1066 : // used to improve write availability in the presence of transient disk
1067 : // unavailability.
1068 : WALFailover *WALFailoverOptions
1069 :
1070 : // WALRecoveryDirs is a list of additional directories that should be
1071 : // scanned for the existence of additional write-ahead logs. WALRecoveryDirs
1072 : // is expected to be used when starting Pebble with a new WALDir or a new
1073 : // WALFailover configuration. The directories associated with the previous
1074 : // configuration may still contain WALs that are required for recovery of
1075 : // the current database state.
1076 : //
1077 : // If a previous WAL configuration may have stored WALs elsewhere but there
1078 : // is not a corresponding entry in WALRecoveryDirs, Open will error.
1079 : WALRecoveryDirs []wal.Dir
1080 :
1081 : // WALMinSyncInterval is the minimum duration between syncs of the WAL. If
1082 : // WAL syncs are requested faster than this interval, they will be
1083 : // artificially delayed. Introducing a small artificial delay (500us) between
1084 : // WAL syncs can allow more operations to arrive and reduce IO operations
1085 : // while having a minimal impact on throughput. This option is supplied as a
1086 : // closure in order to allow the value to be changed dynamically. The default
1087 : // value is 0.
1088 : //
1089 : // TODO(peter): rather than a closure, should there be another mechanism for
1090 : // changing options dynamically?
1091 : WALMinSyncInterval func() time.Duration
1092 :
1093 : // The controls below manage deletion pacing, which slows down
1094 : // deletions when compactions finish or when readers close and
1095 : // obsolete files must be cleaned up. Rapid deletion of many
1096 : // files simultaneously can increase disk latency on certain
1097 : // SSDs, and this functionality helps protect against that.
1098 :
1099 : // TargetByteDeletionRate is the rate (in bytes per second) at which sstable file
1100 : // deletions are limited to (under normal circumstances).
1101 : //
1102 : // This value is only a best-effort target; the effective rate can be
1103 : // higher if deletions are falling behind or disk space is running low.
1104 : //
1105 : // Setting this to 0 disables deletion pacing, which is also the default.
1106 : TargetByteDeletionRate int
1107 :
1108 : // FreeSpaceThresholdBytes specifies the minimum amount of free disk space that Pebble
1109 : // attempts to maintain. If free disk space drops below this threshold, deletions
1110 : // are accelerated above TargetByteDeletionRate until the threshold is restored.
1111 : // Default is 16GB.
1112 : FreeSpaceThresholdBytes uint64
1113 :
1114 : // FreeSpaceTimeframe sets the duration (in seconds) within which Pebble attempts
1115 : // to restore the free disk space back to FreeSpaceThreshold. A lower value means
1116 : // more aggressive deletions. Default is 10s.
1117 : FreeSpaceTimeframe time.Duration
1118 :
1119 : // ObsoleteBytesMaxRatio specifies the maximum allowed ratio of obsolete files to
1120 : // live files. If this ratio is exceeded, Pebble speeds up deletions above the
1121 : // TargetByteDeletionRate until the ratio is restored. Default is 0.20.
1122 : ObsoleteBytesMaxRatio float64
1123 :
1124 : // ObsoleteBytesTimeframe sets the duration (in seconds) within which Pebble aims
1125 : // to restore the obsolete-to-live bytes ratio below ObsoleteBytesMaxRatio. A lower
1126 : // value means more aggressive deletions. Default is 300s.
1127 : ObsoleteBytesTimeframe time.Duration
1128 :
1129 : // EnableSQLRowSpillMetrics specifies whether the Pebble instance will only be used
1130 : // to temporarily persist data spilled to disk for row-oriented SQL query execution.
1131 : EnableSQLRowSpillMetrics bool
1132 :
1133 : // AllocatorSizeClasses provides a sorted list containing the supported size
1134 : // classes of the underlying memory allocator. This provides hints to the
1135 : // sstable block writer's flushing policy to select block sizes that
1136 : // preemptively reduce internal fragmentation when loaded into the block cache.
1137 : AllocatorSizeClasses []int
1138 :
1139 : // private options are only used by internal tests or are used internally
1140 : // for facilitating upgrade paths of unconfigurable functionality.
1141 : private struct {
1142 : // disableDeleteOnlyCompactions prevents the scheduling of delete-only
1143 : // compactions that drop sstables wholy covered by range tombstones or
1144 : // range key tombstones.
1145 : disableDeleteOnlyCompactions bool
1146 :
1147 : // disableElisionOnlyCompactions prevents the scheduling of elision-only
1148 : // compactions that rewrite sstables in place in order to elide obsolete
1149 : // keys.
1150 : disableElisionOnlyCompactions bool
1151 :
1152 : // disableLazyCombinedIteration is a private option used by the
1153 : // metamorphic tests to test equivalence between lazy-combined iteration
1154 : // and constructing the range-key iterator upfront. It's a private
1155 : // option to avoid littering the public interface with options that we
1156 : // do not want to allow users to actually configure.
1157 : disableLazyCombinedIteration bool
1158 :
1159 : // testingAlwaysWaitForCleanup is set by some tests to force waiting for
1160 : // obsolete file deletion (to make events deterministic).
1161 : testingAlwaysWaitForCleanup bool
1162 :
1163 : // fsCloser holds a closer that should be invoked after a DB using these
1164 : // Options is closed. This is used to automatically stop the
1165 : // long-running goroutine associated with the disk-health-checking FS.
1166 : // See the initialization of FS in EnsureDefaults. Note that care has
1167 : // been taken to ensure that it is still safe to continue using the FS
1168 : // after this closer has been invoked. However, if write operations
1169 : // against the FS are made after the DB is closed, the FS may leak a
1170 : // goroutine indefinitely.
1171 : fsCloser io.Closer
1172 : }
1173 : }
1174 :
1175 : // ValueSeparationPolicy controls the policy for separating values into
1176 : // external blob files.
1177 : type ValueSeparationPolicy struct {
1178 : // Enabled controls whether value separation is enabled.
1179 : Enabled bool
1180 : // MinimumSize imposes a lower bound on the size of values that can be
1181 : // separated into a blob file. Values smaller than this are always written
1182 : // to the sstable (but may still be written to a value block within the
1183 : // sstable).
1184 : //
1185 : // MinimumSize must be > 0.
1186 : MinimumSize int
1187 : // MaxBlobReferenceDepth limits the number of potentially overlapping (in
1188 : // the keyspace) blob files that can be referenced by a single sstable. If a
1189 : // compaction may produce an output sstable referencing more than this many
1190 : // overlapping blob files, the compaction will instead rewrite referenced
1191 : // values into new blob files.
1192 : //
1193 : // MaxBlobReferenceDepth must be > 0.
1194 : MaxBlobReferenceDepth int
1195 : // RewriteMinimumAge specifies how old a blob file must be in order for it
1196 : // to be eligible for a rewrite that reclaims disk space. Lower values
1197 : // reduce space amplification at the cost of write amplification
1198 : RewriteMinimumAge time.Duration
1199 : // TargetGarbageRatio is a value in the range [0, 1.0] and configures how
1200 : // aggressively blob files should be written in order to reduce space
1201 : // amplification induced by value separation. As compactions rewrite blob
1202 : // files, data may be duplicated. Older blob files containing the
1203 : // duplicated data may need to remain because other sstables are referencing
1204 : // other values contained in the same file.
1205 : //
1206 : // The DB can rewrite these blob files in place in order to reduce this
1207 : // space amplification, but this incurs write amplification. This option
1208 : // configures how much garbage may accrue before the DB will attempt to
1209 : // rewrite blob files to reduce it. A value of 0.20 indicates that once 20%
1210 : // of values in blob files are unreferenced, the DB should attempt to
1211 : // rewrite blob files to reclaim disk space.
1212 : //
1213 : // A value of 1.0 indicates that the DB should never attempt to rewrite blob
1214 : // files.
1215 : TargetGarbageRatio float64
1216 : }
1217 :
1218 : // SpanPolicy contains policies that can vary by key range. The zero value is
1219 : // the default value.
1220 : type SpanPolicy struct {
1221 : // Prefer a faster compression algorithm for the keys in this span.
1222 : //
1223 : // This is useful for keys that are frequently read or written but which don't
1224 : // amount to a significant amount of space.
1225 : PreferFastCompression bool
1226 :
1227 : // DisableValueSeparationBySuffix disables discriminating KVs depending on
1228 : // suffix.
1229 : //
1230 : // Among a set of keys with the same prefix, Pebble's default heuristics
1231 : // optimize access to the KV with the smallest suffix. This is useful for MVCC
1232 : // keys (where the smallest suffix is the latest version), but should be
1233 : // disabled for keys where the suffix does not correspond to a version.
1234 : DisableValueSeparationBySuffix bool
1235 :
1236 : // ValueStoragePolicy is a hint used to determine where to store the values
1237 : // for KVs.
1238 : ValueStoragePolicy ValueStoragePolicy
1239 : }
1240 :
1241 : // String returns a string representation of the SpanPolicy.
1242 1 : func (p SpanPolicy) String() string {
1243 1 : var sb strings.Builder
1244 1 : if p.PreferFastCompression {
1245 0 : sb.WriteString("fast-compression,")
1246 0 : }
1247 1 : if p.DisableValueSeparationBySuffix {
1248 0 : sb.WriteString("disable-value-separation-by-suffix,")
1249 0 : }
1250 1 : switch p.ValueStoragePolicy {
1251 1 : case ValueStorageLowReadLatency:
1252 1 : sb.WriteString("low-read-latency,")
1253 1 : case ValueStorageLatencyTolerant:
1254 1 : sb.WriteString("latency-tolerant,")
1255 : }
1256 1 : return strings.TrimSuffix(sb.String(), ",")
1257 : }
1258 :
1259 : // ValueStoragePolicy is a hint used to determine where to store the values for
1260 : // KVs.
1261 : type ValueStoragePolicy uint8
1262 :
1263 : const (
1264 : // ValueStorageDefault is the default value; Pebble will respect global
1265 : // configuration for value blocks and value separation.
1266 : ValueStorageDefault ValueStoragePolicy = iota
1267 :
1268 : // ValueStorageLowReadLatency indicates Pebble should prefer storing values
1269 : // in-place.
1270 : ValueStorageLowReadLatency
1271 :
1272 : // ValueStorageLatencyTolerant indicates value retrieval can tolerate
1273 : // additional latency, so Pebble should aggressively prefer storing values
1274 : // separately if it can reduce write amplification.
1275 : //
1276 : // If the global Options' enable value separation, Pebble may choose to
1277 : // separate values under the LatencyTolerant policy even if they do not meet
1278 : // the minimum size threshold of the global Options' ValueSeparationPolicy.
1279 : ValueStorageLatencyTolerant
1280 : )
1281 :
1282 : // SpanPolicyFunc is used to determine the SpanPolicy for a key region.
1283 : //
1284 : // The returned policy is valid from the start key until (and not including) the
1285 : // end key.
1286 : //
1287 : // A flush or compaction will call this function once for the first key to be
1288 : // output. If the compaction reaches the end key, the current output sst is
1289 : // finished and the function is called again.
1290 : //
1291 : // The end key can be empty, in which case the policy is valid for the entire
1292 : // keyspace after startKey.
1293 : type SpanPolicyFunc func(startKey []byte) (policy SpanPolicy, endKey []byte, err error)
1294 :
1295 : // SpanAndPolicy defines a key range and the policy to apply to it.
1296 : type SpanAndPolicy struct {
1297 : KeyRange KeyRange
1298 : Policy SpanPolicy
1299 : }
1300 :
1301 : // MakeStaticSpanPolicyFunc returns a SpanPolicyFunc that applies a given policy
1302 : // to the given span (and the default policy outside the span). The supplied
1303 : // policies must be non-overlapping in key range.
1304 1 : func MakeStaticSpanPolicyFunc(cmp base.Compare, inputPolicies ...SpanAndPolicy) SpanPolicyFunc {
1305 1 : // Collect all the boundaries of the input policies, sort and deduplicate them.
1306 1 : uniqueKeys := make([][]byte, 0, 2*len(inputPolicies))
1307 1 : for i := range inputPolicies {
1308 1 : uniqueKeys = append(uniqueKeys, inputPolicies[i].KeyRange.Start)
1309 1 : uniqueKeys = append(uniqueKeys, inputPolicies[i].KeyRange.End)
1310 1 : }
1311 1 : slices.SortFunc(uniqueKeys, cmp)
1312 1 : uniqueKeys = slices.CompactFunc(uniqueKeys, func(a, b []byte) bool { return cmp(a, b) == 0 })
1313 :
1314 : // Create a list of policies.
1315 1 : policies := make([]SpanPolicy, len(uniqueKeys)-1)
1316 1 : for _, p := range inputPolicies {
1317 1 : idx, _ := slices.BinarySearchFunc(uniqueKeys, p.KeyRange.Start, cmp)
1318 1 : policies[idx] = p.Policy
1319 1 : }
1320 :
1321 1 : return func(startKey []byte) (_ SpanPolicy, endKey []byte, _ error) {
1322 1 : // Find the policy that applies to the start key.
1323 1 : idx, eq := slices.BinarySearchFunc(uniqueKeys, startKey, cmp)
1324 1 : switch idx {
1325 1 : case len(uniqueKeys):
1326 1 : // The start key is after the last policy.
1327 1 : return SpanPolicy{}, nil, nil
1328 1 : case len(uniqueKeys) - 1:
1329 1 : if eq {
1330 1 : // The start key is exactly the start of the last policy.
1331 1 : return SpanPolicy{}, nil, nil
1332 1 : }
1333 1 : case 0:
1334 1 : if !eq {
1335 1 : // The start key is before the first policy.
1336 1 : return SpanPolicy{}, uniqueKeys[0], nil
1337 1 : }
1338 : }
1339 1 : if eq {
1340 1 : // The start key is exactly the start of this policy.
1341 1 : return policies[idx], uniqueKeys[idx+1], nil
1342 1 : }
1343 : // The start key is between two policies.
1344 1 : return policies[idx-1], uniqueKeys[idx], nil
1345 : }
1346 : }
1347 :
1348 : // WALFailoverOptions configures the WAL failover mechanics to use during
1349 : // transient write unavailability on the primary WAL volume.
1350 : type WALFailoverOptions struct {
1351 : // Secondary indicates the secondary directory and VFS to use in the event a
1352 : // write to the primary WAL stalls. The Lock field may be set during setup to
1353 : // preacquire the lock on the secondary directory.
1354 : Secondary wal.Dir
1355 :
1356 : // FailoverOptions provides configuration of the thresholds and intervals
1357 : // involved in WAL failover. If any of its fields are left unspecified,
1358 : // reasonable defaults will be used.
1359 : wal.FailoverOptions
1360 : }
1361 :
1362 : // ReadaheadConfig controls the use of read-ahead.
1363 : type ReadaheadConfig = objstorageprovider.ReadaheadConfig
1364 :
1365 : // JemallocSizeClasses exports sstable.JemallocSizeClasses.
1366 : var JemallocSizeClasses = sstable.JemallocSizeClasses
1367 :
1368 : // DebugCheckLevels calls CheckLevels on the provided database.
1369 : // It may be set in the DebugCheck field of Options to check
1370 : // level invariants whenever a new version is installed.
1371 2 : func DebugCheckLevels(db *DB) error {
1372 2 : return db.CheckLevels(nil)
1373 2 : }
1374 :
1375 : // DBCompressionSettings contains compression settings for the entire store. It
1376 : // defines compression profiles for each LSM level.
1377 : type DBCompressionSettings struct {
1378 : Name string
1379 : Levels [manifest.NumLevels]*block.CompressionProfile
1380 : }
1381 :
1382 : // Predefined compression settings.
1383 : var (
1384 : DBCompressionNone = UniformDBCompressionSettings(block.NoCompression)
1385 : DBCompressionFastest = UniformDBCompressionSettings(block.FastestCompression)
1386 2 : DBCompressionBalanced = func() DBCompressionSettings {
1387 2 : cs := DBCompressionSettings{Name: "Balanced"}
1388 2 : for i := 0; i < manifest.NumLevels-2; i++ {
1389 2 : cs.Levels[i] = block.FastestCompression
1390 2 : }
1391 2 : cs.Levels[manifest.NumLevels-2] = block.FastCompression // Zstd1 for value blocks.
1392 2 : cs.Levels[manifest.NumLevels-1] = block.BalancedCompression // Zstd1 for data and value blocks.
1393 2 : return cs
1394 : }()
1395 2 : DBCompressionGood = func() DBCompressionSettings {
1396 2 : cs := DBCompressionSettings{Name: "Good"}
1397 2 : for i := 0; i < manifest.NumLevels-2; i++ {
1398 2 : cs.Levels[i] = block.FastestCompression
1399 2 : }
1400 2 : cs.Levels[manifest.NumLevels-2] = block.BalancedCompression // Zstd1 for data and value blocks.
1401 2 : cs.Levels[manifest.NumLevels-1] = block.GoodCompression // Zstd3 for data and value blocks.
1402 2 : return cs
1403 : }()
1404 : )
1405 :
1406 : // UniformDBCompressionSettings returns a DBCompressionSettings which uses the
1407 : // same compression profile on all LSM levels.
1408 2 : func UniformDBCompressionSettings(profile *block.CompressionProfile) DBCompressionSettings {
1409 2 : cs := DBCompressionSettings{Name: profile.Name}
1410 2 : for i := range cs.Levels {
1411 2 : cs.Levels[i] = profile
1412 2 : }
1413 2 : return cs
1414 : }
1415 :
1416 : // ApplyCompressionSettings sets the Compression field in each LevelOptions to
1417 : // call the given function and return the compression profile for that level.
1418 1 : func (o *Options) ApplyCompressionSettings(csFn func() DBCompressionSettings) {
1419 1 : for i := range o.Levels {
1420 1 : levelIdx := i
1421 1 : o.Levels[i].Compression = func() *block.CompressionProfile {
1422 1 : return csFn().Levels[levelIdx]
1423 1 : }
1424 : }
1425 : }
1426 :
1427 : // EnsureDefaults ensures that the default values for all options are set if a
1428 : // valid value was not already specified.
1429 2 : func (o *Options) EnsureDefaults() {
1430 2 : if o.Cache == nil && o.CacheSize == 0 {
1431 1 : o.CacheSize = cacheDefaultSize
1432 1 : }
1433 2 : o.Comparer = o.Comparer.EnsureDefaults()
1434 2 :
1435 2 : if o.BytesPerSync <= 0 {
1436 1 : o.BytesPerSync = 512 << 10 // 512 KB
1437 1 : }
1438 2 : if o.Cleaner == nil {
1439 1 : o.Cleaner = DeleteCleaner{}
1440 1 : }
1441 :
1442 2 : if o.FreeSpaceThresholdBytes == 0 {
1443 1 : o.FreeSpaceThresholdBytes = 16 << 30 // 16 GB
1444 1 : }
1445 :
1446 2 : if o.FreeSpaceTimeframe == 0 {
1447 1 : o.FreeSpaceTimeframe = 10 * time.Second
1448 1 : }
1449 :
1450 2 : if o.ObsoleteBytesMaxRatio == 0 {
1451 1 : o.ObsoleteBytesMaxRatio = 0.20
1452 1 : }
1453 :
1454 2 : if o.ObsoleteBytesTimeframe == 0 {
1455 1 : o.ObsoleteBytesTimeframe = 300 * time.Second
1456 1 : }
1457 :
1458 2 : if o.Experimental.DisableIngestAsFlushable == nil {
1459 2 : o.Experimental.DisableIngestAsFlushable = func() bool { return false }
1460 : }
1461 2 : if o.Experimental.L0CompactionConcurrency <= 0 {
1462 1 : o.Experimental.L0CompactionConcurrency = 10
1463 1 : }
1464 2 : if o.Experimental.CompactionDebtConcurrency <= 0 {
1465 1 : o.Experimental.CompactionDebtConcurrency = 1 << 30 // 1 GB
1466 1 : }
1467 2 : if o.Experimental.CompactionGarbageFractionForMaxConcurrency == nil {
1468 1 : // When 40% of the DB is garbage, the compaction concurrency is at the
1469 1 : // maximum permitted.
1470 1 : o.Experimental.CompactionGarbageFractionForMaxConcurrency = func() float64 { return 0.4 }
1471 : }
1472 2 : if o.Experimental.ValueSeparationPolicy == nil {
1473 1 : o.Experimental.ValueSeparationPolicy = func() ValueSeparationPolicy {
1474 1 : return ValueSeparationPolicy{Enabled: false}
1475 1 : }
1476 : }
1477 2 : if o.KeySchema == "" && len(o.KeySchemas) == 0 {
1478 1 : ks := colblk.DefaultKeySchema(o.Comparer, 16 /* bundleSize */)
1479 1 : o.KeySchema = ks.Name
1480 1 : o.KeySchemas = sstable.MakeKeySchemas(&ks)
1481 1 : }
1482 2 : if o.L0CompactionThreshold <= 0 {
1483 1 : o.L0CompactionThreshold = 4
1484 1 : }
1485 2 : if o.L0CompactionFileThreshold <= 0 {
1486 1 : // Some justification for the default of 500:
1487 1 : // Why not smaller?:
1488 1 : // - The default target file size for L0 is 2MB, so 500 files is <= 1GB
1489 1 : // of data. At observed compaction speeds of > 20MB/s, L0 can be
1490 1 : // cleared of all files in < 1min, so this backlog is not huge.
1491 1 : // - 500 files is low overhead for instantiating L0 sublevels from
1492 1 : // scratch.
1493 1 : // - Lower values were observed to cause excessive and inefficient
1494 1 : // compactions out of L0 in a TPCC import benchmark.
1495 1 : // Why not larger?:
1496 1 : // - More than 1min to compact everything out of L0.
1497 1 : // - CockroachDB's admission control system uses a threshold of 1000
1498 1 : // files to start throttling writes to Pebble. Using 500 here gives
1499 1 : // us headroom between when Pebble should start compacting L0 and
1500 1 : // when the admission control threshold is reached.
1501 1 : //
1502 1 : // We can revisit this default in the future based on better
1503 1 : // experimental understanding.
1504 1 : //
1505 1 : // TODO(jackson): Experiment with slightly lower thresholds [or higher
1506 1 : // admission control thresholds] to see whether a higher L0 score at the
1507 1 : // threshold (currently 2.0) is necessary for some workloads to avoid
1508 1 : // starving L0 in favor of lower-level compactions.
1509 1 : o.L0CompactionFileThreshold = 500
1510 1 : }
1511 2 : if o.L0StopWritesThreshold <= 0 {
1512 1 : o.L0StopWritesThreshold = 12
1513 1 : }
1514 2 : if o.LBaseMaxBytes <= 0 {
1515 1 : o.LBaseMaxBytes = 64 << 20 // 64 MB
1516 1 : }
1517 2 : if o.TargetFileSizes[0] <= 0 {
1518 1 : o.TargetFileSizes[0] = 2 << 20 // 2 MB
1519 1 : }
1520 2 : for i := 1; i < len(o.TargetFileSizes); i++ {
1521 2 : if o.TargetFileSizes[i] <= 0 {
1522 1 : o.TargetFileSizes[i] = o.TargetFileSizes[i-1] * 2
1523 1 : }
1524 : }
1525 2 : o.Levels[0].EnsureL0Defaults()
1526 2 : for i := 1; i < len(o.Levels); i++ {
1527 2 : o.Levels[i].EnsureL1PlusDefaults(&o.Levels[i-1])
1528 2 : }
1529 2 : if o.Logger == nil {
1530 2 : o.Logger = DefaultLogger
1531 2 : }
1532 2 : if o.EventListener == nil {
1533 2 : o.EventListener = &EventListener{}
1534 2 : }
1535 2 : o.EventListener.EnsureDefaults(o.Logger)
1536 2 : if o.MaxManifestFileSize == 0 {
1537 1 : o.MaxManifestFileSize = 128 << 20 // 128 MB
1538 1 : }
1539 2 : if o.MaxOpenFiles == 0 {
1540 1 : o.MaxOpenFiles = 1000
1541 1 : }
1542 2 : if o.MemTableSize <= 0 {
1543 1 : o.MemTableSize = 4 << 20 // 4 MB
1544 1 : }
1545 2 : if o.MemTableStopWritesThreshold <= 0 {
1546 1 : o.MemTableStopWritesThreshold = 2
1547 1 : }
1548 2 : if o.Merger == nil {
1549 1 : o.Merger = DefaultMerger
1550 1 : }
1551 2 : if o.CompactionConcurrencyRange == nil {
1552 1 : o.CompactionConcurrencyRange = func() (int, int) { return 1, 1 }
1553 : }
1554 2 : if o.MaxConcurrentDownloads == nil {
1555 1 : o.MaxConcurrentDownloads = func() int { return 1 }
1556 : }
1557 2 : if o.NumPrevManifest <= 0 {
1558 2 : o.NumPrevManifest = 1
1559 2 : }
1560 :
1561 2 : if o.FormatMajorVersion == FormatDefault {
1562 1 : o.FormatMajorVersion = FormatMinSupported
1563 1 : if o.Experimental.CreateOnShared != remote.CreateOnSharedNone {
1564 1 : o.FormatMajorVersion = FormatMinForSharedObjects
1565 1 : }
1566 : }
1567 :
1568 2 : if o.FS == nil {
1569 1 : o.WithFSDefaults()
1570 1 : }
1571 2 : if o.FlushSplitBytes <= 0 {
1572 1 : o.FlushSplitBytes = 2 * o.TargetFileSizes[0]
1573 1 : }
1574 2 : if o.WALFailover != nil {
1575 2 : o.WALFailover.FailoverOptions.EnsureDefaults()
1576 2 : }
1577 2 : if o.Experimental.UseDeprecatedCompensatedScore == nil {
1578 2 : o.Experimental.UseDeprecatedCompensatedScore = func() bool { return false }
1579 : }
1580 2 : if o.Experimental.LevelMultiplier <= 0 {
1581 2 : o.Experimental.LevelMultiplier = defaultLevelMultiplier
1582 2 : }
1583 2 : if o.Experimental.ReadCompactionRate == 0 {
1584 1 : o.Experimental.ReadCompactionRate = 16000
1585 1 : }
1586 2 : if o.Experimental.ReadSamplingMultiplier == 0 {
1587 1 : o.Experimental.ReadSamplingMultiplier = 1 << 4
1588 1 : }
1589 2 : if o.Experimental.NumDeletionsThreshold == 0 {
1590 1 : o.Experimental.NumDeletionsThreshold = sstable.DefaultNumDeletionsThreshold
1591 1 : }
1592 2 : if o.Experimental.DeletionSizeRatioThreshold == 0 {
1593 1 : o.Experimental.DeletionSizeRatioThreshold = sstable.DefaultDeletionSizeRatioThreshold
1594 1 : }
1595 2 : if o.Experimental.TombstoneDenseCompactionThreshold == 0 {
1596 1 : o.Experimental.TombstoneDenseCompactionThreshold = 0.10
1597 1 : }
1598 2 : if o.Experimental.FileCacheShards <= 0 {
1599 1 : o.Experimental.FileCacheShards = runtime.GOMAXPROCS(0)
1600 1 : }
1601 2 : if o.Experimental.MultiLevelCompactionHeuristic == nil {
1602 1 : o.Experimental.MultiLevelCompactionHeuristic = OptionWriteAmpHeuristic
1603 1 : }
1604 2 : if o.Experimental.SpanPolicyFunc == nil {
1605 2 : o.Experimental.SpanPolicyFunc = func(startKey []byte) (SpanPolicy, []byte, error) { return SpanPolicy{}, nil, nil }
1606 : }
1607 : // TODO(jackson): Enable value separation by default once we have confidence
1608 : // in a default policy.
1609 :
1610 2 : o.initMaps()
1611 : }
1612 :
1613 : // TargetFileSize computes the target file size for the given output level.
1614 2 : func (o *Options) TargetFileSize(outputLevel int, baseLevel int) int64 {
1615 2 : if outputLevel == 0 {
1616 2 : return o.TargetFileSizes[0]
1617 2 : }
1618 2 : if baseLevel > outputLevel {
1619 0 : panic(fmt.Sprintf("invalid base level %d (output level %d)", baseLevel, outputLevel))
1620 : }
1621 2 : return o.TargetFileSizes[outputLevel-baseLevel+1]
1622 : }
1623 :
1624 : // DefaultOptions returns a new Options object with the default values set.
1625 1 : func DefaultOptions() *Options {
1626 1 : o := &Options{}
1627 1 : o.EnsureDefaults()
1628 1 : return o
1629 1 : }
1630 :
1631 : // WithFSDefaults configures the Options to wrap the configured filesystem with
1632 : // the default virtual file system middleware, like disk-health checking.
1633 2 : func (o *Options) WithFSDefaults() {
1634 2 : if o.FS == nil {
1635 1 : o.FS = vfs.Default
1636 1 : }
1637 2 : o.FS, o.private.fsCloser = vfs.WithDiskHealthChecks(o.FS, 5*time.Second, nil,
1638 2 : func(info vfs.DiskSlowInfo) {
1639 0 : o.EventListener.DiskSlow(info)
1640 0 : })
1641 : }
1642 :
1643 : // AddEventListener adds the provided event listener to the Options, in addition
1644 : // to any existing event listener.
1645 1 : func (o *Options) AddEventListener(l EventListener) {
1646 1 : if o.EventListener != nil {
1647 1 : l = TeeEventListener(l, *o.EventListener)
1648 1 : }
1649 1 : o.EventListener = &l
1650 : }
1651 :
1652 : // initMaps initializes the Comparers, Filters, and Mergers maps.
1653 2 : func (o *Options) initMaps() {
1654 2 : for i := range o.Levels {
1655 2 : l := &o.Levels[i]
1656 2 : if l.FilterPolicy != NoFilterPolicy {
1657 2 : if o.Filters == nil {
1658 2 : o.Filters = make(map[string]FilterPolicy)
1659 2 : }
1660 2 : name := l.FilterPolicy.Name()
1661 2 : if _, ok := o.Filters[name]; !ok {
1662 2 : o.Filters[name] = l.FilterPolicy
1663 2 : }
1664 : }
1665 : }
1666 : }
1667 :
1668 : // Clone creates a shallow-copy of the supplied options.
1669 2 : func (o *Options) Clone() *Options {
1670 2 : if o == nil {
1671 1 : return &Options{}
1672 1 : }
1673 2 : n := *o
1674 2 : if o.WALFailover != nil {
1675 2 : c := *o.WALFailover
1676 2 : n.WALFailover = &c
1677 2 : }
1678 2 : return &n
1679 : }
1680 :
1681 2 : func (o *Options) String() string {
1682 2 : var buf bytes.Buffer
1683 2 :
1684 2 : cacheSize := o.CacheSize
1685 2 : if o.Cache != nil {
1686 2 : cacheSize = o.Cache.MaxSize()
1687 2 : }
1688 :
1689 2 : fmt.Fprintf(&buf, "[Version]\n")
1690 2 : fmt.Fprintf(&buf, " pebble_version=0.1\n")
1691 2 : fmt.Fprintf(&buf, "\n")
1692 2 : fmt.Fprintf(&buf, "[Options]\n")
1693 2 : fmt.Fprintf(&buf, " bytes_per_sync=%d\n", o.BytesPerSync)
1694 2 : fmt.Fprintf(&buf, " cache_size=%d\n", cacheSize)
1695 2 : fmt.Fprintf(&buf, " cleaner=%s\n", o.Cleaner)
1696 2 : fmt.Fprintf(&buf, " compaction_debt_concurrency=%d\n", o.Experimental.CompactionDebtConcurrency)
1697 2 : fmt.Fprintf(&buf, " compaction_garbage_fraction_for_max_concurrency=%.2f\n",
1698 2 : o.Experimental.CompactionGarbageFractionForMaxConcurrency())
1699 2 : fmt.Fprintf(&buf, " comparer=%s\n", o.Comparer.Name)
1700 2 : fmt.Fprintf(&buf, " disable_wal=%t\n", o.DisableWAL)
1701 2 : if o.Experimental.DisableIngestAsFlushable != nil && o.Experimental.DisableIngestAsFlushable() {
1702 2 : fmt.Fprintf(&buf, " disable_ingest_as_flushable=%t\n", true)
1703 2 : }
1704 2 : fmt.Fprintf(&buf, " flush_delay_delete_range=%s\n", o.FlushDelayDeleteRange)
1705 2 : fmt.Fprintf(&buf, " flush_delay_range_key=%s\n", o.FlushDelayRangeKey)
1706 2 : fmt.Fprintf(&buf, " flush_split_bytes=%d\n", o.FlushSplitBytes)
1707 2 : fmt.Fprintf(&buf, " format_major_version=%d\n", o.FormatMajorVersion)
1708 2 : fmt.Fprintf(&buf, " key_schema=%s\n", o.KeySchema)
1709 2 : fmt.Fprintf(&buf, " l0_compaction_concurrency=%d\n", o.Experimental.L0CompactionConcurrency)
1710 2 : fmt.Fprintf(&buf, " l0_compaction_file_threshold=%d\n", o.L0CompactionFileThreshold)
1711 2 : fmt.Fprintf(&buf, " l0_compaction_threshold=%d\n", o.L0CompactionThreshold)
1712 2 : fmt.Fprintf(&buf, " l0_stop_writes_threshold=%d\n", o.L0StopWritesThreshold)
1713 2 : fmt.Fprintf(&buf, " lbase_max_bytes=%d\n", o.LBaseMaxBytes)
1714 2 : if o.Experimental.LevelMultiplier != defaultLevelMultiplier {
1715 2 : fmt.Fprintf(&buf, " level_multiplier=%d\n", o.Experimental.LevelMultiplier)
1716 2 : }
1717 2 : lower, upper := o.CompactionConcurrencyRange()
1718 2 : fmt.Fprintf(&buf, " concurrent_compactions=%d\n", lower)
1719 2 : fmt.Fprintf(&buf, " max_concurrent_compactions=%d\n", upper)
1720 2 : fmt.Fprintf(&buf, " max_concurrent_downloads=%d\n", o.MaxConcurrentDownloads())
1721 2 : fmt.Fprintf(&buf, " max_manifest_file_size=%d\n", o.MaxManifestFileSize)
1722 2 : fmt.Fprintf(&buf, " max_open_files=%d\n", o.MaxOpenFiles)
1723 2 : fmt.Fprintf(&buf, " mem_table_size=%d\n", o.MemTableSize)
1724 2 : fmt.Fprintf(&buf, " mem_table_stop_writes_threshold=%d\n", o.MemTableStopWritesThreshold)
1725 2 : fmt.Fprintf(&buf, " min_deletion_rate=%d\n", o.TargetByteDeletionRate)
1726 2 : fmt.Fprintf(&buf, " free_space_threshold_bytes=%d\n", o.FreeSpaceThresholdBytes)
1727 2 : fmt.Fprintf(&buf, " free_space_timeframe=%s\n", o.FreeSpaceTimeframe.String())
1728 2 : fmt.Fprintf(&buf, " obsolete_bytes_max_ratio=%f\n", o.ObsoleteBytesMaxRatio)
1729 2 : fmt.Fprintf(&buf, " obsolete_bytes_timeframe=%s\n", o.ObsoleteBytesTimeframe.String())
1730 2 : fmt.Fprintf(&buf, " merger=%s\n", o.Merger.Name)
1731 2 : if o.Experimental.MultiLevelCompactionHeuristic != nil {
1732 2 : fmt.Fprintf(&buf, " multilevel_compaction_heuristic=%s\n", o.Experimental.MultiLevelCompactionHeuristic().String())
1733 2 : }
1734 2 : fmt.Fprintf(&buf, " read_compaction_rate=%d\n", o.Experimental.ReadCompactionRate)
1735 2 : fmt.Fprintf(&buf, " read_sampling_multiplier=%d\n", o.Experimental.ReadSamplingMultiplier)
1736 2 : fmt.Fprintf(&buf, " num_deletions_threshold=%d\n", o.Experimental.NumDeletionsThreshold)
1737 2 : fmt.Fprintf(&buf, " deletion_size_ratio_threshold=%f\n", o.Experimental.DeletionSizeRatioThreshold)
1738 2 : fmt.Fprintf(&buf, " tombstone_dense_compaction_threshold=%f\n", o.Experimental.TombstoneDenseCompactionThreshold)
1739 2 : // We no longer care about strict_wal_tail, but set it to true in case an
1740 2 : // older version reads the options.
1741 2 : fmt.Fprintf(&buf, " strict_wal_tail=%t\n", true)
1742 2 : fmt.Fprintf(&buf, " table_cache_shards=%d\n", o.Experimental.FileCacheShards)
1743 2 : fmt.Fprintf(&buf, " validate_on_ingest=%t\n", o.Experimental.ValidateOnIngest)
1744 2 : fmt.Fprintf(&buf, " wal_dir=%s\n", o.WALDir)
1745 2 : fmt.Fprintf(&buf, " wal_bytes_per_sync=%d\n", o.WALBytesPerSync)
1746 2 : fmt.Fprintf(&buf, " secondary_cache_size_bytes=%d\n", o.Experimental.SecondaryCacheSizeBytes)
1747 2 : fmt.Fprintf(&buf, " create_on_shared=%d\n", o.Experimental.CreateOnShared)
1748 2 :
1749 2 : // Private options.
1750 2 : //
1751 2 : // These options are only encoded if true, because we do not want them to
1752 2 : // appear in production serialized Options files, since they're testing-only
1753 2 : // options. They're only serialized when true, which still ensures that the
1754 2 : // metamorphic tests may propagate them to subprocesses.
1755 2 : if o.private.disableDeleteOnlyCompactions {
1756 2 : fmt.Fprintln(&buf, " disable_delete_only_compactions=true")
1757 2 : }
1758 2 : if o.private.disableElisionOnlyCompactions {
1759 2 : fmt.Fprintln(&buf, " disable_elision_only_compactions=true")
1760 2 : }
1761 2 : if o.private.disableLazyCombinedIteration {
1762 2 : fmt.Fprintln(&buf, " disable_lazy_combined_iteration=true")
1763 2 : }
1764 :
1765 2 : if o.Experimental.ValueSeparationPolicy != nil {
1766 2 : policy := o.Experimental.ValueSeparationPolicy()
1767 2 : if policy.Enabled {
1768 2 : fmt.Fprintln(&buf)
1769 2 : fmt.Fprintln(&buf, "[Value Separation]")
1770 2 : fmt.Fprintf(&buf, " enabled=%t\n", policy.Enabled)
1771 2 : fmt.Fprintf(&buf, " minimum_size=%d\n", policy.MinimumSize)
1772 2 : fmt.Fprintf(&buf, " max_blob_reference_depth=%d\n", policy.MaxBlobReferenceDepth)
1773 2 : fmt.Fprintf(&buf, " rewrite_minimum_age=%s\n", policy.RewriteMinimumAge)
1774 2 : fmt.Fprintf(&buf, " target_garbage_ratio=%.2f\n", policy.TargetGarbageRatio)
1775 2 : }
1776 : }
1777 :
1778 2 : if o.WALFailover != nil {
1779 2 : unhealthyThreshold, _ := o.WALFailover.FailoverOptions.UnhealthyOperationLatencyThreshold()
1780 2 : fmt.Fprintf(&buf, "\n")
1781 2 : fmt.Fprintf(&buf, "[WAL Failover]\n")
1782 2 : fmt.Fprintf(&buf, " secondary_dir=%s\n", o.WALFailover.Secondary.Dirname)
1783 2 : fmt.Fprintf(&buf, " primary_dir_probe_interval=%s\n", o.WALFailover.FailoverOptions.PrimaryDirProbeInterval)
1784 2 : fmt.Fprintf(&buf, " healthy_probe_latency_threshold=%s\n", o.WALFailover.FailoverOptions.HealthyProbeLatencyThreshold)
1785 2 : fmt.Fprintf(&buf, " healthy_interval=%s\n", o.WALFailover.FailoverOptions.HealthyInterval)
1786 2 : fmt.Fprintf(&buf, " unhealthy_sampling_interval=%s\n", o.WALFailover.FailoverOptions.UnhealthySamplingInterval)
1787 2 : fmt.Fprintf(&buf, " unhealthy_operation_latency_threshold=%s\n", unhealthyThreshold)
1788 2 : fmt.Fprintf(&buf, " elevated_write_stall_threshold_lag=%s\n", o.WALFailover.FailoverOptions.ElevatedWriteStallThresholdLag)
1789 2 : }
1790 :
1791 2 : for i := range o.Levels {
1792 2 : l := &o.Levels[i]
1793 2 : fmt.Fprintf(&buf, "\n")
1794 2 : fmt.Fprintf(&buf, "[Level \"%d\"]\n", i)
1795 2 : fmt.Fprintf(&buf, " block_restart_interval=%d\n", l.BlockRestartInterval)
1796 2 : fmt.Fprintf(&buf, " block_size=%d\n", l.BlockSize)
1797 2 : fmt.Fprintf(&buf, " block_size_threshold=%d\n", l.BlockSizeThreshold)
1798 2 : fmt.Fprintf(&buf, " compression=%s\n", l.Compression().Name)
1799 2 : fmt.Fprintf(&buf, " filter_policy=%s\n", l.FilterPolicy.Name())
1800 2 : fmt.Fprintf(&buf, " filter_type=%s\n", l.FilterType)
1801 2 : fmt.Fprintf(&buf, " index_block_size=%d\n", l.IndexBlockSize)
1802 2 : fmt.Fprintf(&buf, " target_file_size=%d\n", o.TargetFileSizes[i])
1803 2 : }
1804 :
1805 2 : return buf.String()
1806 : }
1807 :
1808 : type parseOptionsFuncs struct {
1809 : visitNewSection func(i, j int, section string) error
1810 : visitKeyValue func(i, j int, section, key, value string) error
1811 : visitCommentOrWhitespace func(i, j int, whitespace string) error
1812 : }
1813 :
1814 : // parseOptions takes options serialized by Options.String() and parses them
1815 : // into keys and values. It calls fns.visitNewSection for the beginning of each
1816 : // new section, fns.visitKeyValue for each key-value pair, and
1817 : // visitCommentOrWhitespace for comments and whitespace between key-value pairs.
1818 2 : func parseOptions(s string, fns parseOptionsFuncs) error {
1819 2 : var section, mappedSection string
1820 2 : i := 0
1821 2 : for i < len(s) {
1822 2 : rem := s[i:]
1823 2 : j := strings.IndexByte(rem, '\n')
1824 2 : if j < 0 {
1825 1 : j = len(rem)
1826 2 : } else {
1827 2 : j += 1 // Include the newline.
1828 2 : }
1829 2 : line := strings.TrimSpace(s[i : i+j])
1830 2 : startOff, endOff := i, i+j
1831 2 : i += j
1832 2 :
1833 2 : if len(line) == 0 || line[0] == ';' || line[0] == '#' {
1834 2 : // Skip blank lines and comments.
1835 2 : if fns.visitCommentOrWhitespace != nil {
1836 2 : if err := fns.visitCommentOrWhitespace(startOff, endOff, line); err != nil {
1837 0 : return err
1838 0 : }
1839 : }
1840 2 : continue
1841 : }
1842 2 : n := len(line)
1843 2 : if line[0] == '[' && line[n-1] == ']' {
1844 2 : // Parse section.
1845 2 : section = line[1 : n-1]
1846 2 : // RocksDB uses a similar (INI-style) syntax for the OPTIONS file, but
1847 2 : // different section names and keys. The "CFOptions ..." paths are the
1848 2 : // RocksDB versions which we map to the Pebble paths.
1849 2 : mappedSection = section
1850 2 : if section == `CFOptions "default"` {
1851 1 : mappedSection = "Options"
1852 1 : }
1853 2 : if fns.visitNewSection != nil {
1854 2 : if err := fns.visitNewSection(startOff, endOff, mappedSection); err != nil {
1855 0 : return err
1856 0 : }
1857 : }
1858 2 : continue
1859 : }
1860 :
1861 2 : pos := strings.Index(line, "=")
1862 2 : if pos < 0 {
1863 1 : const maxLen = 50
1864 1 : if len(line) > maxLen {
1865 0 : line = line[:maxLen-3] + "..."
1866 0 : }
1867 1 : return base.CorruptionErrorf("invalid key=value syntax: %q", errors.Safe(line))
1868 : }
1869 :
1870 2 : key := strings.TrimSpace(line[:pos])
1871 2 : value := strings.TrimSpace(line[pos+1:])
1872 2 :
1873 2 : if section == `CFOptions "default"` {
1874 1 : switch key {
1875 1 : case "comparator":
1876 1 : key = "comparer"
1877 1 : case "merge_operator":
1878 1 : key = "merger"
1879 : }
1880 : }
1881 2 : if fns.visitKeyValue != nil {
1882 2 : if err := fns.visitKeyValue(startOff, endOff, mappedSection, key, value); err != nil {
1883 1 : return err
1884 1 : }
1885 : }
1886 : }
1887 2 : return nil
1888 : }
1889 :
1890 : // ParseHooks contains callbacks to create options fields which can have
1891 : // user-defined implementations.
1892 : type ParseHooks struct {
1893 : NewCleaner func(name string) (Cleaner, error)
1894 : NewComparer func(name string) (*Comparer, error)
1895 : NewFilterPolicy func(name string) (FilterPolicy, error)
1896 : NewKeySchema func(name string) (KeySchema, error)
1897 : NewMerger func(name string) (*Merger, error)
1898 : SkipUnknown func(name, value string) bool
1899 : }
1900 :
1901 : // Parse parses the options from the specified string. Note that certain
1902 : // options cannot be parsed into populated fields. For example, comparer and
1903 : // merger.
1904 2 : func (o *Options) Parse(s string, hooks *ParseHooks) error {
1905 2 : var valSepPolicy ValueSeparationPolicy
1906 2 : var concurrencyLimit struct {
1907 2 : lower int
1908 2 : lowerSet bool
1909 2 : upper int
1910 2 : upperSet bool
1911 2 : }
1912 2 :
1913 2 : visitKeyValue := func(i, j int, section, key, value string) error {
1914 2 : // WARNING: DO NOT remove entries from the switches below because doing so
1915 2 : // causes a key previously written to the OPTIONS file to be considered unknown,
1916 2 : // a backwards incompatible change. Instead, leave in support for parsing the
1917 2 : // key but simply don't parse the value.
1918 2 :
1919 2 : parseComparer := func(name string) (*Comparer, error) {
1920 2 : switch name {
1921 1 : case DefaultComparer.Name:
1922 1 : return DefaultComparer, nil
1923 2 : case testkeys.Comparer.Name:
1924 2 : return testkeys.Comparer, nil
1925 2 : default:
1926 2 : if hooks != nil && hooks.NewComparer != nil {
1927 2 : return hooks.NewComparer(name)
1928 2 : }
1929 1 : return nil, nil
1930 : }
1931 : }
1932 :
1933 2 : switch {
1934 2 : case section == "Version":
1935 2 : switch key {
1936 2 : case "pebble_version":
1937 0 : default:
1938 0 : if hooks != nil && hooks.SkipUnknown != nil && hooks.SkipUnknown(section+"."+key, value) {
1939 0 : return nil
1940 0 : }
1941 0 : return errors.Errorf("pebble: unknown option: %s.%s",
1942 0 : errors.Safe(section), errors.Safe(key))
1943 : }
1944 2 : return nil
1945 :
1946 2 : case section == "Options":
1947 2 : var err error
1948 2 : switch key {
1949 2 : case "bytes_per_sync":
1950 2 : o.BytesPerSync, err = strconv.Atoi(value)
1951 2 : case "cache_size":
1952 2 : o.CacheSize, err = strconv.ParseInt(value, 10, 64)
1953 2 : case "cleaner":
1954 2 : switch value {
1955 2 : case "archive":
1956 2 : o.Cleaner = ArchiveCleaner{}
1957 1 : case "delete":
1958 1 : o.Cleaner = DeleteCleaner{}
1959 0 : default:
1960 0 : if hooks != nil && hooks.NewCleaner != nil {
1961 0 : o.Cleaner, err = hooks.NewCleaner(value)
1962 0 : }
1963 : }
1964 2 : case "comparer":
1965 2 : var comparer *Comparer
1966 2 : comparer, err = parseComparer(value)
1967 2 : if comparer != nil {
1968 2 : o.Comparer = comparer
1969 2 : }
1970 2 : case "compaction_debt_concurrency":
1971 2 : o.Experimental.CompactionDebtConcurrency, err = strconv.ParseUint(value, 10, 64)
1972 2 : case "compaction_garbage_fraction_for_max_concurrency":
1973 2 : var frac float64
1974 2 : frac, err = strconv.ParseFloat(value, 64)
1975 2 : if err == nil {
1976 2 : o.Experimental.CompactionGarbageFractionForMaxConcurrency =
1977 2 : func() float64 { return frac }
1978 : }
1979 0 : case "delete_range_flush_delay":
1980 0 : // NB: This is a deprecated serialization of the
1981 0 : // `flush_delay_delete_range`.
1982 0 : o.FlushDelayDeleteRange, err = time.ParseDuration(value)
1983 2 : case "disable_delete_only_compactions":
1984 2 : o.private.disableDeleteOnlyCompactions, err = strconv.ParseBool(value)
1985 2 : case "disable_elision_only_compactions":
1986 2 : o.private.disableElisionOnlyCompactions, err = strconv.ParseBool(value)
1987 2 : case "disable_ingest_as_flushable":
1988 2 : var v bool
1989 2 : v, err = strconv.ParseBool(value)
1990 2 : if err == nil {
1991 2 : o.Experimental.DisableIngestAsFlushable = func() bool { return v }
1992 : }
1993 2 : case "disable_lazy_combined_iteration":
1994 2 : o.private.disableLazyCombinedIteration, err = strconv.ParseBool(value)
1995 2 : case "disable_wal":
1996 2 : o.DisableWAL, err = strconv.ParseBool(value)
1997 1 : case "enable_columnar_blocks":
1998 : // Do nothing; option existed in older versions of pebble.
1999 2 : case "flush_delay_delete_range":
2000 2 : o.FlushDelayDeleteRange, err = time.ParseDuration(value)
2001 2 : case "flush_delay_range_key":
2002 2 : o.FlushDelayRangeKey, err = time.ParseDuration(value)
2003 2 : case "flush_split_bytes":
2004 2 : o.FlushSplitBytes, err = strconv.ParseInt(value, 10, 64)
2005 2 : case "format_major_version":
2006 2 : // NB: The version written here may be stale. Open does
2007 2 : // not use the format major version encoded in the
2008 2 : // OPTIONS file other than to validate that the encoded
2009 2 : // version is valid right here.
2010 2 : var v uint64
2011 2 : v, err = strconv.ParseUint(value, 10, 64)
2012 2 : if vers := FormatMajorVersion(v); vers > internalFormatNewest || vers == FormatDefault {
2013 0 : err = errors.Newf("unsupported format major version %d", o.FormatMajorVersion)
2014 0 : }
2015 2 : if err == nil {
2016 2 : o.FormatMajorVersion = FormatMajorVersion(v)
2017 2 : }
2018 2 : case "key_schema":
2019 2 : o.KeySchema = value
2020 2 : if o.KeySchemas == nil {
2021 1 : o.KeySchemas = make(map[string]*KeySchema)
2022 1 : }
2023 2 : if _, ok := o.KeySchemas[o.KeySchema]; !ok {
2024 1 : if strings.HasPrefix(value, "DefaultKeySchema(") && strings.HasSuffix(value, ")") {
2025 1 : argsStr := strings.TrimSuffix(strings.TrimPrefix(value, "DefaultKeySchema("), ")")
2026 1 : args := strings.FieldsFunc(argsStr, func(r rune) bool {
2027 1 : return unicode.IsSpace(r) || r == ','
2028 1 : })
2029 1 : var comparer *base.Comparer
2030 1 : var bundleSize int
2031 1 : comparer, err = parseComparer(args[0])
2032 1 : if err == nil {
2033 1 : bundleSize, err = strconv.Atoi(args[1])
2034 1 : }
2035 1 : if err == nil {
2036 1 : schema := colblk.DefaultKeySchema(comparer, bundleSize)
2037 1 : o.KeySchema = schema.Name
2038 1 : o.KeySchemas[o.KeySchema] = &schema
2039 1 : }
2040 1 : } else if hooks != nil && hooks.NewKeySchema != nil {
2041 0 : var schema KeySchema
2042 0 : schema, err = hooks.NewKeySchema(value)
2043 0 : if err == nil {
2044 0 : o.KeySchemas[value] = &schema
2045 0 : }
2046 : }
2047 : }
2048 2 : case "l0_compaction_concurrency":
2049 2 : o.Experimental.L0CompactionConcurrency, err = strconv.Atoi(value)
2050 2 : case "l0_compaction_file_threshold":
2051 2 : o.L0CompactionFileThreshold, err = strconv.Atoi(value)
2052 2 : case "l0_compaction_threshold":
2053 2 : o.L0CompactionThreshold, err = strconv.Atoi(value)
2054 2 : case "l0_stop_writes_threshold":
2055 2 : o.L0StopWritesThreshold, err = strconv.Atoi(value)
2056 0 : case "l0_sublevel_compactions":
2057 : // Do nothing; option existed in older versions of pebble.
2058 2 : case "lbase_max_bytes":
2059 2 : o.LBaseMaxBytes, err = strconv.ParseInt(value, 10, 64)
2060 2 : case "level_multiplier":
2061 2 : o.Experimental.LevelMultiplier, err = strconv.Atoi(value)
2062 2 : case "concurrent_compactions":
2063 2 : concurrencyLimit.lowerSet = true
2064 2 : concurrencyLimit.lower, err = strconv.Atoi(value)
2065 2 : case "max_concurrent_compactions":
2066 2 : concurrencyLimit.upperSet = true
2067 2 : concurrencyLimit.upper, err = strconv.Atoi(value)
2068 2 : case "max_concurrent_downloads":
2069 2 : var concurrentDownloads int
2070 2 : concurrentDownloads, err = strconv.Atoi(value)
2071 2 : if concurrentDownloads <= 0 {
2072 0 : err = errors.New("max_concurrent_compactions cannot be <= 0")
2073 2 : } else {
2074 2 : o.MaxConcurrentDownloads = func() int { return concurrentDownloads }
2075 : }
2076 2 : case "max_manifest_file_size":
2077 2 : o.MaxManifestFileSize, err = strconv.ParseInt(value, 10, 64)
2078 2 : case "max_open_files":
2079 2 : o.MaxOpenFiles, err = strconv.Atoi(value)
2080 2 : case "mem_table_size":
2081 2 : o.MemTableSize, err = strconv.ParseUint(value, 10, 64)
2082 2 : case "mem_table_stop_writes_threshold":
2083 2 : o.MemTableStopWritesThreshold, err = strconv.Atoi(value)
2084 0 : case "min_compaction_rate":
2085 : // Do nothing; option existed in older versions of pebble, and
2086 : // may be meaningful again eventually.
2087 2 : case "min_deletion_rate":
2088 2 : o.TargetByteDeletionRate, err = strconv.Atoi(value)
2089 2 : case "free_space_threshold_bytes":
2090 2 : o.FreeSpaceThresholdBytes, err = strconv.ParseUint(value, 10, 64)
2091 2 : case "free_space_timeframe":
2092 2 : o.FreeSpaceTimeframe, err = time.ParseDuration(value)
2093 2 : case "obsolete_bytes_max_ratio":
2094 2 : o.ObsoleteBytesMaxRatio, err = strconv.ParseFloat(value, 64)
2095 2 : case "obsolete_bytes_timeframe":
2096 2 : o.ObsoleteBytesTimeframe, err = time.ParseDuration(value)
2097 0 : case "min_flush_rate":
2098 : // Do nothing; option existed in older versions of pebble, and
2099 : // may be meaningful again eventually.
2100 2 : case "multilevel_compaction_heuristic":
2101 2 : switch {
2102 2 : case value == "none":
2103 2 : o.Experimental.MultiLevelCompactionHeuristic = OptionNoMultiLevel
2104 2 : case strings.HasPrefix(value, "wamp"):
2105 2 : o.Experimental.MultiLevelCompactionHeuristic = OptionWriteAmpHeuristic
2106 2 : fields := strings.FieldsFunc(strings.TrimPrefix(value, "wamp"), func(r rune) bool {
2107 2 : return unicode.IsSpace(r) || r == ',' || r == '(' || r == ')'
2108 2 : })
2109 2 : if len(fields) != 2 {
2110 0 : err = errors.Newf("require 2 arguments")
2111 0 : }
2112 2 : var h WriteAmpHeuristic
2113 2 : if err == nil {
2114 2 : h.AddPropensity, err = strconv.ParseFloat(fields[0], 64)
2115 2 : }
2116 2 : if err == nil {
2117 2 : h.AllowL0, err = strconv.ParseBool(fields[1])
2118 2 : }
2119 :
2120 2 : if err == nil {
2121 2 : if h.AllowL0 || h.AddPropensity != 0 {
2122 2 : o.Experimental.MultiLevelCompactionHeuristic = func() MultiLevelHeuristic {
2123 2 : return &h
2124 2 : }
2125 : }
2126 0 : } else {
2127 0 : err = errors.Wrapf(err, "unexpected wamp heuristic arguments: %s", value)
2128 0 : }
2129 0 : default:
2130 0 : err = errors.Newf("unrecognized multilevel compaction heuristic: %s", value)
2131 : }
2132 0 : case "point_tombstone_weight":
2133 : // Do nothing; deprecated.
2134 2 : case "strict_wal_tail":
2135 2 : var strictWALTail bool
2136 2 : strictWALTail, err = strconv.ParseBool(value)
2137 2 : if err == nil && !strictWALTail {
2138 0 : err = errors.Newf("reading from versions with strict_wal_tail=false no longer supported")
2139 0 : }
2140 2 : case "merger":
2141 2 : switch value {
2142 0 : case "nullptr":
2143 0 : o.Merger = nil
2144 2 : case "pebble.concatenate":
2145 2 : o.Merger = DefaultMerger
2146 1 : default:
2147 1 : if hooks != nil && hooks.NewMerger != nil {
2148 1 : o.Merger, err = hooks.NewMerger(value)
2149 1 : }
2150 : }
2151 2 : case "read_compaction_rate":
2152 2 : o.Experimental.ReadCompactionRate, err = strconv.ParseInt(value, 10, 64)
2153 2 : case "read_sampling_multiplier":
2154 2 : o.Experimental.ReadSamplingMultiplier, err = strconv.ParseInt(value, 10, 64)
2155 2 : case "num_deletions_threshold":
2156 2 : o.Experimental.NumDeletionsThreshold, err = strconv.Atoi(value)
2157 2 : case "deletion_size_ratio_threshold":
2158 2 : val, parseErr := strconv.ParseFloat(value, 32)
2159 2 : o.Experimental.DeletionSizeRatioThreshold = float32(val)
2160 2 : err = parseErr
2161 2 : case "tombstone_dense_compaction_threshold":
2162 2 : o.Experimental.TombstoneDenseCompactionThreshold, err = strconv.ParseFloat(value, 64)
2163 2 : case "table_cache_shards":
2164 2 : o.Experimental.FileCacheShards, err = strconv.Atoi(value)
2165 0 : case "table_format":
2166 0 : switch value {
2167 0 : case "leveldb":
2168 0 : case "rocksdbv2":
2169 0 : default:
2170 0 : return errors.Errorf("pebble: unknown table format: %q", errors.Safe(value))
2171 : }
2172 1 : case "table_property_collectors":
2173 : // No longer implemented; ignore.
2174 2 : case "validate_on_ingest":
2175 2 : o.Experimental.ValidateOnIngest, err = strconv.ParseBool(value)
2176 2 : case "wal_dir":
2177 2 : o.WALDir = value
2178 2 : case "wal_bytes_per_sync":
2179 2 : o.WALBytesPerSync, err = strconv.Atoi(value)
2180 1 : case "max_writer_concurrency":
2181 : // No longer implemented; ignore.
2182 1 : case "force_writer_parallelism":
2183 : // No longer implemented; ignore.
2184 2 : case "secondary_cache_size_bytes":
2185 2 : o.Experimental.SecondaryCacheSizeBytes, err = strconv.ParseInt(value, 10, 64)
2186 2 : case "create_on_shared":
2187 2 : var createOnSharedInt int64
2188 2 : createOnSharedInt, err = strconv.ParseInt(value, 10, 64)
2189 2 : o.Experimental.CreateOnShared = remote.CreateOnSharedStrategy(createOnSharedInt)
2190 0 : default:
2191 0 : if hooks != nil && hooks.SkipUnknown != nil && hooks.SkipUnknown(section+"."+key, value) {
2192 0 : return nil
2193 0 : }
2194 0 : return errors.Errorf("pebble: unknown option: %s.%s",
2195 0 : errors.Safe(section), errors.Safe(key))
2196 : }
2197 2 : return err
2198 :
2199 2 : case section == "Value Separation":
2200 2 : var err error
2201 2 : switch key {
2202 2 : case "enabled":
2203 2 : valSepPolicy.Enabled, err = strconv.ParseBool(value)
2204 2 : case "minimum_size":
2205 2 : var minimumSize int
2206 2 : minimumSize, err = strconv.Atoi(value)
2207 2 : valSepPolicy.MinimumSize = minimumSize
2208 2 : case "max_blob_reference_depth":
2209 2 : valSepPolicy.MaxBlobReferenceDepth, err = strconv.Atoi(value)
2210 2 : case "rewrite_minimum_age":
2211 2 : valSepPolicy.RewriteMinimumAge, err = time.ParseDuration(value)
2212 2 : case "target_garbage_ratio":
2213 2 : valSepPolicy.TargetGarbageRatio, err = strconv.ParseFloat(value, 64)
2214 0 : default:
2215 0 : if hooks != nil && hooks.SkipUnknown != nil && hooks.SkipUnknown(section+"."+key, value) {
2216 0 : return nil
2217 0 : }
2218 0 : return errors.Errorf("pebble: unknown option: %s.%s", errors.Safe(section), errors.Safe(key))
2219 : }
2220 2 : return err
2221 :
2222 2 : case section == "WAL Failover":
2223 2 : if o.WALFailover == nil {
2224 2 : o.WALFailover = new(WALFailoverOptions)
2225 2 : }
2226 2 : var err error
2227 2 : switch key {
2228 2 : case "secondary_dir":
2229 2 : o.WALFailover.Secondary = wal.Dir{Dirname: value, FS: vfs.Default}
2230 2 : case "primary_dir_probe_interval":
2231 2 : o.WALFailover.PrimaryDirProbeInterval, err = time.ParseDuration(value)
2232 2 : case "healthy_probe_latency_threshold":
2233 2 : o.WALFailover.HealthyProbeLatencyThreshold, err = time.ParseDuration(value)
2234 2 : case "healthy_interval":
2235 2 : o.WALFailover.HealthyInterval, err = time.ParseDuration(value)
2236 2 : case "unhealthy_sampling_interval":
2237 2 : o.WALFailover.UnhealthySamplingInterval, err = time.ParseDuration(value)
2238 2 : case "unhealthy_operation_latency_threshold":
2239 2 : var threshold time.Duration
2240 2 : threshold, err = time.ParseDuration(value)
2241 2 : o.WALFailover.UnhealthyOperationLatencyThreshold = func() (time.Duration, bool) {
2242 2 : return threshold, true
2243 2 : }
2244 2 : case "elevated_write_stall_threshold_lag":
2245 2 : o.WALFailover.ElevatedWriteStallThresholdLag, err = time.ParseDuration(value)
2246 0 : default:
2247 0 : if hooks != nil && hooks.SkipUnknown != nil && hooks.SkipUnknown(section+"."+key, value) {
2248 0 : return nil
2249 0 : }
2250 0 : return errors.Errorf("pebble: unknown option: %s.%s",
2251 0 : errors.Safe(section), errors.Safe(key))
2252 : }
2253 2 : return err
2254 :
2255 2 : case strings.HasPrefix(section, "Level "):
2256 2 : m := regexp.MustCompile(`Level\s*"?(\d+)"?\s*$`).FindStringSubmatch(section)
2257 2 : if m == nil {
2258 0 : return errors.Errorf("pebble: unknown section: %q", errors.Safe(section))
2259 0 : }
2260 2 : index, _ := strconv.Atoi(m[1])
2261 2 :
2262 2 : l := &o.Levels[index]
2263 2 :
2264 2 : var err error
2265 2 : switch key {
2266 2 : case "block_restart_interval":
2267 2 : l.BlockRestartInterval, err = strconv.Atoi(value)
2268 2 : case "block_size":
2269 2 : l.BlockSize, err = strconv.Atoi(value)
2270 2 : case "block_size_threshold":
2271 2 : l.BlockSizeThreshold, err = strconv.Atoi(value)
2272 2 : case "compression":
2273 2 : profile := block.CompressionProfileByName(value)
2274 2 : if profile == nil {
2275 0 : return errors.Errorf("pebble: unknown compression: %q", errors.Safe(value))
2276 0 : }
2277 2 : l.Compression = func() *sstable.CompressionProfile { return profile }
2278 2 : case "filter_policy":
2279 2 : if hooks != nil && hooks.NewFilterPolicy != nil {
2280 2 : l.FilterPolicy, err = hooks.NewFilterPolicy(value)
2281 2 : } else {
2282 1 : l.FilterPolicy = NoFilterPolicy
2283 1 : }
2284 2 : case "filter_type":
2285 2 : switch value {
2286 2 : case "table":
2287 2 : l.FilterType = TableFilter
2288 0 : default:
2289 0 : return errors.Errorf("pebble: unknown filter type: %q", errors.Safe(value))
2290 : }
2291 2 : case "index_block_size":
2292 2 : l.IndexBlockSize, err = strconv.Atoi(value)
2293 2 : case "target_file_size":
2294 2 : o.TargetFileSizes[index], err = strconv.ParseInt(value, 10, 64)
2295 0 : default:
2296 0 : if hooks != nil && hooks.SkipUnknown != nil && hooks.SkipUnknown(section+"."+key, value) {
2297 0 : return nil
2298 0 : }
2299 0 : return errors.Errorf("pebble: unknown option: %s.%s", errors.Safe(section), errors.Safe(key))
2300 : }
2301 2 : return err
2302 : }
2303 2 : if hooks != nil && hooks.SkipUnknown != nil && hooks.SkipUnknown(section+"."+key, value) {
2304 2 : return nil
2305 2 : }
2306 0 : return errors.Errorf("pebble: unknown section %q or key %q", errors.Safe(section), errors.Safe(key))
2307 : }
2308 2 : err := parseOptions(s, parseOptionsFuncs{
2309 2 : visitKeyValue: visitKeyValue,
2310 2 : })
2311 2 : if err != nil {
2312 1 : return err
2313 1 : }
2314 2 : o.Experimental.ValueSeparationPolicy = func() ValueSeparationPolicy { return valSepPolicy }
2315 2 : if concurrencyLimit.lowerSet || concurrencyLimit.upperSet {
2316 2 : if !concurrencyLimit.lowerSet {
2317 1 : concurrencyLimit.lower = 1
2318 2 : } else if concurrencyLimit.lower < 1 {
2319 0 : return errors.New("baseline_concurrent_compactions cannot be <= 0")
2320 0 : }
2321 2 : if !concurrencyLimit.upperSet {
2322 1 : concurrencyLimit.upper = concurrencyLimit.lower
2323 2 : } else if concurrencyLimit.upper < concurrencyLimit.lower {
2324 0 : return errors.Newf("max_concurrent_compactions cannot be < %d", concurrencyLimit.lower)
2325 0 : }
2326 2 : o.CompactionConcurrencyRange = func() (int, int) {
2327 2 : return concurrencyLimit.lower, concurrencyLimit.upper
2328 2 : }
2329 : }
2330 2 : return nil
2331 : }
2332 :
2333 : // ErrMissingWALRecoveryDir is an error returned when a database is attempted to be
2334 : // opened without supplying a Options.WALRecoveryDir entry for a directory that
2335 : // may contain WALs required to recover a consistent database state.
2336 : type ErrMissingWALRecoveryDir struct {
2337 : Dir string
2338 : ExtraInfo string
2339 : }
2340 :
2341 : // Error implements error.
2342 1 : func (e ErrMissingWALRecoveryDir) Error() string {
2343 1 : return fmt.Sprintf("directory %q may contain relevant WALs but is not in WALRecoveryDirs%s", e.Dir, e.ExtraInfo)
2344 1 : }
2345 :
2346 : // CheckCompatibility verifies the options are compatible with the previous options
2347 : // serialized by Options.String(). For example, the Comparer and Merger must be
2348 : // the same, or data will not be able to be properly read from the DB.
2349 : //
2350 : // This function only looks at specific keys and does not error out if the
2351 : // options are newer and contain unknown keys.
2352 2 : func (o *Options) CheckCompatibility(storeDir string, previousOptions string) error {
2353 2 : previousWALDir := ""
2354 2 :
2355 2 : visitKeyValue := func(i, j int, section, key, value string) error {
2356 2 : switch section + "." + key {
2357 2 : case "Options.comparer":
2358 2 : if value != o.Comparer.Name {
2359 1 : return errors.Errorf("pebble: comparer name from file %q != comparer name from options %q",
2360 1 : errors.Safe(value), errors.Safe(o.Comparer.Name))
2361 1 : }
2362 2 : case "Options.merger":
2363 2 : // RocksDB allows the merge operator to be unspecified, in which case it
2364 2 : // shows up as "nullptr".
2365 2 : if value != "nullptr" && value != o.Merger.Name {
2366 1 : return errors.Errorf("pebble: merger name from file %q != merger name from options %q",
2367 1 : errors.Safe(value), errors.Safe(o.Merger.Name))
2368 1 : }
2369 2 : case "Options.wal_dir":
2370 2 : previousWALDir = value
2371 2 : case "WAL Failover.secondary_dir":
2372 2 : previousWALSecondaryDir := value
2373 2 : if err := o.checkWALDir(storeDir, previousWALSecondaryDir, "WALFailover.Secondary changed from previous options"); err != nil {
2374 1 : return err
2375 1 : }
2376 : }
2377 2 : return nil
2378 : }
2379 2 : if err := parseOptions(previousOptions, parseOptionsFuncs{visitKeyValue: visitKeyValue}); err != nil {
2380 1 : return err
2381 1 : }
2382 2 : if err := o.checkWALDir(storeDir, previousWALDir, "WALDir changed from previous options"); err != nil {
2383 1 : return err
2384 1 : }
2385 2 : return nil
2386 : }
2387 :
2388 : // checkWALDir verifies that walDir is among o.WALDir, o.WALFailover.Secondary,
2389 : // or o.WALRecoveryDirs. An empty "walDir" maps to the storeDir.
2390 2 : func (o *Options) checkWALDir(storeDir, walDir, errContext string) error {
2391 2 : walPath := resolveStorePath(storeDir, walDir)
2392 2 : if walDir == "" {
2393 2 : walPath = storeDir
2394 2 : }
2395 :
2396 2 : if o.WALDir == "" {
2397 2 : if walPath == storeDir {
2398 2 : return nil
2399 2 : }
2400 2 : } else {
2401 2 : if walPath == resolveStorePath(storeDir, o.WALDir) {
2402 2 : return nil
2403 2 : }
2404 : }
2405 :
2406 2 : if o.WALFailover != nil && walPath == resolveStorePath(storeDir, o.WALFailover.Secondary.Dirname) {
2407 2 : return nil
2408 2 : }
2409 :
2410 1 : for _, d := range o.WALRecoveryDirs {
2411 1 : // TODO(radu): should we also check that d.FS is the same as walDir's FS?
2412 1 : if walPath == resolveStorePath(storeDir, d.Dirname) {
2413 1 : return nil
2414 1 : }
2415 : }
2416 :
2417 1 : var buf bytes.Buffer
2418 1 : fmt.Fprintf(&buf, "\n %s\n", errContext)
2419 1 : fmt.Fprintf(&buf, " o.WALDir: %q\n", o.WALDir)
2420 1 : if o.WALFailover != nil {
2421 0 : fmt.Fprintf(&buf, " o.WALFailover.Secondary.Dirname: %q\n", o.WALFailover.Secondary.Dirname)
2422 0 : }
2423 1 : fmt.Fprintf(&buf, " o.WALRecoveryDirs: %d", len(o.WALRecoveryDirs))
2424 1 : for _, d := range o.WALRecoveryDirs {
2425 0 : fmt.Fprintf(&buf, "\n %q", d.Dirname)
2426 0 : }
2427 1 : return ErrMissingWALRecoveryDir{Dir: walPath, ExtraInfo: buf.String()}
2428 : }
2429 :
2430 : // Validate verifies that the options are mutually consistent. For example,
2431 : // L0StopWritesThreshold must be >= L0CompactionThreshold, otherwise a write
2432 : // stall would persist indefinitely.
2433 2 : func (o *Options) Validate() error {
2434 2 : // Note that we can presume Options.EnsureDefaults has been called, so there
2435 2 : // is no need to check for zero values.
2436 2 :
2437 2 : var buf strings.Builder
2438 2 : if o.Experimental.L0CompactionConcurrency < 1 {
2439 1 : fmt.Fprintf(&buf, "L0CompactionConcurrency (%d) must be >= 1\n",
2440 1 : o.Experimental.L0CompactionConcurrency)
2441 1 : }
2442 2 : if o.L0StopWritesThreshold < o.L0CompactionThreshold {
2443 1 : fmt.Fprintf(&buf, "L0StopWritesThreshold (%d) must be >= L0CompactionThreshold (%d)\n",
2444 1 : o.L0StopWritesThreshold, o.L0CompactionThreshold)
2445 1 : }
2446 2 : if uint64(o.MemTableSize) >= maxMemTableSize {
2447 1 : fmt.Fprintf(&buf, "MemTableSize (%s) must be < %s\n",
2448 1 : humanize.Bytes.Uint64(uint64(o.MemTableSize)), humanize.Bytes.Uint64(maxMemTableSize))
2449 1 : }
2450 2 : if o.MemTableStopWritesThreshold < 2 {
2451 1 : fmt.Fprintf(&buf, "MemTableStopWritesThreshold (%d) must be >= 2\n",
2452 1 : o.MemTableStopWritesThreshold)
2453 1 : }
2454 2 : if o.FormatMajorVersion < FormatMinSupported || o.FormatMajorVersion > internalFormatNewest {
2455 0 : fmt.Fprintf(&buf, "FormatMajorVersion (%d) must be between %d and %d\n",
2456 0 : o.FormatMajorVersion, FormatMinSupported, internalFormatNewest)
2457 0 : }
2458 2 : if o.Experimental.CreateOnShared != remote.CreateOnSharedNone && o.FormatMajorVersion < FormatMinForSharedObjects {
2459 0 : fmt.Fprintf(&buf, "FormatMajorVersion (%d) when CreateOnShared is set must be at least %d\n",
2460 0 : o.FormatMajorVersion, FormatMinForSharedObjects)
2461 0 : }
2462 2 : if len(o.KeySchemas) > 0 {
2463 2 : if o.KeySchema == "" {
2464 0 : fmt.Fprintf(&buf, "KeySchemas is set but KeySchema is not\n")
2465 0 : }
2466 2 : if _, ok := o.KeySchemas[o.KeySchema]; !ok {
2467 0 : fmt.Fprintf(&buf, "KeySchema %q not found in KeySchemas\n", o.KeySchema)
2468 0 : }
2469 : }
2470 2 : if policy := o.Experimental.ValueSeparationPolicy(); policy.Enabled {
2471 2 : if policy.MinimumSize <= 0 {
2472 0 : fmt.Fprintf(&buf, "ValueSeparationPolicy.MinimumSize (%d) must be > 0\n", policy.MinimumSize)
2473 0 : }
2474 2 : if policy.MaxBlobReferenceDepth <= 0 {
2475 0 : fmt.Fprintf(&buf, "ValueSeparationPolicy.MaxBlobReferenceDepth (%d) must be > 0\n", policy.MaxBlobReferenceDepth)
2476 0 : }
2477 : }
2478 :
2479 2 : if buf.Len() == 0 {
2480 2 : return nil
2481 2 : }
2482 1 : return errors.New(buf.String())
2483 : }
2484 :
2485 : // MakeReaderOptions constructs sstable.ReaderOptions from the corresponding
2486 : // options in the receiver.
2487 2 : func (o *Options) MakeReaderOptions() sstable.ReaderOptions {
2488 2 : var readerOpts sstable.ReaderOptions
2489 2 : if o != nil {
2490 2 : readerOpts.Comparer = o.Comparer
2491 2 : readerOpts.Filters = o.Filters
2492 2 : readerOpts.KeySchemas = o.KeySchemas
2493 2 : readerOpts.LoadBlockSema = o.LoadBlockSema
2494 2 : readerOpts.LoggerAndTracer = o.LoggerAndTracer
2495 2 : readerOpts.Merger = o.Merger
2496 2 : }
2497 2 : return readerOpts
2498 : }
2499 :
2500 : // MakeWriterOptions constructs sstable.WriterOptions for the specified level
2501 : // from the corresponding options in the receiver.
2502 2 : func (o *Options) MakeWriterOptions(level int, format sstable.TableFormat) sstable.WriterOptions {
2503 2 : var writerOpts sstable.WriterOptions
2504 2 : writerOpts.TableFormat = format
2505 2 : if o != nil {
2506 2 : writerOpts.Comparer = o.Comparer
2507 2 : if o.Merger != nil {
2508 2 : writerOpts.MergerName = o.Merger.Name
2509 2 : }
2510 2 : writerOpts.BlockPropertyCollectors = o.BlockPropertyCollectors
2511 : }
2512 2 : if format >= sstable.TableFormatPebblev3 {
2513 2 : writerOpts.ShortAttributeExtractor = o.Experimental.ShortAttributeExtractor
2514 2 : if format >= sstable.TableFormatPebblev4 && level == numLevels-1 {
2515 2 : writerOpts.WritingToLowestLevel = true
2516 2 : }
2517 : }
2518 2 : levelOpts := o.Levels[level]
2519 2 : writerOpts.BlockRestartInterval = levelOpts.BlockRestartInterval
2520 2 : writerOpts.BlockSize = levelOpts.BlockSize
2521 2 : writerOpts.BlockSizeThreshold = levelOpts.BlockSizeThreshold
2522 2 : writerOpts.Compression = levelOpts.Compression()
2523 2 : writerOpts.FilterPolicy = levelOpts.FilterPolicy
2524 2 : writerOpts.FilterType = levelOpts.FilterType
2525 2 : writerOpts.IndexBlockSize = levelOpts.IndexBlockSize
2526 2 : if o.KeySchema != "" {
2527 2 : var ok bool
2528 2 : writerOpts.KeySchema, ok = o.KeySchemas[o.KeySchema]
2529 2 : if !ok {
2530 0 : panic(fmt.Sprintf("invalid schema %q", redact.Safe(o.KeySchema)))
2531 : }
2532 : }
2533 2 : writerOpts.AllocatorSizeClasses = o.AllocatorSizeClasses
2534 2 : writerOpts.NumDeletionsThreshold = o.Experimental.NumDeletionsThreshold
2535 2 : writerOpts.DeletionSizeRatioThreshold = o.Experimental.DeletionSizeRatioThreshold
2536 2 : return writerOpts
2537 : }
2538 :
2539 : // MakeBlobWriterOptions constructs blob.FileWriterOptions from the corresponding
2540 : // options in the receiver.
2541 2 : func (o *Options) MakeBlobWriterOptions(level int, format blob.FileFormat) blob.FileWriterOptions {
2542 2 : lo := o.Levels[level]
2543 2 : return blob.FileWriterOptions{
2544 2 : Format: format,
2545 2 : Compression: lo.Compression(),
2546 2 : ChecksumType: block.ChecksumTypeCRC32c,
2547 2 : FlushGovernor: block.MakeFlushGovernor(
2548 2 : lo.BlockSize,
2549 2 : lo.BlockSizeThreshold,
2550 2 : base.SizeClassAwareBlockSizeThreshold,
2551 2 : o.AllocatorSizeClasses,
2552 2 : ),
2553 2 : }
2554 2 : }
2555 :
2556 2 : func (o *Options) MakeObjStorageProviderSettings(dirname string) objstorageprovider.Settings {
2557 2 : s := objstorageprovider.Settings{
2558 2 : Logger: o.Logger,
2559 2 : FS: o.FS,
2560 2 : FSDirName: dirname,
2561 2 : FSCleaner: o.Cleaner,
2562 2 : NoSyncOnClose: o.NoSyncOnClose,
2563 2 : BytesPerSync: o.BytesPerSync,
2564 2 : }
2565 2 : s.Local.ReadaheadConfig = o.Local.ReadaheadConfig
2566 2 : s.Remote.StorageFactory = o.Experimental.RemoteStorage
2567 2 : s.Remote.CreateOnShared = o.Experimental.CreateOnShared
2568 2 : s.Remote.CreateOnSharedLocator = o.Experimental.CreateOnSharedLocator
2569 2 : s.Remote.CacheSizeBytes = o.Experimental.SecondaryCacheSizeBytes
2570 2 : return s
2571 2 : }
2572 :
2573 : // UserKeyCategories describes a partitioning of the user key space. Each
2574 : // partition is a category with a name. The categories are used for informative
2575 : // purposes only (like pprof labels). Pebble does not treat keys differently
2576 : // based on the UserKeyCategories.
2577 : //
2578 : // The partitions are defined by their upper bounds. The last partition is
2579 : // assumed to go until the end of keyspace; its UpperBound is ignored. The rest
2580 : // of the partitions are ordered by their UpperBound.
2581 : type UserKeyCategories struct {
2582 : categories []UserKeyCategory
2583 : cmp base.Compare
2584 : // rangeNames[i][j] contains the string referring to the categories in the
2585 : // range [i, j], with j > i.
2586 : rangeNames [][]string
2587 : }
2588 :
2589 : // UserKeyCategory describes a partition of the user key space.
2590 : //
2591 : // User keys >= the previous category's UpperBound and < this category's
2592 : // UpperBound are part of this category.
2593 : type UserKeyCategory struct {
2594 : Name string
2595 : // UpperBound is the exclusive upper bound of the category. All user keys >= the
2596 : // previous category's UpperBound and < this UpperBound are part of this
2597 : // category.
2598 : UpperBound []byte
2599 : }
2600 :
2601 : // MakeUserKeyCategories creates a UserKeyCategories object with the given
2602 : // categories. The object is immutable and can be reused across different
2603 : // stores.
2604 1 : func MakeUserKeyCategories(cmp base.Compare, categories ...UserKeyCategory) UserKeyCategories {
2605 1 : n := len(categories)
2606 1 : if n == 0 {
2607 0 : return UserKeyCategories{}
2608 0 : }
2609 1 : if categories[n-1].UpperBound != nil {
2610 0 : panic("last category UpperBound must be nil")
2611 : }
2612 : // Verify that the partitions are ordered as expected.
2613 1 : for i := 1; i < n-1; i++ {
2614 1 : if cmp(categories[i-1].UpperBound, categories[i].UpperBound) >= 0 {
2615 0 : panic("invalid UserKeyCategories: key prefixes must be sorted")
2616 : }
2617 : }
2618 :
2619 : // Precalculate a table of range names to avoid allocations in the
2620 : // categorization path.
2621 1 : rangeNamesBuf := make([]string, n*n)
2622 1 : rangeNames := make([][]string, n)
2623 1 : for i := range rangeNames {
2624 1 : rangeNames[i] = rangeNamesBuf[:n]
2625 1 : rangeNamesBuf = rangeNamesBuf[n:]
2626 1 : for j := i + 1; j < n; j++ {
2627 1 : rangeNames[i][j] = categories[i].Name + "-" + categories[j].Name
2628 1 : }
2629 : }
2630 1 : return UserKeyCategories{
2631 1 : categories: categories,
2632 1 : cmp: cmp,
2633 1 : rangeNames: rangeNames,
2634 1 : }
2635 : }
2636 :
2637 : // Len returns the number of categories defined.
2638 2 : func (kc *UserKeyCategories) Len() int {
2639 2 : return len(kc.categories)
2640 2 : }
2641 :
2642 : // CategorizeKey returns the name of the category containing the key.
2643 1 : func (kc *UserKeyCategories) CategorizeKey(userKey []byte) string {
2644 1 : idx := sort.Search(len(kc.categories)-1, func(i int) bool {
2645 1 : return kc.cmp(userKey, kc.categories[i].UpperBound) < 0
2646 1 : })
2647 1 : return kc.categories[idx].Name
2648 : }
2649 :
2650 : // CategorizeKeyRange returns the name of the category containing the key range.
2651 : // If the key range spans multiple categories, the result shows the first and
2652 : // last category separated by a dash, e.g. `cat1-cat5`.
2653 1 : func (kc *UserKeyCategories) CategorizeKeyRange(startUserKey, endUserKey []byte) string {
2654 1 : n := len(kc.categories)
2655 1 : p := sort.Search(n-1, func(i int) bool {
2656 1 : return kc.cmp(startUserKey, kc.categories[i].UpperBound) < 0
2657 1 : })
2658 1 : if p == n-1 || kc.cmp(endUserKey, kc.categories[p].UpperBound) < 0 {
2659 1 : // Fast path for a single category.
2660 1 : return kc.categories[p].Name
2661 1 : }
2662 : // Binary search among the remaining categories.
2663 1 : q := p + 1 + sort.Search(n-2-p, func(i int) bool {
2664 1 : return kc.cmp(endUserKey, kc.categories[p+1+i].UpperBound) < 0
2665 1 : })
2666 1 : return kc.rangeNames[p][q]
2667 : }
2668 :
2669 : const storePathIdentifier = "{store_path}"
2670 :
2671 : // MakeStoreRelativePath takes a path that is relative to the store directory
2672 : // and creates a path that can be used for Options.WALDir and wal.Dir.Dirname.
2673 : //
2674 : // This is used in metamorphic tests, so that the test run directory can be
2675 : // copied or moved.
2676 1 : func MakeStoreRelativePath(fs vfs.FS, relativePath string) string {
2677 1 : if relativePath == "" {
2678 0 : return storePathIdentifier
2679 0 : }
2680 1 : return fs.PathJoin(storePathIdentifier, relativePath)
2681 : }
2682 :
2683 : // resolveStorePath is the inverse of MakeStoreRelativePath(). It replaces any
2684 : // storePathIdentifier prefix with the store dir.
2685 2 : func resolveStorePath(storeDir, path string) string {
2686 2 : if remainder, ok := strings.CutPrefix(path, storePathIdentifier); ok {
2687 2 : return storeDir + remainder
2688 2 : }
2689 2 : return path
2690 : }
|