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