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