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