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