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 : "strconv"
13 : "strings"
14 : "time"
15 : "unicode"
16 :
17 : "github.com/cockroachdb/crlib/fifo"
18 : "github.com/cockroachdb/errors"
19 : "github.com/cockroachdb/pebble/internal/base"
20 : "github.com/cockroachdb/pebble/internal/cache"
21 : "github.com/cockroachdb/pebble/internal/humanize"
22 : "github.com/cockroachdb/pebble/internal/keyspan"
23 : "github.com/cockroachdb/pebble/internal/manifest"
24 : "github.com/cockroachdb/pebble/internal/testkeys"
25 : "github.com/cockroachdb/pebble/objstorage/objstorageprovider"
26 : "github.com/cockroachdb/pebble/objstorage/remote"
27 : "github.com/cockroachdb/pebble/rangekey"
28 : "github.com/cockroachdb/pebble/sstable"
29 : "github.com/cockroachdb/pebble/sstable/block"
30 : "github.com/cockroachdb/pebble/sstable/colblk"
31 : "github.com/cockroachdb/pebble/vfs"
32 : "github.com/cockroachdb/pebble/wal"
33 : )
34 :
35 : const (
36 : cacheDefaultSize = 8 << 20 // 8 MB
37 : defaultLevelMultiplier = 10
38 : )
39 :
40 : // Compression exports the base.Compression type.
41 : type Compression = block.Compression
42 :
43 : // Exported Compression constants.
44 : const (
45 : DefaultCompression = block.DefaultCompression
46 : NoCompression = block.NoCompression
47 : SnappyCompression = block.SnappyCompression
48 : ZstdCompression = block.ZstdCompression
49 : )
50 :
51 : // FilterType exports the base.FilterType type.
52 : type FilterType = base.FilterType
53 :
54 : // Exported TableFilter constants.
55 : const (
56 : TableFilter = base.TableFilter
57 : )
58 :
59 : // FilterWriter exports the base.FilterWriter type.
60 : type FilterWriter = base.FilterWriter
61 :
62 : // FilterPolicy exports the base.FilterPolicy type.
63 : type FilterPolicy = base.FilterPolicy
64 :
65 : // KeySchema exports the colblk.KeySchema type.
66 : type KeySchema = colblk.KeySchema
67 :
68 : // BlockPropertyCollector exports the sstable.BlockPropertyCollector type.
69 : type BlockPropertyCollector = sstable.BlockPropertyCollector
70 :
71 : // BlockPropertyFilter exports the sstable.BlockPropertyFilter type.
72 : type BlockPropertyFilter = base.BlockPropertyFilter
73 :
74 : // ShortAttributeExtractor exports the base.ShortAttributeExtractor type.
75 : type ShortAttributeExtractor = base.ShortAttributeExtractor
76 :
77 : // UserKeyPrefixBound exports the sstable.UserKeyPrefixBound type.
78 : type UserKeyPrefixBound = sstable.UserKeyPrefixBound
79 :
80 : // CompactionLimiter exports the base.CompactionLimiter type.
81 : type CompactionLimiter = base.CompactionLimiter
82 :
83 : // CompactionSlot exports the base.CompactionSlot type.
84 : type CompactionSlot = base.CompactionSlot
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 1 : func (t IterKeyType) String() string {
103 1 : switch t {
104 1 : case IterKeyTypePointsOnly:
105 1 : return "points-only"
106 1 : case IterKeyTypeRangesOnly:
107 1 : return "ranges-only"
108 1 : case IterKeyTypePointsAndRanges:
109 1 : 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 sstable.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 2 : func (o *IterOptions) GetLowerBound() []byte {
222 2 : if o == nil {
223 2 : return nil
224 2 : }
225 2 : return o.LowerBound
226 : }
227 :
228 : // GetUpperBound returns the UpperBound or nil if the receiver is nil.
229 2 : func (o *IterOptions) GetUpperBound() []byte {
230 2 : if o == nil {
231 2 : return nil
232 2 : }
233 2 : return o.UpperBound
234 : }
235 :
236 2 : func (o *IterOptions) pointKeys() bool {
237 2 : if o == nil {
238 0 : return true
239 0 : }
240 2 : return o.KeyTypes == IterKeyTypePointsOnly || o.KeyTypes == IterKeyTypePointsAndRanges
241 : }
242 :
243 2 : func (o *IterOptions) rangeKeys() bool {
244 2 : if o == nil {
245 0 : return false
246 0 : }
247 2 : return o.KeyTypes == IterKeyTypeRangesOnly || o.KeyTypes == IterKeyTypePointsAndRanges
248 : }
249 :
250 2 : func (o *IterOptions) getLogger() Logger {
251 2 : if o == nil || o.logger == nil {
252 2 : return DefaultLogger
253 2 : }
254 2 : return o.logger
255 : }
256 :
257 : // SpanIterOptions creates a SpanIterOptions from this IterOptions.
258 2 : func (o *IterOptions) SpanIterOptions() keyspan.SpanIterOptions {
259 2 : if o == nil {
260 2 : return keyspan.SpanIterOptions{}
261 2 : }
262 2 : return keyspan.SpanIterOptions{
263 2 : RangeKeyFilters: o.RangeKeyFilters,
264 2 : }
265 : }
266 :
267 : // scanInternalOptions is similar to IterOptions, meant for use with
268 : // scanInternalIterator.
269 : type scanInternalOptions struct {
270 : IterOptions
271 :
272 : category sstable.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 2 : func (o *WriteOptions) GetSync() bool {
389 2 : return o == nil || o.Sync
390 2 : }
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 2 : func (o *LevelOptions) EnsureDefaults() *LevelOptions {
452 2 : if o == nil {
453 0 : o = &LevelOptions{}
454 0 : }
455 2 : if o.BlockRestartInterval <= 0 {
456 1 : o.BlockRestartInterval = base.DefaultBlockRestartInterval
457 1 : }
458 2 : if o.BlockSize <= 0 {
459 1 : o.BlockSize = base.DefaultBlockSize
460 2 : } else if o.BlockSize > sstable.MaximumBlockSize {
461 0 : panic(errors.Errorf("BlockSize %d exceeds MaximumBlockSize", o.BlockSize))
462 : }
463 2 : if o.BlockSizeThreshold <= 0 {
464 1 : o.BlockSizeThreshold = base.DefaultBlockSizeThreshold
465 1 : }
466 2 : if o.Compression == nil {
467 1 : o.Compression = func() Compression { return DefaultCompression }
468 : }
469 2 : if o.IndexBlockSize <= 0 {
470 1 : o.IndexBlockSize = o.BlockSize
471 1 : }
472 2 : if o.TargetFileSize <= 0 {
473 1 : o.TargetFileSize = 2 << 20 // 2 MB
474 1 : }
475 2 : return o
476 : }
477 :
478 : // Options holds the optional parameters for configuring pebble. These options
479 : // apply to the DB at large; per-query options are defined by the IterOptions
480 : // and WriteOptions types.
481 : type Options struct {
482 : // Sync sstables periodically in order to smooth out writes to disk. This
483 : // option does not provide any persistency guarantee, but is used to avoid
484 : // latency spikes if the OS automatically decides to write out a large chunk
485 : // of dirty filesystem buffers. This option only controls SSTable syncs; WAL
486 : // syncs are controlled by WALBytesPerSync.
487 : //
488 : // The default value is 512KB.
489 : BytesPerSync int
490 :
491 : // Cache is used to cache uncompressed blocks from sstables.
492 : //
493 : // The default cache size is 8 MB.
494 : Cache *cache.Cache
495 :
496 : // LoadBlockSema, if set, is used to limit the number of blocks that can be
497 : // loaded (i.e. read from the filesystem) in parallel. Each load acquires one
498 : // unit from the semaphore for the duration of the read.
499 : LoadBlockSema *fifo.Semaphore
500 :
501 : // Cleaner cleans obsolete files.
502 : //
503 : // The default cleaner uses the DeleteCleaner.
504 : Cleaner Cleaner
505 :
506 : // Local contains option that pertain to files stored on the local filesystem.
507 : Local struct {
508 : // ReadaheadConfig is used to retrieve the current readahead mode; it is
509 : // consulted whenever a read handle is initialized.
510 : ReadaheadConfig *ReadaheadConfig
511 :
512 : // TODO(radu): move BytesPerSync, LoadBlockSema, Cleaner here.
513 : }
514 :
515 : // Comparer defines a total ordering over the space of []byte keys: a 'less
516 : // than' relationship. The same comparison algorithm must be used for reads
517 : // and writes over the lifetime of the DB.
518 : //
519 : // The default value uses the same ordering as bytes.Compare.
520 : Comparer *Comparer
521 :
522 : // DebugCheck is invoked, if non-nil, whenever a new version is being
523 : // installed. Typically, this is set to pebble.DebugCheckLevels in tests
524 : // or tools only, to check invariants over all the data in the database.
525 : DebugCheck func(*DB) error
526 :
527 : // Disable the write-ahead log (WAL). Disabling the write-ahead log prohibits
528 : // crash recovery, but can improve performance if crash recovery is not
529 : // needed (e.g. when only temporary state is being stored in the database).
530 : //
531 : // TODO(peter): untested
532 : DisableWAL bool
533 :
534 : // ErrorIfExists causes an error on Open if the database already exists.
535 : // The error can be checked with errors.Is(err, ErrDBAlreadyExists).
536 : //
537 : // The default value is false.
538 : ErrorIfExists bool
539 :
540 : // ErrorIfNotExists causes an error on Open if the database does not already
541 : // exist. The error can be checked with errors.Is(err, ErrDBDoesNotExist).
542 : //
543 : // The default value is false which will cause a database to be created if it
544 : // does not already exist.
545 : ErrorIfNotExists bool
546 :
547 : // ErrorIfNotPristine causes an error on Open if the database already exists
548 : // and any operations have been performed on the database. The error can be
549 : // checked with errors.Is(err, ErrDBNotPristine).
550 : //
551 : // Note that a database that contained keys that were all subsequently deleted
552 : // may or may not trigger the error. Currently, we check if there are any live
553 : // SSTs or log records to replay.
554 : ErrorIfNotPristine bool
555 :
556 : // EventListener provides hooks to listening to significant DB events such as
557 : // flushes, compactions, and table deletion.
558 : EventListener *EventListener
559 :
560 : // Experimental contains experimental options which are off by default.
561 : // These options are temporary and will eventually either be deleted, moved
562 : // out of the experimental group, or made the non-adjustable default. These
563 : // options may change at any time, so do not rely on them.
564 : Experimental struct {
565 : // The threshold of L0 read-amplification at which compaction concurrency
566 : // is enabled (if CompactionDebtConcurrency was not already exceeded).
567 : // Every multiple of this value enables another concurrent
568 : // compaction up to MaxConcurrentCompactions.
569 : L0CompactionConcurrency int
570 :
571 : // CompactionDebtConcurrency controls the threshold of compaction debt
572 : // at which additional compaction concurrency slots are added. For every
573 : // multiple of this value in compaction debt bytes, an additional
574 : // concurrent compaction is added. This works "on top" of
575 : // L0CompactionConcurrency, so the higher of the count of compaction
576 : // concurrency slots as determined by the two options is chosen.
577 : CompactionDebtConcurrency uint64
578 :
579 : // IngestSplit, if it returns true, allows for ingest-time splitting of
580 : // existing sstables into two virtual sstables to allow ingestion sstables to
581 : // slot into a lower level than they otherwise would have.
582 : IngestSplit func() bool
583 :
584 : // ReadCompactionRate controls the frequency of read triggered
585 : // compactions by adjusting `AllowedSeeks` in manifest.FileMetadata:
586 : //
587 : // AllowedSeeks = FileSize / ReadCompactionRate
588 : //
589 : // From LevelDB:
590 : // ```
591 : // We arrange to automatically compact this file after
592 : // a certain number of seeks. Let's assume:
593 : // (1) One seek costs 10ms
594 : // (2) Writing or reading 1MB costs 10ms (100MB/s)
595 : // (3) A compaction of 1MB does 25MB of IO:
596 : // 1MB read from this level
597 : // 10-12MB read from next level (boundaries may be misaligned)
598 : // 10-12MB written to next level
599 : // This implies that 25 seeks cost the same as the compaction
600 : // of 1MB of data. I.e., one seek costs approximately the
601 : // same as the compaction of 40KB of data. We are a little
602 : // conservative and allow approximately one seek for every 16KB
603 : // of data before triggering a compaction.
604 : // ```
605 : ReadCompactionRate int64
606 :
607 : // ReadSamplingMultiplier is a multiplier for the readSamplingPeriod in
608 : // iterator.maybeSampleRead() to control the frequency of read sampling
609 : // to trigger a read triggered compaction. A value of -1 prevents sampling
610 : // and disables read triggered compactions. The default is 1 << 4. which
611 : // gets multiplied with a constant of 1 << 16 to yield 1 << 20 (1MB).
612 : ReadSamplingMultiplier int64
613 :
614 : // NumDeletionsThreshold defines the minimum number of point tombstones
615 : // that must be present in a single data block for that block to be
616 : // considered tombstone-dense for the purposes of triggering a
617 : // tombstone density compaction. Data blocks may also be considered
618 : // tombstone-dense if they meet the criteria defined by
619 : // DeletionSizeRatioThreshold below. Tombstone-dense blocks are identified
620 : // when sstables are written, and so this is effectively an option for
621 : // sstable writers. The default value is 100.
622 : NumDeletionsThreshold int
623 :
624 : // DeletionSizeRatioThreshold defines the minimum ratio of the size of
625 : // point tombstones to the size of a data block that must be reached
626 : // for that block to be considered tombstone-dense for the purposes of
627 : // triggering a tombstone density compaction. Data blocks may also be
628 : // considered tombstone-dense if they meet the criteria defined by
629 : // NumDeletionsThreshold above. Tombstone-dense blocks are identified
630 : // when sstables are written, and so this is effectively an option for
631 : // sstable writers. The default value is 0.5.
632 : DeletionSizeRatioThreshold float32
633 :
634 : // TombstoneDenseCompactionThreshold is the minimum percent of data
635 : // blocks in a table that must be tombstone-dense for that table to be
636 : // eligible for a tombstone density compaction. It should be defined as a
637 : // ratio out of 1. The default value is 0.10.
638 : //
639 : // If multiple tables are eligible for a tombstone density compaction, then
640 : // tables with a higher percent of tombstone-dense blocks are still
641 : // prioritized for compaction.
642 : //
643 : // A zero or negative value disables tombstone density compactions.
644 : TombstoneDenseCompactionThreshold float64
645 :
646 : // FileCacheShards is the number of shards per file cache.
647 : // Reducing the value can reduce the number of idle goroutines per DB
648 : // instance which can be useful in scenarios with a lot of DB instances
649 : // and a large number of CPUs, but doing so can lead to higher contention
650 : // in the file cache and reduced performance.
651 : //
652 : // The default value is the number of logical CPUs, which can be
653 : // limited by runtime.GOMAXPROCS.
654 : FileCacheShards int
655 :
656 : // KeyValidationFunc is a function to validate a user key in an SSTable.
657 : //
658 : // Currently, this function is used to validate the smallest and largest
659 : // keys in an SSTable undergoing compaction. In this case, returning an
660 : // error from the validation function will result in a panic at runtime,
661 : // given that there is rarely any way of recovering from malformed keys
662 : // present in compacted files. By default, validation is not performed.
663 : //
664 : // Additional use-cases may be added in the future.
665 : //
666 : // NOTE: callers should take care to not mutate the key being validated.
667 : KeyValidationFunc func(userKey []byte) error
668 :
669 : // ValidateOnIngest schedules validation of sstables after they have
670 : // been ingested.
671 : //
672 : // By default, this value is false.
673 : ValidateOnIngest bool
674 :
675 : // LevelMultiplier configures the size multiplier used to determine the
676 : // desired size of each level of the LSM. Defaults to 10.
677 : LevelMultiplier int
678 :
679 : // MultiLevelCompactionHeuristic determines whether to add an additional
680 : // level to a conventional two level compaction. If nil, a multilevel
681 : // compaction will never get triggered.
682 : MultiLevelCompactionHeuristic MultiLevelHeuristic
683 :
684 : // MaxWriterConcurrency is used to indicate the maximum number of
685 : // compression workers the compression queue is allowed to use. If
686 : // MaxWriterConcurrency > 0, then the Writer will use parallelism, to
687 : // compress and write blocks to disk. Otherwise, the writer will
688 : // compress and write blocks to disk synchronously.
689 : MaxWriterConcurrency int
690 :
691 : // ForceWriterParallelism is used to force parallelism in the sstable
692 : // Writer for the metamorphic tests. Even with the MaxWriterConcurrency
693 : // option set, we only enable parallelism in the sstable Writer if there
694 : // is enough CPU available, and this option bypasses that.
695 : ForceWriterParallelism bool
696 :
697 : // CPUWorkPermissionGranter should be set if Pebble should be given the
698 : // ability to optionally schedule additional CPU. See the documentation
699 : // for CPUWorkPermissionGranter for more details.
700 : CPUWorkPermissionGranter CPUWorkPermissionGranter
701 :
702 : // EnableColumnarBlocks is used to decide whether to enable writing
703 : // TableFormatPebblev5 sstables. This setting is only respected by
704 : // FormatColumnarBlocks. In lower format major versions, the
705 : // TableFormatPebblev5 format is prohibited. If EnableColumnarBlocks is
706 : // nil and the DB is at FormatColumnarBlocks, the DB defaults to not
707 : // writing columnar blocks.
708 : EnableColumnarBlocks func() bool
709 :
710 : // EnableValueBlocks is used to decide whether to enable writing
711 : // TableFormatPebblev3 sstables. This setting is only respected by a
712 : // specific subset of format major versions: FormatSSTableValueBlocks,
713 : // FormatFlushableIngest and FormatPrePebblev1MarkedCompacted. In lower
714 : // format major versions, value blocks are never enabled. In higher
715 : // format major versions, value blocks are always enabled.
716 : EnableValueBlocks func() bool
717 :
718 : // ShortAttributeExtractor is used iff EnableValueBlocks() returns true
719 : // (else ignored). If non-nil, a ShortAttribute can be extracted from the
720 : // value and stored with the key, when the value is stored elsewhere.
721 : ShortAttributeExtractor ShortAttributeExtractor
722 :
723 : // RequiredInPlaceValueBound specifies an optional span of user key
724 : // prefixes that are not-MVCC, but have a suffix. For these the values
725 : // must be stored with the key, since the concept of "older versions" is
726 : // not defined. It is also useful for statically known exclusions to value
727 : // separation. In CockroachDB, this will be used for the lock table key
728 : // space that has non-empty suffixes, but those locks don't represent
729 : // actual MVCC versions (the suffix ordering is arbitrary). We will also
730 : // need to add support for dynamically configured exclusions (we want the
731 : // default to be to allow Pebble to decide whether to separate the value
732 : // or not, hence this is structured as exclusions), for example, for users
733 : // of CockroachDB to dynamically exclude certain tables.
734 : //
735 : // Any change in exclusion behavior takes effect only on future written
736 : // sstables, and does not start rewriting existing sstables.
737 : //
738 : // Even ignoring changes in this setting, exclusions are interpreted as a
739 : // guidance by Pebble, and not necessarily honored. Specifically, user
740 : // keys with multiple Pebble-versions *may* have the older versions stored
741 : // in value blocks.
742 : RequiredInPlaceValueBound UserKeyPrefixBound
743 :
744 : // DisableIngestAsFlushable disables lazy ingestion of sstables through
745 : // a WAL write and memtable rotation. Only effectual if the format
746 : // major version is at least `FormatFlushableIngest`.
747 : DisableIngestAsFlushable func() bool
748 :
749 : // RemoteStorage enables use of remote storage (e.g. S3) for storing
750 : // sstables. Setting this option enables use of CreateOnShared option and
751 : // allows ingestion of external files.
752 : RemoteStorage remote.StorageFactory
753 :
754 : // If CreateOnShared is non-zero, new sstables are created on remote storage
755 : // (using CreateOnSharedLocator and with the appropriate
756 : // CreateOnSharedStrategy). These sstables can be shared between different
757 : // Pebble instances; the lifecycle of such objects is managed by the
758 : // remote.Storage constructed by options.RemoteStorage.
759 : //
760 : // Can only be used when RemoteStorage is set (and recognizes
761 : // CreateOnSharedLocator).
762 : CreateOnShared remote.CreateOnSharedStrategy
763 : CreateOnSharedLocator remote.Locator
764 :
765 : // CacheSizeBytesBytes is the size of the on-disk block cache for objects
766 : // on shared storage in bytes. If it is 0, no cache is used.
767 : SecondaryCacheSizeBytes int64
768 :
769 : // NB: DO NOT crash on SingleDeleteInvariantViolationCallback or
770 : // IneffectualSingleDeleteCallback, since these can be false positives
771 : // even if SingleDel has been used correctly.
772 : //
773 : // Pebble's delete-only compactions can cause a recent RANGEDEL to peek
774 : // below an older SINGLEDEL and delete an arbitrary subset of data below
775 : // that SINGLEDEL. When that SINGLEDEL gets compacted (without the
776 : // RANGEDEL), any of these callbacks can happen, without it being a real
777 : // correctness problem.
778 : //
779 : // Example 1:
780 : // RANGEDEL [a, c)#10 in L0
781 : // SINGLEDEL b#5 in L1
782 : // SET b#3 in L6
783 : //
784 : // If the L6 file containing the SET is narrow and the L1 file containing
785 : // the SINGLEDEL is wide, a delete-only compaction can remove the file in
786 : // L2 before the SINGLEDEL is compacted down. Then when the SINGLEDEL is
787 : // compacted down, it will not find any SET to delete, resulting in the
788 : // ineffectual callback.
789 : //
790 : // Example 2:
791 : // RANGEDEL [a, z)#60 in L0
792 : // SINGLEDEL g#50 in L1
793 : // SET g#40 in L2
794 : // RANGEDEL [g,h)#30 in L3
795 : // SET g#20 in L6
796 : //
797 : // In this example, the two SETs represent the same user write, and the
798 : // RANGEDELs are caused by the CockroachDB range being dropped. That is,
799 : // the user wrote to g once, range was dropped, then added back, which
800 : // caused the SET again, then at some point g was validly deleted using a
801 : // SINGLEDEL, and then the range was dropped again. The older RANGEDEL can
802 : // get fragmented due to compactions it has been part of. Say this L3 file
803 : // containing the RANGEDEL is very narrow, while the L1, L2, L6 files are
804 : // wider than the RANGEDEL in L0. Then the RANGEDEL in L3 can be dropped
805 : // using a delete-only compaction, resulting in an LSM with state:
806 : //
807 : // RANGEDEL [a, z)#60 in L0
808 : // SINGLEDEL g#50 in L1
809 : // SET g#40 in L2
810 : // SET g#20 in L6
811 : //
812 : // A multi-level compaction involving L1, L2, L6 will cause the invariant
813 : // violation callback. This example doesn't need multi-level compactions:
814 : // say there was a Pebble snapshot at g#21 preventing g#20 from being
815 : // dropped when it meets g#40 in a compaction. That snapshot will not save
816 : // RANGEDEL [g,h)#30, so we can have:
817 : //
818 : // SINGLEDEL g#50 in L1
819 : // SET g#40, SET g#20 in L6
820 : //
821 : // And say the snapshot is removed and then the L1 and L6 compaction
822 : // happens, resulting in the invariant violation callback.
823 : //
824 : // TODO(sumeer): rename SingleDeleteInvariantViolationCallback to remove
825 : // the word "invariant".
826 :
827 : // IneffectualPointDeleteCallback is called in compactions/flushes if any
828 : // single delete is being elided without deleting a point set/merge.
829 : IneffectualSingleDeleteCallback func(userKey []byte)
830 :
831 : // SingleDeleteInvariantViolationCallback is called in compactions/flushes if any
832 : // single delete has consumed a Set/Merge, and there is another immediately older
833 : // Set/SetWithDelete/Merge. The user of Pebble has violated the invariant under
834 : // which SingleDelete can be used correctly.
835 : //
836 : // Consider the sequence SingleDelete#3, Set#2, Set#1. There are three
837 : // ways some of these keys can first meet in a compaction.
838 : //
839 : // - All 3 keys in the same compaction: this callback will detect the
840 : // violation.
841 : //
842 : // - SingleDelete#3, Set#2 meet in a compaction first: Both keys will
843 : // disappear. The violation will not be detected, and the DB will have
844 : // Set#1 which is likely incorrect (from the user's perspective).
845 : //
846 : // - Set#2, Set#1 meet in a compaction first: The output will be Set#2,
847 : // which will later be consumed by SingleDelete#3. The violation will
848 : // not be detected and the DB will be correct.
849 : SingleDeleteInvariantViolationCallback func(userKey []byte)
850 :
851 : // EnableDeleteOnlyCompactionExcises enables delete-only compactions to also
852 : // apply delete-only compaction hints on sstables that partially overlap
853 : // with it. This application happens through an excise, similar to
854 : // the excise phase of IngestAndExcise.
855 : EnableDeleteOnlyCompactionExcises func() bool
856 :
857 : // CompactionLimiter, if set, is used to limit concurrent compactions as well
858 : // as to pace compactions and flushing compactions already chosen. If nil,
859 : // no limiting or pacing happens other than that controlled by other options
860 : // like L0CompactionConcurrency and CompactionDebtConcurrency.
861 : CompactionLimiter CompactionLimiter
862 : }
863 :
864 : // Filters is a map from filter policy name to filter policy. It is used for
865 : // debugging tools which may be used on multiple databases configured with
866 : // different filter policies. It is not necessary to populate this filters
867 : // map during normal usage of a DB (it will be done automatically by
868 : // EnsureDefaults).
869 : Filters map[string]FilterPolicy
870 :
871 : // FlushDelayDeleteRange configures how long the database should wait before
872 : // forcing a flush of a memtable that contains a range deletion. Disk space
873 : // cannot be reclaimed until the range deletion is flushed. No automatic
874 : // flush occurs if zero.
875 : FlushDelayDeleteRange time.Duration
876 :
877 : // FlushDelayRangeKey configures how long the database should wait before
878 : // forcing a flush of a memtable that contains a range key. Range keys in
879 : // the memtable prevent lazy combined iteration, so it's desirable to flush
880 : // range keys promptly. No automatic flush occurs if zero.
881 : FlushDelayRangeKey time.Duration
882 :
883 : // FlushSplitBytes denotes the target number of bytes per sublevel in
884 : // each flush split interval (i.e. range between two flush split keys)
885 : // in L0 sstables. When set to zero, only a single sstable is generated
886 : // by each flush. When set to a non-zero value, flushes are split at
887 : // points to meet L0's TargetFileSize, any grandparent-related overlap
888 : // options, and at boundary keys of L0 flush split intervals (which are
889 : // targeted to contain around FlushSplitBytes bytes in each sublevel
890 : // between pairs of boundary keys). Splitting sstables during flush
891 : // allows increased compaction flexibility and concurrency when those
892 : // tables are compacted to lower levels.
893 : FlushSplitBytes int64
894 :
895 : // FormatMajorVersion sets the format of on-disk files. It is
896 : // recommended to set the format major version to an explicit
897 : // version, as the default may change over time.
898 : //
899 : // At Open if the existing database is formatted using a later
900 : // format major version that is known to this version of Pebble,
901 : // Pebble will continue to use the later format major version. If
902 : // the existing database's version is unknown, the caller may use
903 : // FormatMostCompatible and will be able to open the database
904 : // regardless of its actual version.
905 : //
906 : // If the existing database is formatted using a format major
907 : // version earlier than the one specified, Open will automatically
908 : // ratchet the database to the specified format major version.
909 : FormatMajorVersion FormatMajorVersion
910 :
911 : // FS provides the interface for persistent file storage.
912 : //
913 : // The default value uses the underlying operating system's file system.
914 : FS vfs.FS
915 :
916 : // KeySchema is the name of the key schema that should be used when writing
917 : // new sstables. There must be a key schema with this name defined in
918 : // KeySchemas. If not set, colblk.DefaultKeySchema is used to construct a
919 : // default key schema.
920 : KeySchema string
921 :
922 : // KeySchemas defines the set of known schemas of user keys. When columnar
923 : // blocks are in use (see FormatColumnarBlocks), the user may specify how a
924 : // key should be decomposed into columns. Each KeySchema must have a unique
925 : // name. The schema named by Options.KeySchema is used while writing
926 : // sstables during flushes and compactions.
927 : //
928 : // Multiple KeySchemas may be used over the lifetime of a database. Once a
929 : // KeySchema is used, it must be provided in KeySchemas in subsequent calls
930 : // to Open for perpetuity.
931 : KeySchemas sstable.KeySchemas
932 :
933 : // Lock, if set, must be a database lock acquired through LockDirectory for
934 : // the same directory passed to Open. If provided, Open will skip locking
935 : // the directory. Closing the database will not release the lock, and it's
936 : // the responsibility of the caller to release the lock after closing the
937 : // database.
938 : //
939 : // Open will enforce that the Lock passed locks the same directory passed to
940 : // Open. Concurrent calls to Open using the same Lock are detected and
941 : // prohibited.
942 : Lock *Lock
943 :
944 : // The count of L0 files necessary to trigger an L0 compaction.
945 : L0CompactionFileThreshold int
946 :
947 : // The amount of L0 read-amplification necessary to trigger an L0 compaction.
948 : L0CompactionThreshold int
949 :
950 : // Hard limit on L0 read-amplification, computed as the number of L0
951 : // sublevels. Writes are stopped when this threshold is reached.
952 : L0StopWritesThreshold int
953 :
954 : // The maximum number of bytes for LBase. The base level is the level which
955 : // L0 is compacted into. The base level is determined dynamically based on
956 : // the existing data in the LSM. The maximum number of bytes for other levels
957 : // is computed dynamically based on the base level's maximum size. When the
958 : // maximum number of bytes for a level is exceeded, compaction is requested.
959 : LBaseMaxBytes int64
960 :
961 : // Per-level options. Options for at least one level must be specified. The
962 : // options for the last level are used for all subsequent levels.
963 : Levels []LevelOptions
964 :
965 : // LoggerAndTracer will be used, if non-nil, else Logger will be used and
966 : // tracing will be a noop.
967 :
968 : // Logger used to write log messages.
969 : //
970 : // The default logger uses the Go standard library log package.
971 : Logger Logger
972 : // LoggerAndTracer is used for writing log messages and traces.
973 : LoggerAndTracer LoggerAndTracer
974 :
975 : // MaxManifestFileSize is the maximum size the MANIFEST file is allowed to
976 : // become. When the MANIFEST exceeds this size it is rolled over and a new
977 : // MANIFEST is created.
978 : MaxManifestFileSize int64
979 :
980 : // MaxOpenFiles is a soft limit on the number of open files that can be
981 : // used by the DB.
982 : //
983 : // The default value is 1000.
984 : MaxOpenFiles int
985 :
986 : // The size of a MemTable in steady state. The actual MemTable size starts at
987 : // min(256KB, MemTableSize) and doubles for each subsequent MemTable up to
988 : // MemTableSize. This reduces the memory pressure caused by MemTables for
989 : // short lived (test) DB instances. Note that more than one MemTable can be
990 : // in existence since flushing a MemTable involves creating a new one and
991 : // writing the contents of the old one in the
992 : // background. MemTableStopWritesThreshold places a hard limit on the size of
993 : // the queued MemTables.
994 : //
995 : // The default value is 4MB.
996 : MemTableSize uint64
997 :
998 : // Hard limit on the number of queued of MemTables. Writes are stopped when
999 : // the sum of the queued memtable sizes exceeds:
1000 : // MemTableStopWritesThreshold * MemTableSize.
1001 : //
1002 : // This value should be at least 2 or writes will stop whenever a MemTable is
1003 : // being flushed.
1004 : //
1005 : // The default value is 2.
1006 : MemTableStopWritesThreshold int
1007 :
1008 : // Merger defines the associative merge operation to use for merging values
1009 : // written with {Batch,DB}.Merge.
1010 : //
1011 : // The default merger concatenates values.
1012 : Merger *Merger
1013 :
1014 : // MaxConcurrentCompactions specifies the maximum number of concurrent
1015 : // compactions (not including download compactions).
1016 : //
1017 : // Concurrent compactions are performed:
1018 : // - when L0 read-amplification passes the L0CompactionConcurrency threshold;
1019 : // - for automatic background compactions;
1020 : // - when a manual compaction for a level is split and parallelized.
1021 : //
1022 : // MaxConcurrentCompactions() must be greater than 0.
1023 : //
1024 : // The default value is 1.
1025 : MaxConcurrentCompactions func() int
1026 :
1027 : // MaxConcurrentDownloads specifies the maximum number of download
1028 : // compactions. These are compactions that copy an external file to the local
1029 : // store.
1030 : //
1031 : // This limit is independent of MaxConcurrentCompactions; at any point in
1032 : // time, we may be running MaxConcurrentCompactions non-download compactions
1033 : // and MaxConcurrentDownloads download compactions.
1034 : //
1035 : // MaxConcurrentDownloads() must be greater than 0.
1036 : //
1037 : // The default value is 1.
1038 : MaxConcurrentDownloads func() int
1039 :
1040 : // DisableAutomaticCompactions dictates whether automatic compactions are
1041 : // scheduled or not. The default is false (enabled). This option is only used
1042 : // externally when running a manual compaction, and internally for tests.
1043 : DisableAutomaticCompactions bool
1044 :
1045 : // DisableConsistencyCheck disables the consistency check that is performed on
1046 : // open. Should only be used when a database cannot be opened normally (e.g.
1047 : // some of the tables don't exist / aren't accessible).
1048 : DisableConsistencyCheck bool
1049 :
1050 : // DisableTableStats dictates whether tables should be loaded asynchronously
1051 : // to compute statistics that inform compaction heuristics. The collection
1052 : // of table stats improves compaction of tombstones, reclaiming disk space
1053 : // more quickly and in some cases reducing write amplification in the
1054 : // presence of tombstones. Disabling table stats may be useful in tests
1055 : // that require determinism as the asynchronicity of table stats collection
1056 : // introduces significant nondeterminism.
1057 : DisableTableStats bool
1058 :
1059 : // NoSyncOnClose decides whether the Pebble instance will enforce a
1060 : // close-time synchronization (e.g., fdatasync() or sync_file_range())
1061 : // on files it writes to. Setting this to true removes the guarantee for a
1062 : // sync on close. Some implementations can still issue a non-blocking sync.
1063 : NoSyncOnClose bool
1064 :
1065 : // NumPrevManifest is the number of non-current or older manifests which
1066 : // we want to keep around for debugging purposes. By default, we're going
1067 : // to keep one older manifest.
1068 : NumPrevManifest int
1069 :
1070 : // ReadOnly indicates that the DB should be opened in read-only mode. Writes
1071 : // to the DB will return an error, background compactions are disabled, and
1072 : // the flush that normally occurs after replaying the WAL at startup is
1073 : // disabled.
1074 : ReadOnly bool
1075 :
1076 : // FileCache is an initialized FileCache which should be set as an
1077 : // option if the DB needs to be initialized with a pre-existing file cache.
1078 : // If FileCache is nil, then a file cache which is unique to the DB instance
1079 : // is created. FileCache can be shared between db instances by setting it here.
1080 : // The FileCache set here must use the same underlying cache as Options.Cache
1081 : // and pebble will panic otherwise.
1082 : FileCache *FileCache
1083 :
1084 : // BlockPropertyCollectors is a list of BlockPropertyCollector creation
1085 : // functions. A new BlockPropertyCollector is created for each sstable
1086 : // built and lives for the lifetime of writing that table.
1087 : BlockPropertyCollectors []func() BlockPropertyCollector
1088 :
1089 : // WALBytesPerSync sets the number of bytes to write to a WAL before calling
1090 : // Sync on it in the background. Just like with BytesPerSync above, this
1091 : // helps smooth out disk write latencies, and avoids cases where the OS
1092 : // writes a lot of buffered data to disk at once. However, this is less
1093 : // necessary with WALs, as many write operations already pass in
1094 : // Sync = true.
1095 : //
1096 : // The default value is 0, i.e. no background syncing. This matches the
1097 : // default behaviour in RocksDB.
1098 : WALBytesPerSync int
1099 :
1100 : // WALDir specifies the directory to store write-ahead logs (WALs) in. If
1101 : // empty (the default), WALs will be stored in the same directory as sstables
1102 : // (i.e. the directory passed to pebble.Open).
1103 : WALDir string
1104 :
1105 : // WALFailover may be set to configure Pebble to monitor writes to its
1106 : // write-ahead log and failover to writing write-ahead log entries to a
1107 : // secondary location (eg, a separate physical disk). WALFailover may be
1108 : // used to improve write availability in the presence of transient disk
1109 : // unavailability.
1110 : WALFailover *WALFailoverOptions
1111 :
1112 : // WALRecoveryDirs is a list of additional directories that should be
1113 : // scanned for the existence of additional write-ahead logs. WALRecoveryDirs
1114 : // is expected to be used when starting Pebble with a new WALDir or a new
1115 : // WALFailover configuration. The directories associated with the previous
1116 : // configuration may still contain WALs that are required for recovery of
1117 : // the current database state.
1118 : //
1119 : // If a previous WAL configuration may have stored WALs elsewhere but there
1120 : // is not a corresponding entry in WALRecoveryDirs, Open will error.
1121 : WALRecoveryDirs []wal.Dir
1122 :
1123 : // WALMinSyncInterval is the minimum duration between syncs of the WAL. If
1124 : // WAL syncs are requested faster than this interval, they will be
1125 : // artificially delayed. Introducing a small artificial delay (500us) between
1126 : // WAL syncs can allow more operations to arrive and reduce IO operations
1127 : // while having a minimal impact on throughput. This option is supplied as a
1128 : // closure in order to allow the value to be changed dynamically. The default
1129 : // value is 0.
1130 : //
1131 : // TODO(peter): rather than a closure, should there be another mechanism for
1132 : // changing options dynamically?
1133 : WALMinSyncInterval func() time.Duration
1134 :
1135 : // TargetByteDeletionRate is the rate (in bytes per second) at which sstable file
1136 : // deletions are limited to (under normal circumstances).
1137 : //
1138 : // Deletion pacing is used to slow down deletions when compactions finish up
1139 : // or readers close and newly-obsolete files need cleaning up. Deleting lots
1140 : // of files at once can cause disk latency to go up on some SSDs, which this
1141 : // functionality guards against.
1142 : //
1143 : // This value is only a best-effort target; the effective rate can be
1144 : // higher if deletions are falling behind or disk space is running low.
1145 : //
1146 : // Setting this to 0 disables deletion pacing, which is also the default.
1147 : TargetByteDeletionRate int
1148 :
1149 : // EnableSQLRowSpillMetrics specifies whether the Pebble instance will only be used
1150 : // to temporarily persist data spilled to disk for row-oriented SQL query execution.
1151 : EnableSQLRowSpillMetrics bool
1152 :
1153 : // AllocatorSizeClasses provides a sorted list containing the supported size
1154 : // classes of the underlying memory allocator. This provides hints to the
1155 : // sstable block writer's flushing policy to select block sizes that
1156 : // preemptively reduce internal fragmentation when loaded into the block cache.
1157 : AllocatorSizeClasses []int
1158 :
1159 : // private options are only used by internal tests or are used internally
1160 : // for facilitating upgrade paths of unconfigurable functionality.
1161 : private struct {
1162 : // disableDeleteOnlyCompactions prevents the scheduling of delete-only
1163 : // compactions that drop sstables wholy covered by range tombstones or
1164 : // range key tombstones.
1165 : disableDeleteOnlyCompactions bool
1166 :
1167 : // disableElisionOnlyCompactions prevents the scheduling of elision-only
1168 : // compactions that rewrite sstables in place in order to elide obsolete
1169 : // keys.
1170 : disableElisionOnlyCompactions bool
1171 :
1172 : // disableLazyCombinedIteration is a private option used by the
1173 : // metamorphic tests to test equivalence between lazy-combined iteration
1174 : // and constructing the range-key iterator upfront. It's a private
1175 : // option to avoid littering the public interface with options that we
1176 : // do not want to allow users to actually configure.
1177 : disableLazyCombinedIteration bool
1178 :
1179 : // testingAlwaysWaitForCleanup is set by some tests to force waiting for
1180 : // obsolete file deletion (to make events deterministic).
1181 : testingAlwaysWaitForCleanup bool
1182 :
1183 : // fsCloser holds a closer that should be invoked after a DB using these
1184 : // Options is closed. This is used to automatically stop the
1185 : // long-running goroutine associated with the disk-health-checking FS.
1186 : // See the initialization of FS in EnsureDefaults. Note that care has
1187 : // been taken to ensure that it is still safe to continue using the FS
1188 : // after this closer has been invoked. However, if write operations
1189 : // against the FS are made after the DB is closed, the FS may leak a
1190 : // goroutine indefinitely.
1191 : fsCloser io.Closer
1192 : }
1193 : }
1194 :
1195 : // WALFailoverOptions configures the WAL failover mechanics to use during
1196 : // transient write unavailability on the primary WAL volume.
1197 : type WALFailoverOptions struct {
1198 : // Secondary indicates the secondary directory and VFS to use in the event a
1199 : // write to the primary WAL stalls.
1200 : Secondary wal.Dir
1201 : // FailoverOptions provides configuration of the thresholds and intervals
1202 : // involved in WAL failover. If any of its fields are left unspecified,
1203 : // reasonable defaults will be used.
1204 : wal.FailoverOptions
1205 : }
1206 :
1207 : // ReadaheadConfig controls the use of read-ahead.
1208 : type ReadaheadConfig = objstorageprovider.ReadaheadConfig
1209 :
1210 : // JemallocSizeClasses exports sstable.JemallocSizeClasses.
1211 : var JemallocSizeClasses = sstable.JemallocSizeClasses
1212 :
1213 : // DebugCheckLevels calls CheckLevels on the provided database.
1214 : // It may be set in the DebugCheck field of Options to check
1215 : // level invariants whenever a new version is installed.
1216 2 : func DebugCheckLevels(db *DB) error {
1217 2 : return db.CheckLevels(nil)
1218 2 : }
1219 :
1220 : // EnsureDefaults ensures that the default values for all options are set if a
1221 : // valid value was not already specified. Returns the new options.
1222 2 : func (o *Options) EnsureDefaults() *Options {
1223 2 : if o == nil {
1224 1 : o = &Options{}
1225 1 : }
1226 2 : o.Comparer = o.Comparer.EnsureDefaults()
1227 2 :
1228 2 : if o.BytesPerSync <= 0 {
1229 1 : o.BytesPerSync = 512 << 10 // 512 KB
1230 1 : }
1231 2 : if o.Cleaner == nil {
1232 1 : o.Cleaner = DeleteCleaner{}
1233 1 : }
1234 :
1235 2 : if o.Experimental.DisableIngestAsFlushable == nil {
1236 2 : o.Experimental.DisableIngestAsFlushable = func() bool { return false }
1237 : }
1238 2 : if o.Experimental.L0CompactionConcurrency <= 0 {
1239 1 : o.Experimental.L0CompactionConcurrency = 10
1240 1 : }
1241 2 : if o.Experimental.CompactionDebtConcurrency <= 0 {
1242 1 : o.Experimental.CompactionDebtConcurrency = 1 << 30 // 1 GB
1243 1 : }
1244 2 : if o.Experimental.CompactionLimiter == nil {
1245 2 : o.Experimental.CompactionLimiter = &base.DefaultCompactionLimiter{}
1246 2 : }
1247 2 : if o.Experimental.KeyValidationFunc == nil {
1248 2 : o.Experimental.KeyValidationFunc = func([]byte) error { return nil }
1249 : }
1250 2 : if o.KeySchema == "" && len(o.KeySchemas) == 0 {
1251 1 : ks := colblk.DefaultKeySchema(o.Comparer, 16 /* bundleSize */)
1252 1 : o.KeySchema = ks.Name
1253 1 : o.KeySchemas = sstable.MakeKeySchemas(&ks)
1254 1 : }
1255 2 : if o.L0CompactionThreshold <= 0 {
1256 1 : o.L0CompactionThreshold = 4
1257 1 : }
1258 2 : if o.L0CompactionFileThreshold <= 0 {
1259 1 : // Some justification for the default of 500:
1260 1 : // Why not smaller?:
1261 1 : // - The default target file size for L0 is 2MB, so 500 files is <= 1GB
1262 1 : // of data. At observed compaction speeds of > 20MB/s, L0 can be
1263 1 : // cleared of all files in < 1min, so this backlog is not huge.
1264 1 : // - 500 files is low overhead for instantiating L0 sublevels from
1265 1 : // scratch.
1266 1 : // - Lower values were observed to cause excessive and inefficient
1267 1 : // compactions out of L0 in a TPCC import benchmark.
1268 1 : // Why not larger?:
1269 1 : // - More than 1min to compact everything out of L0.
1270 1 : // - CockroachDB's admission control system uses a threshold of 1000
1271 1 : // files to start throttling writes to Pebble. Using 500 here gives
1272 1 : // us headroom between when Pebble should start compacting L0 and
1273 1 : // when the admission control threshold is reached.
1274 1 : //
1275 1 : // We can revisit this default in the future based on better
1276 1 : // experimental understanding.
1277 1 : //
1278 1 : // TODO(jackson): Experiment with slightly lower thresholds [or higher
1279 1 : // admission control thresholds] to see whether a higher L0 score at the
1280 1 : // threshold (currently 2.0) is necessary for some workloads to avoid
1281 1 : // starving L0 in favor of lower-level compactions.
1282 1 : o.L0CompactionFileThreshold = 500
1283 1 : }
1284 2 : if o.L0StopWritesThreshold <= 0 {
1285 1 : o.L0StopWritesThreshold = 12
1286 1 : }
1287 2 : if o.LBaseMaxBytes <= 0 {
1288 1 : o.LBaseMaxBytes = 64 << 20 // 64 MB
1289 1 : }
1290 2 : if o.Levels == nil {
1291 1 : o.Levels = make([]LevelOptions, 1)
1292 1 : for i := range o.Levels {
1293 1 : if i > 0 {
1294 0 : l := &o.Levels[i]
1295 0 : if l.TargetFileSize <= 0 {
1296 0 : l.TargetFileSize = o.Levels[i-1].TargetFileSize * 2
1297 0 : }
1298 : }
1299 1 : o.Levels[i].EnsureDefaults()
1300 : }
1301 2 : } else {
1302 2 : for i := range o.Levels {
1303 2 : o.Levels[i].EnsureDefaults()
1304 2 : }
1305 : }
1306 2 : if o.Logger == nil {
1307 2 : o.Logger = DefaultLogger
1308 2 : }
1309 2 : if o.EventListener == nil {
1310 2 : o.EventListener = &EventListener{}
1311 2 : }
1312 2 : o.EventListener.EnsureDefaults(o.Logger)
1313 2 : if o.MaxManifestFileSize == 0 {
1314 1 : o.MaxManifestFileSize = 128 << 20 // 128 MB
1315 1 : }
1316 2 : if o.MaxOpenFiles == 0 {
1317 1 : o.MaxOpenFiles = 1000
1318 1 : }
1319 2 : if o.MemTableSize <= 0 {
1320 1 : o.MemTableSize = 4 << 20 // 4 MB
1321 1 : }
1322 2 : if o.MemTableStopWritesThreshold <= 0 {
1323 1 : o.MemTableStopWritesThreshold = 2
1324 1 : }
1325 2 : if o.Merger == nil {
1326 1 : o.Merger = DefaultMerger
1327 1 : }
1328 2 : if o.MaxConcurrentCompactions == nil {
1329 1 : o.MaxConcurrentCompactions = func() int { return 1 }
1330 : }
1331 2 : if o.MaxConcurrentDownloads == nil {
1332 1 : o.MaxConcurrentDownloads = func() int { return 1 }
1333 : }
1334 2 : if o.NumPrevManifest <= 0 {
1335 2 : o.NumPrevManifest = 1
1336 2 : }
1337 :
1338 2 : if o.FormatMajorVersion == FormatDefault {
1339 1 : o.FormatMajorVersion = FormatMinSupported
1340 1 : if o.Experimental.CreateOnShared != remote.CreateOnSharedNone {
1341 1 : o.FormatMajorVersion = FormatMinForSharedObjects
1342 1 : }
1343 : }
1344 :
1345 2 : if o.FS == nil {
1346 1 : o.WithFSDefaults()
1347 1 : }
1348 2 : if o.FlushSplitBytes <= 0 {
1349 1 : o.FlushSplitBytes = 2 * o.Levels[0].TargetFileSize
1350 1 : }
1351 2 : if o.WALFailover != nil {
1352 2 : o.WALFailover.FailoverOptions.EnsureDefaults()
1353 2 : }
1354 2 : if o.Experimental.LevelMultiplier <= 0 {
1355 2 : o.Experimental.LevelMultiplier = defaultLevelMultiplier
1356 2 : }
1357 2 : if o.Experimental.ReadCompactionRate == 0 {
1358 1 : o.Experimental.ReadCompactionRate = 16000
1359 1 : }
1360 2 : if o.Experimental.ReadSamplingMultiplier == 0 {
1361 1 : o.Experimental.ReadSamplingMultiplier = 1 << 4
1362 1 : }
1363 2 : if o.Experimental.NumDeletionsThreshold == 0 {
1364 1 : o.Experimental.NumDeletionsThreshold = sstable.DefaultNumDeletionsThreshold
1365 1 : }
1366 2 : if o.Experimental.DeletionSizeRatioThreshold == 0 {
1367 1 : o.Experimental.DeletionSizeRatioThreshold = sstable.DefaultDeletionSizeRatioThreshold
1368 1 : }
1369 2 : if o.Experimental.TombstoneDenseCompactionThreshold == 0 {
1370 1 : o.Experimental.TombstoneDenseCompactionThreshold = 0.10
1371 1 : }
1372 2 : if o.Experimental.FileCacheShards <= 0 {
1373 1 : o.Experimental.FileCacheShards = runtime.GOMAXPROCS(0)
1374 1 : }
1375 2 : if o.Experimental.CPUWorkPermissionGranter == nil {
1376 2 : o.Experimental.CPUWorkPermissionGranter = defaultCPUWorkGranter{}
1377 2 : }
1378 2 : if o.Experimental.MultiLevelCompactionHeuristic == nil {
1379 1 : o.Experimental.MultiLevelCompactionHeuristic = WriteAmpHeuristic{}
1380 1 : }
1381 :
1382 2 : o.initMaps()
1383 2 : return o
1384 : }
1385 :
1386 : // WithFSDefaults configures the Options to wrap the configured filesystem with
1387 : // the default virtual file system middleware, like disk-health checking.
1388 2 : func (o *Options) WithFSDefaults() *Options {
1389 2 : if o.FS == nil {
1390 1 : o.FS = vfs.Default
1391 1 : }
1392 2 : o.FS, o.private.fsCloser = vfs.WithDiskHealthChecks(o.FS, 5*time.Second, nil,
1393 2 : func(info vfs.DiskSlowInfo) {
1394 0 : o.EventListener.DiskSlow(info)
1395 0 : })
1396 2 : return o
1397 : }
1398 :
1399 : // AddEventListener adds the provided event listener to the Options, in addition
1400 : // to any existing event listener.
1401 1 : func (o *Options) AddEventListener(l EventListener) {
1402 1 : if o.EventListener != nil {
1403 1 : l = TeeEventListener(l, *o.EventListener)
1404 1 : }
1405 1 : o.EventListener = &l
1406 : }
1407 :
1408 : // initMaps initializes the Comparers, Filters, and Mergers maps.
1409 2 : func (o *Options) initMaps() {
1410 2 : for i := range o.Levels {
1411 2 : l := &o.Levels[i]
1412 2 : if l.FilterPolicy != nil {
1413 2 : if o.Filters == nil {
1414 2 : o.Filters = make(map[string]FilterPolicy)
1415 2 : }
1416 2 : name := l.FilterPolicy.Name()
1417 2 : if _, ok := o.Filters[name]; !ok {
1418 2 : o.Filters[name] = l.FilterPolicy
1419 2 : }
1420 : }
1421 : }
1422 : }
1423 :
1424 : // Level returns the LevelOptions for the specified level.
1425 2 : func (o *Options) Level(level int) LevelOptions {
1426 2 : if level < len(o.Levels) {
1427 2 : return o.Levels[level]
1428 2 : }
1429 2 : n := len(o.Levels) - 1
1430 2 : l := o.Levels[n]
1431 2 : for i := n; i < level; i++ {
1432 2 : l.TargetFileSize *= 2
1433 2 : }
1434 2 : return l
1435 : }
1436 :
1437 : // Clone creates a shallow-copy of the supplied options.
1438 2 : func (o *Options) Clone() *Options {
1439 2 : n := &Options{}
1440 2 : if o != nil {
1441 2 : *n = *o
1442 2 : }
1443 2 : return n
1444 : }
1445 :
1446 2 : func filterPolicyName(p FilterPolicy) string {
1447 2 : if p == nil {
1448 2 : return "none"
1449 2 : }
1450 2 : return p.Name()
1451 : }
1452 :
1453 2 : func (o *Options) String() string {
1454 2 : var buf bytes.Buffer
1455 2 :
1456 2 : cacheSize := int64(cacheDefaultSize)
1457 2 : if o.Cache != nil {
1458 2 : cacheSize = o.Cache.MaxSize()
1459 2 : }
1460 :
1461 2 : fmt.Fprintf(&buf, "[Version]\n")
1462 2 : fmt.Fprintf(&buf, " pebble_version=0.1\n")
1463 2 : fmt.Fprintf(&buf, "\n")
1464 2 : fmt.Fprintf(&buf, "[Options]\n")
1465 2 : fmt.Fprintf(&buf, " bytes_per_sync=%d\n", o.BytesPerSync)
1466 2 : fmt.Fprintf(&buf, " cache_size=%d\n", cacheSize)
1467 2 : fmt.Fprintf(&buf, " cleaner=%s\n", o.Cleaner)
1468 2 : fmt.Fprintf(&buf, " compaction_debt_concurrency=%d\n", o.Experimental.CompactionDebtConcurrency)
1469 2 : fmt.Fprintf(&buf, " comparer=%s\n", o.Comparer.Name)
1470 2 : fmt.Fprintf(&buf, " disable_wal=%t\n", o.DisableWAL)
1471 2 : if o.Experimental.DisableIngestAsFlushable != nil && o.Experimental.DisableIngestAsFlushable() {
1472 2 : fmt.Fprintf(&buf, " disable_ingest_as_flushable=%t\n", true)
1473 2 : }
1474 2 : if o.Experimental.EnableColumnarBlocks != nil && o.Experimental.EnableColumnarBlocks() {
1475 2 : fmt.Fprintf(&buf, " enable_columnar_blocks=%t\n", true)
1476 2 : }
1477 2 : fmt.Fprintf(&buf, " flush_delay_delete_range=%s\n", o.FlushDelayDeleteRange)
1478 2 : fmt.Fprintf(&buf, " flush_delay_range_key=%s\n", o.FlushDelayRangeKey)
1479 2 : fmt.Fprintf(&buf, " flush_split_bytes=%d\n", o.FlushSplitBytes)
1480 2 : fmt.Fprintf(&buf, " format_major_version=%d\n", o.FormatMajorVersion)
1481 2 : fmt.Fprintf(&buf, " key_schema=%s\n", o.KeySchema)
1482 2 : fmt.Fprintf(&buf, " l0_compaction_concurrency=%d\n", o.Experimental.L0CompactionConcurrency)
1483 2 : fmt.Fprintf(&buf, " l0_compaction_file_threshold=%d\n", o.L0CompactionFileThreshold)
1484 2 : fmt.Fprintf(&buf, " l0_compaction_threshold=%d\n", o.L0CompactionThreshold)
1485 2 : fmt.Fprintf(&buf, " l0_stop_writes_threshold=%d\n", o.L0StopWritesThreshold)
1486 2 : fmt.Fprintf(&buf, " lbase_max_bytes=%d\n", o.LBaseMaxBytes)
1487 2 : if o.Experimental.LevelMultiplier != defaultLevelMultiplier {
1488 2 : fmt.Fprintf(&buf, " level_multiplier=%d\n", o.Experimental.LevelMultiplier)
1489 2 : }
1490 2 : fmt.Fprintf(&buf, " max_concurrent_compactions=%d\n", o.MaxConcurrentCompactions())
1491 2 : fmt.Fprintf(&buf, " max_concurrent_downloads=%d\n", o.MaxConcurrentDownloads())
1492 2 : fmt.Fprintf(&buf, " max_manifest_file_size=%d\n", o.MaxManifestFileSize)
1493 2 : fmt.Fprintf(&buf, " max_open_files=%d\n", o.MaxOpenFiles)
1494 2 : fmt.Fprintf(&buf, " mem_table_size=%d\n", o.MemTableSize)
1495 2 : fmt.Fprintf(&buf, " mem_table_stop_writes_threshold=%d\n", o.MemTableStopWritesThreshold)
1496 2 : fmt.Fprintf(&buf, " min_deletion_rate=%d\n", o.TargetByteDeletionRate)
1497 2 : fmt.Fprintf(&buf, " merger=%s\n", o.Merger.Name)
1498 2 : if o.Experimental.MultiLevelCompactionHeuristic != nil {
1499 2 : fmt.Fprintf(&buf, " multilevel_compaction_heuristic=%s\n", o.Experimental.MultiLevelCompactionHeuristic.String())
1500 2 : }
1501 2 : fmt.Fprintf(&buf, " read_compaction_rate=%d\n", o.Experimental.ReadCompactionRate)
1502 2 : fmt.Fprintf(&buf, " read_sampling_multiplier=%d\n", o.Experimental.ReadSamplingMultiplier)
1503 2 : fmt.Fprintf(&buf, " num_deletions_threshold=%d\n", o.Experimental.NumDeletionsThreshold)
1504 2 : fmt.Fprintf(&buf, " deletion_size_ratio_threshold=%f\n", o.Experimental.DeletionSizeRatioThreshold)
1505 2 : fmt.Fprintf(&buf, " tombstone_dense_compaction_threshold=%f\n", o.Experimental.TombstoneDenseCompactionThreshold)
1506 2 : // We no longer care about strict_wal_tail, but set it to true in case an
1507 2 : // older version reads the options.
1508 2 : fmt.Fprintf(&buf, " strict_wal_tail=%t\n", true)
1509 2 : fmt.Fprintf(&buf, " table_cache_shards=%d\n", o.Experimental.FileCacheShards)
1510 2 : fmt.Fprintf(&buf, " validate_on_ingest=%t\n", o.Experimental.ValidateOnIngest)
1511 2 : fmt.Fprintf(&buf, " wal_dir=%s\n", o.WALDir)
1512 2 : fmt.Fprintf(&buf, " wal_bytes_per_sync=%d\n", o.WALBytesPerSync)
1513 2 : fmt.Fprintf(&buf, " max_writer_concurrency=%d\n", o.Experimental.MaxWriterConcurrency)
1514 2 : fmt.Fprintf(&buf, " force_writer_parallelism=%t\n", o.Experimental.ForceWriterParallelism)
1515 2 : fmt.Fprintf(&buf, " secondary_cache_size_bytes=%d\n", o.Experimental.SecondaryCacheSizeBytes)
1516 2 : fmt.Fprintf(&buf, " create_on_shared=%d\n", o.Experimental.CreateOnShared)
1517 2 :
1518 2 : // Private options.
1519 2 : //
1520 2 : // These options are only encoded if true, because we do not want them to
1521 2 : // appear in production serialized Options files, since they're testing-only
1522 2 : // options. They're only serialized when true, which still ensures that the
1523 2 : // metamorphic tests may propagate them to subprocesses.
1524 2 : if o.private.disableDeleteOnlyCompactions {
1525 2 : fmt.Fprintln(&buf, " disable_delete_only_compactions=true")
1526 2 : }
1527 2 : if o.private.disableElisionOnlyCompactions {
1528 2 : fmt.Fprintln(&buf, " disable_elision_only_compactions=true")
1529 2 : }
1530 2 : if o.private.disableLazyCombinedIteration {
1531 2 : fmt.Fprintln(&buf, " disable_lazy_combined_iteration=true")
1532 2 : }
1533 :
1534 2 : if o.WALFailover != nil {
1535 2 : unhealthyThreshold, _ := o.WALFailover.FailoverOptions.UnhealthyOperationLatencyThreshold()
1536 2 : fmt.Fprintf(&buf, "\n")
1537 2 : fmt.Fprintf(&buf, "[WAL Failover]\n")
1538 2 : fmt.Fprintf(&buf, " secondary_dir=%s\n", o.WALFailover.Secondary.Dirname)
1539 2 : fmt.Fprintf(&buf, " primary_dir_probe_interval=%s\n", o.WALFailover.FailoverOptions.PrimaryDirProbeInterval)
1540 2 : fmt.Fprintf(&buf, " healthy_probe_latency_threshold=%s\n", o.WALFailover.FailoverOptions.HealthyProbeLatencyThreshold)
1541 2 : fmt.Fprintf(&buf, " healthy_interval=%s\n", o.WALFailover.FailoverOptions.HealthyInterval)
1542 2 : fmt.Fprintf(&buf, " unhealthy_sampling_interval=%s\n", o.WALFailover.FailoverOptions.UnhealthySamplingInterval)
1543 2 : fmt.Fprintf(&buf, " unhealthy_operation_latency_threshold=%s\n", unhealthyThreshold)
1544 2 : fmt.Fprintf(&buf, " elevated_write_stall_threshold_lag=%s\n", o.WALFailover.FailoverOptions.ElevatedWriteStallThresholdLag)
1545 2 : }
1546 :
1547 2 : for i := range o.Levels {
1548 2 : l := &o.Levels[i]
1549 2 : fmt.Fprintf(&buf, "\n")
1550 2 : fmt.Fprintf(&buf, "[Level \"%d\"]\n", i)
1551 2 : fmt.Fprintf(&buf, " block_restart_interval=%d\n", l.BlockRestartInterval)
1552 2 : fmt.Fprintf(&buf, " block_size=%d\n", l.BlockSize)
1553 2 : fmt.Fprintf(&buf, " block_size_threshold=%d\n", l.BlockSizeThreshold)
1554 2 : fmt.Fprintf(&buf, " compression=%s\n", resolveDefaultCompression(l.Compression()))
1555 2 : fmt.Fprintf(&buf, " filter_policy=%s\n", filterPolicyName(l.FilterPolicy))
1556 2 : fmt.Fprintf(&buf, " filter_type=%s\n", l.FilterType)
1557 2 : fmt.Fprintf(&buf, " index_block_size=%d\n", l.IndexBlockSize)
1558 2 : fmt.Fprintf(&buf, " target_file_size=%d\n", l.TargetFileSize)
1559 2 : }
1560 :
1561 2 : return buf.String()
1562 : }
1563 :
1564 : type parseOptionsFuncs struct {
1565 : visitNewSection func(i, j int, section string) error
1566 : visitKeyValue func(i, j int, section, key, value string) error
1567 : visitCommentOrWhitespace func(i, j int, whitespace string) error
1568 : }
1569 :
1570 : // parseOptions takes options serialized by Options.String() and parses them
1571 : // into keys and values. It calls fns.visitNewSection for the beginning of each
1572 : // new section, fns.visitKeyValue for each key-value pair, and
1573 : // visitCommentOrWhitespace for comments and whitespace between key-value pairs.
1574 2 : func parseOptions(s string, fns parseOptionsFuncs) error {
1575 2 : var section, mappedSection string
1576 2 : i := 0
1577 2 : for i < len(s) {
1578 2 : rem := s[i:]
1579 2 : j := strings.IndexByte(rem, '\n')
1580 2 : if j < 0 {
1581 1 : j = len(rem)
1582 2 : } else {
1583 2 : j += 1 // Include the newline.
1584 2 : }
1585 2 : line := strings.TrimSpace(s[i : i+j])
1586 2 : startOff, endOff := i, i+j
1587 2 : i += j
1588 2 :
1589 2 : if len(line) == 0 || line[0] == ';' || line[0] == '#' {
1590 2 : // Skip blank lines and comments.
1591 2 : if fns.visitCommentOrWhitespace != nil {
1592 2 : if err := fns.visitCommentOrWhitespace(startOff, endOff, line); err != nil {
1593 0 : return err
1594 0 : }
1595 : }
1596 2 : continue
1597 : }
1598 2 : n := len(line)
1599 2 : if line[0] == '[' && line[n-1] == ']' {
1600 2 : // Parse section.
1601 2 : section = line[1 : n-1]
1602 2 : // RocksDB uses a similar (INI-style) syntax for the OPTIONS file, but
1603 2 : // different section names and keys. The "CFOptions ..." paths are the
1604 2 : // RocksDB versions which we map to the Pebble paths.
1605 2 : mappedSection = section
1606 2 : if section == `CFOptions "default"` {
1607 1 : mappedSection = "Options"
1608 1 : }
1609 2 : if fns.visitNewSection != nil {
1610 2 : if err := fns.visitNewSection(startOff, endOff, mappedSection); err != nil {
1611 0 : return err
1612 0 : }
1613 : }
1614 2 : continue
1615 : }
1616 :
1617 2 : pos := strings.Index(line, "=")
1618 2 : if pos < 0 {
1619 1 : const maxLen = 50
1620 1 : if len(line) > maxLen {
1621 0 : line = line[:maxLen-3] + "..."
1622 0 : }
1623 1 : return base.CorruptionErrorf("invalid key=value syntax: %q", errors.Safe(line))
1624 : }
1625 :
1626 2 : key := strings.TrimSpace(line[:pos])
1627 2 : value := strings.TrimSpace(line[pos+1:])
1628 2 :
1629 2 : if section == `CFOptions "default"` {
1630 1 : switch key {
1631 1 : case "comparator":
1632 1 : key = "comparer"
1633 1 : case "merge_operator":
1634 1 : key = "merger"
1635 : }
1636 : }
1637 2 : if fns.visitKeyValue != nil {
1638 2 : if err := fns.visitKeyValue(startOff, endOff, mappedSection, key, value); err != nil {
1639 1 : return err
1640 1 : }
1641 : }
1642 : }
1643 2 : return nil
1644 : }
1645 :
1646 : // ParseHooks contains callbacks to create options fields which can have
1647 : // user-defined implementations.
1648 : type ParseHooks struct {
1649 : NewCache func(size int64) *Cache
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 2 : func (o *Options) Parse(s string, hooks *ParseHooks) error {
1662 2 : visitKeyValue := func(i, j int, section, key, value string) error {
1663 2 : // WARNING: DO NOT remove entries from the switches below because doing so
1664 2 : // causes a key previously written to the OPTIONS file to be considered unknown,
1665 2 : // a backwards incompatible change. Instead, leave in support for parsing the
1666 2 : // key but simply don't parse the value.
1667 2 :
1668 2 : parseComparer := func(name string) (*Comparer, error) {
1669 2 : switch name {
1670 1 : case DefaultComparer.Name:
1671 1 : return DefaultComparer, nil
1672 2 : case testkeys.Comparer.Name:
1673 2 : return testkeys.Comparer, nil
1674 1 : default:
1675 1 : if hooks != nil && hooks.NewComparer != nil {
1676 1 : return hooks.NewComparer(name)
1677 1 : }
1678 1 : return nil, nil
1679 : }
1680 : }
1681 :
1682 2 : switch {
1683 2 : case section == "Version":
1684 2 : switch key {
1685 2 : case "pebble_version":
1686 0 : default:
1687 0 : if hooks != nil && hooks.SkipUnknown != nil && hooks.SkipUnknown(section+"."+key, value) {
1688 0 : return nil
1689 0 : }
1690 0 : return errors.Errorf("pebble: unknown option: %s.%s",
1691 0 : errors.Safe(section), errors.Safe(key))
1692 : }
1693 2 : return nil
1694 :
1695 2 : case section == "Options":
1696 2 : var err error
1697 2 : switch key {
1698 2 : case "bytes_per_sync":
1699 2 : o.BytesPerSync, err = strconv.Atoi(value)
1700 2 : case "cache_size":
1701 2 : var n int64
1702 2 : n, err = strconv.ParseInt(value, 10, 64)
1703 2 : if err == nil && hooks != nil && hooks.NewCache != nil {
1704 2 : if o.Cache != nil {
1705 0 : o.Cache.Unref()
1706 0 : }
1707 2 : o.Cache = hooks.NewCache(n)
1708 : }
1709 : // We avoid calling cache.New in parsing because it makes it
1710 : // too easy to leak a cache.
1711 2 : case "cleaner":
1712 2 : switch value {
1713 2 : case "archive":
1714 2 : o.Cleaner = ArchiveCleaner{}
1715 1 : case "delete":
1716 1 : 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 2 : case "comparer":
1723 2 : var comparer *Comparer
1724 2 : comparer, err = parseComparer(value)
1725 2 : if comparer != nil {
1726 2 : o.Comparer = comparer
1727 2 : }
1728 2 : case "compaction_debt_concurrency":
1729 2 : o.Experimental.CompactionDebtConcurrency, err = strconv.ParseUint(value, 10, 64)
1730 0 : case "delete_range_flush_delay":
1731 0 : // NB: This is a deprecated serialization of the
1732 0 : // `flush_delay_delete_range`.
1733 0 : o.FlushDelayDeleteRange, err = time.ParseDuration(value)
1734 2 : case "disable_delete_only_compactions":
1735 2 : o.private.disableDeleteOnlyCompactions, err = strconv.ParseBool(value)
1736 2 : case "disable_elision_only_compactions":
1737 2 : o.private.disableElisionOnlyCompactions, err = strconv.ParseBool(value)
1738 2 : case "disable_ingest_as_flushable":
1739 2 : var v bool
1740 2 : v, err = strconv.ParseBool(value)
1741 2 : if err == nil {
1742 2 : o.Experimental.DisableIngestAsFlushable = func() bool { return v }
1743 : }
1744 2 : case "disable_lazy_combined_iteration":
1745 2 : o.private.disableLazyCombinedIteration, err = strconv.ParseBool(value)
1746 2 : case "disable_wal":
1747 2 : o.DisableWAL, err = strconv.ParseBool(value)
1748 2 : case "enable_columnar_blocks":
1749 2 : var v bool
1750 2 : if v, err = strconv.ParseBool(value); err == nil {
1751 2 : o.Experimental.EnableColumnarBlocks = func() bool { return v }
1752 : }
1753 2 : case "flush_delay_delete_range":
1754 2 : o.FlushDelayDeleteRange, err = time.ParseDuration(value)
1755 2 : case "flush_delay_range_key":
1756 2 : o.FlushDelayRangeKey, err = time.ParseDuration(value)
1757 2 : case "flush_split_bytes":
1758 2 : o.FlushSplitBytes, err = strconv.ParseInt(value, 10, 64)
1759 2 : case "format_major_version":
1760 2 : // NB: The version written here may be stale. Open does
1761 2 : // not use the format major version encoded in the
1762 2 : // OPTIONS file other than to validate that the encoded
1763 2 : // version is valid right here.
1764 2 : var v uint64
1765 2 : v, err = strconv.ParseUint(value, 10, 64)
1766 2 : if vers := FormatMajorVersion(v); vers > internalFormatNewest || vers == FormatDefault {
1767 0 : err = errors.Newf("unsupported format major version %d", o.FormatMajorVersion)
1768 0 : }
1769 2 : if err == nil {
1770 2 : o.FormatMajorVersion = FormatMajorVersion(v)
1771 2 : }
1772 2 : case "key_schema":
1773 2 : o.KeySchema = value
1774 2 : if o.KeySchemas == nil {
1775 2 : o.KeySchemas = make(map[string]*KeySchema)
1776 2 : }
1777 2 : if _, ok := o.KeySchemas[o.KeySchema]; !ok {
1778 2 : if strings.HasPrefix(value, "DefaultKeySchema(") && strings.HasSuffix(value, ")") {
1779 2 : argsStr := strings.TrimSuffix(strings.TrimPrefix(value, "DefaultKeySchema("), ")")
1780 2 : args := strings.FieldsFunc(argsStr, func(r rune) bool {
1781 2 : return unicode.IsSpace(r) || r == ','
1782 2 : })
1783 2 : var comparer *base.Comparer
1784 2 : var bundleSize int
1785 2 : comparer, err = parseComparer(args[0])
1786 2 : if err == nil {
1787 2 : bundleSize, err = strconv.Atoi(args[1])
1788 2 : }
1789 2 : if err == nil {
1790 2 : schema := colblk.DefaultKeySchema(comparer, bundleSize)
1791 2 : o.KeySchema = schema.Name
1792 2 : o.KeySchemas[o.KeySchema] = &schema
1793 2 : }
1794 0 : } else if hooks != nil && hooks.NewKeySchema != nil {
1795 0 : var schema KeySchema
1796 0 : schema, err = hooks.NewKeySchema(value)
1797 0 : if err == nil {
1798 0 : o.KeySchemas[value] = &schema
1799 0 : }
1800 : }
1801 : }
1802 2 : case "l0_compaction_concurrency":
1803 2 : o.Experimental.L0CompactionConcurrency, err = strconv.Atoi(value)
1804 2 : case "l0_compaction_file_threshold":
1805 2 : o.L0CompactionFileThreshold, err = strconv.Atoi(value)
1806 2 : case "l0_compaction_threshold":
1807 2 : o.L0CompactionThreshold, err = strconv.Atoi(value)
1808 2 : case "l0_stop_writes_threshold":
1809 2 : o.L0StopWritesThreshold, err = strconv.Atoi(value)
1810 0 : case "l0_sublevel_compactions":
1811 : // Do nothing; option existed in older versions of pebble.
1812 2 : case "lbase_max_bytes":
1813 2 : o.LBaseMaxBytes, err = strconv.ParseInt(value, 10, 64)
1814 2 : case "level_multiplier":
1815 2 : o.Experimental.LevelMultiplier, err = strconv.Atoi(value)
1816 2 : case "max_concurrent_compactions":
1817 2 : var concurrentCompactions int
1818 2 : concurrentCompactions, err = strconv.Atoi(value)
1819 2 : if concurrentCompactions <= 0 {
1820 0 : err = errors.New("max_concurrent_compactions cannot be <= 0")
1821 2 : } else {
1822 2 : o.MaxConcurrentCompactions = func() int { return concurrentCompactions }
1823 : }
1824 2 : case "max_concurrent_downloads":
1825 2 : var concurrentDownloads int
1826 2 : concurrentDownloads, err = strconv.Atoi(value)
1827 2 : if concurrentDownloads <= 0 {
1828 0 : err = errors.New("max_concurrent_compactions cannot be <= 0")
1829 2 : } else {
1830 2 : o.MaxConcurrentDownloads = func() int { return concurrentDownloads }
1831 : }
1832 2 : case "max_manifest_file_size":
1833 2 : o.MaxManifestFileSize, err = strconv.ParseInt(value, 10, 64)
1834 2 : case "max_open_files":
1835 2 : o.MaxOpenFiles, err = strconv.Atoi(value)
1836 2 : case "mem_table_size":
1837 2 : o.MemTableSize, err = strconv.ParseUint(value, 10, 64)
1838 2 : case "mem_table_stop_writes_threshold":
1839 2 : o.MemTableStopWritesThreshold, err = strconv.Atoi(value)
1840 0 : case "min_compaction_rate":
1841 : // Do nothing; option existed in older versions of pebble, and
1842 : // may be meaningful again eventually.
1843 2 : case "min_deletion_rate":
1844 2 : o.TargetByteDeletionRate, err = strconv.Atoi(value)
1845 0 : case "min_flush_rate":
1846 : // Do nothing; option existed in older versions of pebble, and
1847 : // may be meaningful again eventually.
1848 2 : case "multilevel_compaction_heuristic":
1849 2 : switch {
1850 2 : case value == "none":
1851 2 : o.Experimental.MultiLevelCompactionHeuristic = NoMultiLevel{}
1852 2 : case strings.HasPrefix(value, "wamp"):
1853 2 : fields := strings.FieldsFunc(strings.TrimPrefix(value, "wamp"), func(r rune) bool {
1854 2 : return unicode.IsSpace(r) || r == ',' || r == '(' || r == ')'
1855 2 : })
1856 2 : if len(fields) != 2 {
1857 0 : err = errors.Newf("require 2 arguments")
1858 0 : }
1859 2 : var h WriteAmpHeuristic
1860 2 : if err == nil {
1861 2 : h.AddPropensity, err = strconv.ParseFloat(fields[0], 64)
1862 2 : }
1863 2 : if err == nil {
1864 2 : h.AllowL0, err = strconv.ParseBool(fields[1])
1865 2 : }
1866 2 : if err == nil {
1867 2 : o.Experimental.MultiLevelCompactionHeuristic = h
1868 2 : } else {
1869 0 : err = errors.Wrapf(err, "unexpected wamp heuristic arguments: %s", value)
1870 0 : }
1871 0 : default:
1872 0 : err = errors.Newf("unrecognized multilevel compaction heuristic: %s", value)
1873 : }
1874 0 : case "point_tombstone_weight":
1875 : // Do nothing; deprecated.
1876 2 : case "strict_wal_tail":
1877 2 : var strictWALTail bool
1878 2 : strictWALTail, err = strconv.ParseBool(value)
1879 2 : if err == nil && !strictWALTail {
1880 0 : err = errors.Newf("reading from versions with strict_wal_tail=false no longer supported")
1881 0 : }
1882 2 : case "merger":
1883 2 : switch value {
1884 0 : case "nullptr":
1885 0 : o.Merger = nil
1886 2 : case "pebble.concatenate":
1887 2 : o.Merger = DefaultMerger
1888 1 : default:
1889 1 : if hooks != nil && hooks.NewMerger != nil {
1890 1 : o.Merger, err = hooks.NewMerger(value)
1891 1 : }
1892 : }
1893 2 : case "read_compaction_rate":
1894 2 : o.Experimental.ReadCompactionRate, err = strconv.ParseInt(value, 10, 64)
1895 2 : case "read_sampling_multiplier":
1896 2 : o.Experimental.ReadSamplingMultiplier, err = strconv.ParseInt(value, 10, 64)
1897 2 : case "num_deletions_threshold":
1898 2 : o.Experimental.NumDeletionsThreshold, err = strconv.Atoi(value)
1899 2 : case "deletion_size_ratio_threshold":
1900 2 : val, parseErr := strconv.ParseFloat(value, 32)
1901 2 : o.Experimental.DeletionSizeRatioThreshold = float32(val)
1902 2 : err = parseErr
1903 2 : case "tombstone_dense_compaction_threshold":
1904 2 : o.Experimental.TombstoneDenseCompactionThreshold, err = strconv.ParseFloat(value, 64)
1905 2 : case "table_cache_shards":
1906 2 : o.Experimental.FileCacheShards, err = strconv.Atoi(value)
1907 0 : case "table_format":
1908 0 : switch value {
1909 0 : case "leveldb":
1910 0 : case "rocksdbv2":
1911 0 : default:
1912 0 : return errors.Errorf("pebble: unknown table format: %q", errors.Safe(value))
1913 : }
1914 1 : case "table_property_collectors":
1915 : // No longer implemented; ignore.
1916 2 : case "validate_on_ingest":
1917 2 : o.Experimental.ValidateOnIngest, err = strconv.ParseBool(value)
1918 2 : case "wal_dir":
1919 2 : o.WALDir = value
1920 2 : case "wal_bytes_per_sync":
1921 2 : o.WALBytesPerSync, err = strconv.Atoi(value)
1922 2 : case "max_writer_concurrency":
1923 2 : o.Experimental.MaxWriterConcurrency, err = strconv.Atoi(value)
1924 2 : case "force_writer_parallelism":
1925 2 : o.Experimental.ForceWriterParallelism, err = strconv.ParseBool(value)
1926 2 : case "secondary_cache_size_bytes":
1927 2 : o.Experimental.SecondaryCacheSizeBytes, err = strconv.ParseInt(value, 10, 64)
1928 2 : case "create_on_shared":
1929 2 : var createOnSharedInt int64
1930 2 : createOnSharedInt, err = strconv.ParseInt(value, 10, 64)
1931 2 : o.Experimental.CreateOnShared = remote.CreateOnSharedStrategy(createOnSharedInt)
1932 0 : default:
1933 0 : if hooks != nil && hooks.SkipUnknown != nil && hooks.SkipUnknown(section+"."+key, value) {
1934 0 : return nil
1935 0 : }
1936 0 : return errors.Errorf("pebble: unknown option: %s.%s",
1937 0 : errors.Safe(section), errors.Safe(key))
1938 : }
1939 2 : return err
1940 :
1941 2 : case section == "WAL Failover":
1942 2 : if o.WALFailover == nil {
1943 2 : o.WALFailover = new(WALFailoverOptions)
1944 2 : }
1945 2 : var err error
1946 2 : switch key {
1947 2 : case "secondary_dir":
1948 2 : o.WALFailover.Secondary = wal.Dir{Dirname: value, FS: vfs.Default}
1949 2 : case "primary_dir_probe_interval":
1950 2 : o.WALFailover.PrimaryDirProbeInterval, err = time.ParseDuration(value)
1951 2 : case "healthy_probe_latency_threshold":
1952 2 : o.WALFailover.HealthyProbeLatencyThreshold, err = time.ParseDuration(value)
1953 2 : case "healthy_interval":
1954 2 : o.WALFailover.HealthyInterval, err = time.ParseDuration(value)
1955 2 : case "unhealthy_sampling_interval":
1956 2 : o.WALFailover.UnhealthySamplingInterval, err = time.ParseDuration(value)
1957 2 : case "unhealthy_operation_latency_threshold":
1958 2 : var threshold time.Duration
1959 2 : threshold, err = time.ParseDuration(value)
1960 2 : o.WALFailover.UnhealthyOperationLatencyThreshold = func() (time.Duration, bool) {
1961 2 : return threshold, true
1962 2 : }
1963 2 : case "elevated_write_stall_threshold_lag":
1964 2 : o.WALFailover.ElevatedWriteStallThresholdLag, err = time.ParseDuration(value)
1965 0 : default:
1966 0 : if hooks != nil && hooks.SkipUnknown != nil && hooks.SkipUnknown(section+"."+key, value) {
1967 0 : return nil
1968 0 : }
1969 0 : return errors.Errorf("pebble: unknown option: %s.%s",
1970 0 : errors.Safe(section), errors.Safe(key))
1971 : }
1972 2 : return err
1973 :
1974 2 : case strings.HasPrefix(section, "Level "):
1975 2 : var index int
1976 2 : if n, err := fmt.Sscanf(section, `Level "%d"`, &index); err != nil {
1977 0 : return err
1978 2 : } else if n != 1 {
1979 0 : if hooks != nil && hooks.SkipUnknown != nil && hooks.SkipUnknown(section, value) {
1980 0 : return nil
1981 0 : }
1982 0 : return errors.Errorf("pebble: unknown section: %q", errors.Safe(section))
1983 : }
1984 :
1985 2 : if len(o.Levels) <= index {
1986 1 : newLevels := make([]LevelOptions, index+1)
1987 1 : copy(newLevels, o.Levels)
1988 1 : o.Levels = newLevels
1989 1 : }
1990 2 : l := &o.Levels[index]
1991 2 :
1992 2 : var err error
1993 2 : switch key {
1994 2 : case "block_restart_interval":
1995 2 : l.BlockRestartInterval, err = strconv.Atoi(value)
1996 2 : case "block_size":
1997 2 : l.BlockSize, err = strconv.Atoi(value)
1998 2 : case "block_size_threshold":
1999 2 : l.BlockSizeThreshold, err = strconv.Atoi(value)
2000 2 : case "compression":
2001 2 : switch value {
2002 0 : case "Default":
2003 0 : l.Compression = func() Compression { return DefaultCompression }
2004 2 : case "NoCompression":
2005 2 : l.Compression = func() Compression { return NoCompression }
2006 2 : case "Snappy":
2007 2 : l.Compression = func() Compression { return SnappyCompression }
2008 2 : case "ZSTD":
2009 2 : l.Compression = func() Compression { return ZstdCompression }
2010 0 : default:
2011 0 : return errors.Errorf("pebble: unknown compression: %q", errors.Safe(value))
2012 : }
2013 2 : case "filter_policy":
2014 2 : if hooks != nil && hooks.NewFilterPolicy != nil {
2015 2 : l.FilterPolicy, err = hooks.NewFilterPolicy(value)
2016 2 : }
2017 2 : case "filter_type":
2018 2 : switch value {
2019 2 : case "table":
2020 2 : l.FilterType = TableFilter
2021 0 : default:
2022 0 : return errors.Errorf("pebble: unknown filter type: %q", errors.Safe(value))
2023 : }
2024 2 : case "index_block_size":
2025 2 : l.IndexBlockSize, err = strconv.Atoi(value)
2026 2 : case "target_file_size":
2027 2 : l.TargetFileSize, err = strconv.ParseInt(value, 10, 64)
2028 0 : default:
2029 0 : if hooks != nil && hooks.SkipUnknown != nil && hooks.SkipUnknown(section+"."+key, value) {
2030 0 : return nil
2031 0 : }
2032 0 : return errors.Errorf("pebble: unknown option: %s.%s", errors.Safe(section), errors.Safe(key))
2033 : }
2034 2 : return err
2035 : }
2036 2 : if hooks != nil && hooks.SkipUnknown != nil && hooks.SkipUnknown(section+"."+key, value) {
2037 2 : return nil
2038 2 : }
2039 0 : return errors.Errorf("pebble: unknown section: %q", errors.Safe(section))
2040 : }
2041 2 : return parseOptions(s, parseOptionsFuncs{
2042 2 : visitKeyValue: visitKeyValue,
2043 2 : })
2044 : }
2045 :
2046 : // ErrMissingWALRecoveryDir is an error returned when a database is attempted to be
2047 : // opened without supplying a Options.WALRecoveryDir entry for a directory that
2048 : // may contain WALs required to recover a consistent database state.
2049 : type ErrMissingWALRecoveryDir struct {
2050 : Dir string
2051 : }
2052 :
2053 : // Error implements error.
2054 1 : func (e ErrMissingWALRecoveryDir) Error() string {
2055 1 : return fmt.Sprintf("directory %q may contain relevant WALs", e.Dir)
2056 1 : }
2057 :
2058 : // CheckCompatibility verifies the options are compatible with the previous options
2059 : // serialized by Options.String(). For example, the Comparer and Merger must be
2060 : // the same, or data will not be able to be properly read from the DB.
2061 : //
2062 : // This function only looks at specific keys and does not error out if the
2063 : // options are newer and contain unknown keys.
2064 2 : func (o *Options) CheckCompatibility(previousOptions string) error {
2065 2 : visitKeyValue := func(i, j int, section, key, value string) error {
2066 2 : switch section + "." + key {
2067 2 : case "Options.comparer":
2068 2 : if value != o.Comparer.Name {
2069 1 : return errors.Errorf("pebble: comparer name from file %q != comparer name from options %q",
2070 1 : errors.Safe(value), errors.Safe(o.Comparer.Name))
2071 1 : }
2072 2 : case "Options.merger":
2073 2 : // RocksDB allows the merge operator to be unspecified, in which case it
2074 2 : // shows up as "nullptr".
2075 2 : if value != "nullptr" && value != o.Merger.Name {
2076 1 : return errors.Errorf("pebble: merger name from file %q != merger name from options %q",
2077 1 : errors.Safe(value), errors.Safe(o.Merger.Name))
2078 1 : }
2079 2 : case "Options.wal_dir", "WAL Failover.secondary_dir":
2080 2 : switch {
2081 2 : case o.WALDir == value:
2082 2 : return nil
2083 2 : case o.WALFailover != nil && o.WALFailover.Secondary.Dirname == value:
2084 2 : return nil
2085 1 : default:
2086 1 : for _, d := range o.WALRecoveryDirs {
2087 1 : if d.Dirname == value {
2088 1 : return nil
2089 1 : }
2090 : }
2091 1 : return ErrMissingWALRecoveryDir{Dir: value}
2092 : }
2093 : }
2094 2 : return nil
2095 : }
2096 2 : return parseOptions(previousOptions, parseOptionsFuncs{visitKeyValue: visitKeyValue})
2097 : }
2098 :
2099 : // Validate verifies that the options are mutually consistent. For example,
2100 : // L0StopWritesThreshold must be >= L0CompactionThreshold, otherwise a write
2101 : // stall would persist indefinitely.
2102 2 : func (o *Options) Validate() error {
2103 2 : // Note that we can presume Options.EnsureDefaults has been called, so there
2104 2 : // is no need to check for zero values.
2105 2 :
2106 2 : var buf strings.Builder
2107 2 : if o.Experimental.L0CompactionConcurrency < 1 {
2108 1 : fmt.Fprintf(&buf, "L0CompactionConcurrency (%d) must be >= 1\n",
2109 1 : o.Experimental.L0CompactionConcurrency)
2110 1 : }
2111 2 : if o.L0StopWritesThreshold < o.L0CompactionThreshold {
2112 1 : fmt.Fprintf(&buf, "L0StopWritesThreshold (%d) must be >= L0CompactionThreshold (%d)\n",
2113 1 : o.L0StopWritesThreshold, o.L0CompactionThreshold)
2114 1 : }
2115 2 : if uint64(o.MemTableSize) >= maxMemTableSize {
2116 1 : fmt.Fprintf(&buf, "MemTableSize (%s) must be < %s\n",
2117 1 : humanize.Bytes.Uint64(uint64(o.MemTableSize)), humanize.Bytes.Uint64(maxMemTableSize))
2118 1 : }
2119 2 : if o.MemTableStopWritesThreshold < 2 {
2120 1 : fmt.Fprintf(&buf, "MemTableStopWritesThreshold (%d) must be >= 2\n",
2121 1 : o.MemTableStopWritesThreshold)
2122 1 : }
2123 2 : if o.FormatMajorVersion < FormatMinSupported || o.FormatMajorVersion > internalFormatNewest {
2124 0 : fmt.Fprintf(&buf, "FormatMajorVersion (%d) must be between %d and %d\n",
2125 0 : o.FormatMajorVersion, FormatMinSupported, internalFormatNewest)
2126 0 : }
2127 2 : if o.Experimental.CreateOnShared != remote.CreateOnSharedNone && o.FormatMajorVersion < FormatMinForSharedObjects {
2128 0 : fmt.Fprintf(&buf, "FormatMajorVersion (%d) when CreateOnShared is set must be at least %d\n",
2129 0 : o.FormatMajorVersion, FormatMinForSharedObjects)
2130 0 : }
2131 2 : if o.FileCache != nil && o.Cache != o.FileCache.cache {
2132 1 : fmt.Fprintf(&buf, "underlying cache in the FileCache and the Cache dont match\n")
2133 1 : }
2134 2 : if len(o.KeySchemas) > 0 {
2135 2 : if o.KeySchema == "" {
2136 0 : fmt.Fprintf(&buf, "KeySchemas is set but KeySchema is not\n")
2137 0 : }
2138 2 : if _, ok := o.KeySchemas[o.KeySchema]; !ok {
2139 0 : fmt.Fprintf(&buf, "KeySchema %q not found in KeySchemas\n", o.KeySchema)
2140 0 : }
2141 : }
2142 2 : if buf.Len() == 0 {
2143 2 : return nil
2144 2 : }
2145 1 : return errors.New(buf.String())
2146 : }
2147 :
2148 : // MakeReaderOptions constructs sstable.ReaderOptions from the corresponding
2149 : // options in the receiver.
2150 2 : func (o *Options) MakeReaderOptions() sstable.ReaderOptions {
2151 2 : var readerOpts sstable.ReaderOptions
2152 2 : if o != nil {
2153 2 : readerOpts.Comparer = o.Comparer
2154 2 : readerOpts.Filters = o.Filters
2155 2 : readerOpts.KeySchemas = o.KeySchemas
2156 2 : readerOpts.LoadBlockSema = o.LoadBlockSema
2157 2 : readerOpts.LoggerAndTracer = o.LoggerAndTracer
2158 2 : readerOpts.Merger = o.Merger
2159 2 : }
2160 2 : return readerOpts
2161 : }
2162 :
2163 : // MakeWriterOptions constructs sstable.WriterOptions for the specified level
2164 : // from the corresponding options in the receiver.
2165 2 : func (o *Options) MakeWriterOptions(level int, format sstable.TableFormat) sstable.WriterOptions {
2166 2 : var writerOpts sstable.WriterOptions
2167 2 : writerOpts.TableFormat = format
2168 2 : if o != nil {
2169 2 : writerOpts.Comparer = o.Comparer
2170 2 : if o.Merger != nil {
2171 2 : writerOpts.MergerName = o.Merger.Name
2172 2 : }
2173 2 : writerOpts.BlockPropertyCollectors = o.BlockPropertyCollectors
2174 : }
2175 2 : if format >= sstable.TableFormatPebblev3 {
2176 2 : writerOpts.ShortAttributeExtractor = o.Experimental.ShortAttributeExtractor
2177 2 : writerOpts.RequiredInPlaceValueBound = o.Experimental.RequiredInPlaceValueBound
2178 2 : if format >= sstable.TableFormatPebblev4 && level == numLevels-1 {
2179 2 : writerOpts.WritingToLowestLevel = true
2180 2 : }
2181 : }
2182 2 : levelOpts := o.Level(level)
2183 2 : writerOpts.BlockRestartInterval = levelOpts.BlockRestartInterval
2184 2 : writerOpts.BlockSize = levelOpts.BlockSize
2185 2 : writerOpts.BlockSizeThreshold = levelOpts.BlockSizeThreshold
2186 2 : writerOpts.Compression = resolveDefaultCompression(levelOpts.Compression())
2187 2 : writerOpts.FilterPolicy = levelOpts.FilterPolicy
2188 2 : writerOpts.FilterType = levelOpts.FilterType
2189 2 : writerOpts.IndexBlockSize = levelOpts.IndexBlockSize
2190 2 : writerOpts.KeySchema = o.KeySchemas[o.KeySchema]
2191 2 : writerOpts.AllocatorSizeClasses = o.AllocatorSizeClasses
2192 2 : writerOpts.NumDeletionsThreshold = o.Experimental.NumDeletionsThreshold
2193 2 : writerOpts.DeletionSizeRatioThreshold = o.Experimental.DeletionSizeRatioThreshold
2194 2 : return writerOpts
2195 : }
2196 :
2197 2 : func resolveDefaultCompression(c Compression) Compression {
2198 2 : if c <= DefaultCompression || c >= block.NCompression {
2199 1 : c = SnappyCompression
2200 1 : }
2201 2 : return c
2202 : }
|