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