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