forked from cockroachdb/pebble
-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.go
2999 lines (2737 loc) · 105 KB
/
db.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2012 The LevelDB-Go and Pebble Authors. All rights reserved. Use
// of this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
// Package pebble provides an ordered key/value store.
package pebble // import "github.com/cockroachdb/pebble"
import (
"context"
"fmt"
"io"
"sync"
"sync/atomic"
"time"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/pebble/internal/arenaskl"
"github.com/cockroachdb/pebble/internal/base"
"github.com/cockroachdb/pebble/internal/invalidating"
"github.com/cockroachdb/pebble/internal/invariants"
"github.com/cockroachdb/pebble/internal/keyspan"
"github.com/cockroachdb/pebble/internal/keyspan/keyspanimpl"
"github.com/cockroachdb/pebble/internal/manifest"
"github.com/cockroachdb/pebble/internal/manual"
"github.com/cockroachdb/pebble/objstorage"
"github.com/cockroachdb/pebble/objstorage/remote"
"github.com/cockroachdb/pebble/rangekey"
"github.com/cockroachdb/pebble/record"
"github.com/cockroachdb/pebble/sstable"
"github.com/cockroachdb/pebble/vfs"
"github.com/cockroachdb/pebble/vfs/atomicfs"
"github.com/cockroachdb/pebble/wal"
"github.com/cockroachdb/tokenbucket"
"github.com/prometheus/client_golang/prometheus"
)
const (
// minTableCacheSize is the minimum size of the table cache, for a single db.
minTableCacheSize = 64
// numNonTableCacheFiles is an approximation for the number of files
// that we don't use for table caches, for a given db.
numNonTableCacheFiles = 10
)
var (
// ErrNotFound is returned when a get operation does not find the requested
// key.
ErrNotFound = base.ErrNotFound
// ErrClosed is panicked when an operation is performed on a closed snapshot or
// DB. Use errors.Is(err, ErrClosed) to check for this error.
ErrClosed = errors.New("pebble: closed")
// ErrReadOnly is returned when a write operation is performed on a read-only
// database.
ErrReadOnly = errors.New("pebble: read-only")
// errNoSplit indicates that the user is trying to perform a range key
// operation but the configured Comparer does not provide a Split
// implementation.
errNoSplit = errors.New("pebble: Comparer.Split required for range key operations")
)
// Reader is a readable key/value store.
//
// It is safe to call Get and NewIter from concurrent goroutines.
type Reader interface {
// Get gets the value for the given key. It returns ErrNotFound if the DB
// does not contain the key.
//
// The caller should not modify the contents of the returned slice, but it is
// safe to modify the contents of the argument after Get returns. The
// returned slice will remain valid until the returned Closer is closed. On
// success, the caller MUST call closer.Close() or a memory leak will occur.
Get(key []byte) (value []byte, closer io.Closer, err error)
// NewIter returns an iterator that is unpositioned (Iterator.Valid() will
// return false). The iterator can be positioned via a call to SeekGE,
// SeekLT, First or Last.
NewIter(o *IterOptions) (*Iterator, error)
// NewIterWithContext is like NewIter, and additionally accepts a context
// for tracing.
NewIterWithContext(ctx context.Context, o *IterOptions) (*Iterator, error)
// Close closes the Reader. It may or may not close any underlying io.Reader
// or io.Writer, depending on how the DB was created.
//
// It is not safe to close a DB until all outstanding iterators are closed.
// It is valid to call Close multiple times. Other methods should not be
// called after the DB has been closed.
Close() error
}
// Writer is a writable key/value store.
//
// Goroutine safety is dependent on the specific implementation.
type Writer interface {
// Apply the operations contained in the batch to the DB.
//
// It is safe to modify the contents of the arguments after Apply returns.
Apply(batch *Batch, o *WriteOptions) error
// Delete deletes the value for the given key. Deletes are blind all will
// succeed even if the given key does not exist.
//
// It is safe to modify the contents of the arguments after Delete returns.
Delete(key []byte, o *WriteOptions) error
// DeleteSized behaves identically to Delete, but takes an additional
// argument indicating the size of the value being deleted. DeleteSized
// should be preferred when the caller has the expectation that there exists
// a single internal KV pair for the key (eg, the key has not been
// overwritten recently), and the caller knows the size of its value.
//
// DeleteSized will record the value size within the tombstone and use it to
// inform compaction-picking heuristics which strive to reduce space
// amplification in the LSM. This "calling your shot" mechanic allows the
// storage engine to more accurately estimate and reduce space
// amplification.
//
// It is safe to modify the contents of the arguments after DeleteSized
// returns.
DeleteSized(key []byte, valueSize uint32, _ *WriteOptions) error
// SingleDelete is similar to Delete in that it deletes the value for the given key. Like Delete,
// it is a blind operation that will succeed even if the given key does not exist.
//
// WARNING: Undefined (non-deterministic) behavior will result if a key is overwritten and
// then deleted using SingleDelete. The record may appear deleted immediately, but be
// resurrected at a later time after compactions have been performed. Or the record may
// be deleted permanently. A Delete operation lays down a "tombstone" which shadows all
// previous versions of a key. The SingleDelete operation is akin to "anti-matter" and will
// only delete the most recently written version for a key. These different semantics allow
// the DB to avoid propagating a SingleDelete operation during a compaction as soon as the
// corresponding Set operation is encountered. These semantics require extreme care to handle
// properly. Only use if you have a workload where the performance gain is critical and you
// can guarantee that a record is written once and then deleted once.
//
// SingleDelete is internally transformed into a Delete if the most recent record for a key is either
// a Merge or Delete record.
//
// It is safe to modify the contents of the arguments after SingleDelete returns.
SingleDelete(key []byte, o *WriteOptions) error
// DeleteRange deletes all of the point keys (and values) in the range
// [start,end) (inclusive on start, exclusive on end). DeleteRange does NOT
// delete overlapping range keys (eg, keys set via RangeKeySet).
//
// It is safe to modify the contents of the arguments after DeleteRange
// returns.
DeleteRange(start, end []byte, o *WriteOptions) error
// LogData adds the specified to the batch. The data will be written to the
// WAL, but not added to memtables or sstables. Log data is never indexed,
// which makes it useful for testing WAL performance.
//
// It is safe to modify the contents of the argument after LogData returns.
LogData(data []byte, opts *WriteOptions) error
// Merge merges the value for the given key. The details of the merge are
// dependent upon the configured merge operation.
//
// It is safe to modify the contents of the arguments after Merge returns.
Merge(key, value []byte, o *WriteOptions) error
// Set sets the value for the given key. It overwrites any previous value
// for that key; a DB is not a multi-map.
//
// It is safe to modify the contents of the arguments after Set returns.
Set(key, value []byte, o *WriteOptions) error
// RangeKeySet sets a range key mapping the key range [start, end) at the MVCC
// timestamp suffix to value. The suffix is optional. If any portion of the key
// range [start, end) is already set by a range key with the same suffix value,
// RangeKeySet overrides it.
//
// It is safe to modify the contents of the arguments after RangeKeySet returns.
RangeKeySet(start, end, suffix, value []byte, opts *WriteOptions) error
// RangeKeyUnset removes a range key mapping the key range [start, end) at the
// MVCC timestamp suffix. The suffix may be omitted to remove an unsuffixed
// range key. RangeKeyUnset only removes portions of range keys that fall within
// the [start, end) key span, and only range keys with suffixes that exactly
// match the unset suffix.
//
// It is safe to modify the contents of the arguments after RangeKeyUnset
// returns.
RangeKeyUnset(start, end, suffix []byte, opts *WriteOptions) error
// RangeKeyDelete deletes all of the range keys in the range [start,end)
// (inclusive on start, exclusive on end). It does not delete point keys (for
// that use DeleteRange). RangeKeyDelete removes all range keys within the
// bounds, including those with or without suffixes.
//
// It is safe to modify the contents of the arguments after RangeKeyDelete
// returns.
RangeKeyDelete(start, end []byte, opts *WriteOptions) error
}
// CPUWorkHandle represents a handle used by the CPUWorkPermissionGranter API.
type CPUWorkHandle interface {
// Permitted indicates whether Pebble can use additional CPU resources.
Permitted() bool
}
// CPUWorkPermissionGranter is used to request permission to opportunistically
// use additional CPUs to speed up internal background work.
type CPUWorkPermissionGranter interface {
// GetPermission returns a handle regardless of whether permission is granted
// or not. In the latter case, the handle is only useful for recording
// the CPU time actually spent on this calling goroutine.
GetPermission(time.Duration) CPUWorkHandle
// CPUWorkDone must be called regardless of whether CPUWorkHandle.Permitted
// returns true or false.
CPUWorkDone(CPUWorkHandle)
}
// Use a default implementation for the CPU work granter to avoid excessive nil
// checks in the code.
type defaultCPUWorkHandle struct{}
func (d defaultCPUWorkHandle) Permitted() bool {
return false
}
type defaultCPUWorkGranter struct{}
func (d defaultCPUWorkGranter) GetPermission(_ time.Duration) CPUWorkHandle {
return defaultCPUWorkHandle{}
}
func (d defaultCPUWorkGranter) CPUWorkDone(_ CPUWorkHandle) {}
// DB provides a concurrent, persistent ordered key/value store.
//
// A DB's basic operations (Get, Set, Delete) should be self-explanatory. Get
// and Delete will return ErrNotFound if the requested key is not in the store.
// Callers are free to ignore this error.
//
// A DB also allows for iterating over the key/value pairs in key order. If d
// is a DB, the code below prints all key/value pairs whose keys are 'greater
// than or equal to' k:
//
// iter := d.NewIter(readOptions)
// for iter.SeekGE(k); iter.Valid(); iter.Next() {
// fmt.Printf("key=%q value=%q\n", iter.Key(), iter.Value())
// }
// return iter.Close()
//
// The Options struct holds the optional parameters for the DB, including a
// Comparer to define a 'less than' relationship over keys. It is always valid
// to pass a nil *Options, which means to use the default parameter values. Any
// zero field of a non-nil *Options also means to use the default value for
// that parameter. Thus, the code below uses a custom Comparer, but the default
// values for every other parameter:
//
// db := pebble.Open(&Options{
// Comparer: myComparer,
// })
type DB struct {
// The count and size of referenced memtables. This includes memtables
// present in DB.mu.mem.queue, as well as memtables that have been flushed
// but are still referenced by an inuse readState, as well as up to one
// memTable waiting to be reused and stored in d.memTableRecycle.
memTableCount atomic.Int64
memTableReserved atomic.Int64 // number of bytes reserved in the cache for memtables
// memTableRecycle holds a pointer to an obsolete memtable. The next
// memtable allocation will reuse this memtable if it has not already been
// recycled.
memTableRecycle atomic.Pointer[memTable]
// The logical size of the current WAL.
logSize atomic.Uint64
// The number of input bytes to the log. This is the raw size of the
// batches written to the WAL, without the overhead of the record
// envelopes.
logBytesIn atomic.Uint64
// The number of bytes available on disk.
diskAvailBytes atomic.Uint64
cacheID uint64
dirname string
opts *Options
cmp Compare
equal Equal
merge Merge
split Split
abbreviatedKey AbbreviatedKey
// The threshold for determining when a batch is "large" and will skip being
// inserted into a memtable.
largeBatchThreshold uint64
// The current OPTIONS file number.
optionsFileNum base.DiskFileNum
// The on-disk size of the current OPTIONS file.
optionsFileSize uint64
// objProvider is used to access and manage SSTs.
objProvider objstorage.Provider
fileLock *Lock
dataDir vfs.File
tableCache *tableCacheContainer
newIters tableNewIters
tableNewRangeKeyIter keyspanimpl.TableNewSpanIter
commit *commitPipeline
// readState provides access to the state needed for reading without needing
// to acquire DB.mu.
readState struct {
sync.RWMutex
val *readState
}
closed *atomic.Value
closedCh chan struct{}
cleanupManager *cleanupManager
// During an iterator close, we may asynchronously schedule read compactions.
// We want to wait for those goroutines to finish, before closing the DB.
// compactionShedulers.Wait() should not be called while the DB.mu is held.
compactionSchedulers sync.WaitGroup
// The main mutex protecting internal DB state. This mutex encompasses many
// fields because those fields need to be accessed and updated atomically. In
// particular, the current version, log.*, mem.*, and snapshot list need to
// be accessed and updated atomically during compaction.
//
// Care is taken to avoid holding DB.mu during IO operations. Accomplishing
// this sometimes requires releasing DB.mu in a method that was called with
// it held. See versionSet.logAndApply() and DB.makeRoomForWrite() for
// examples. This is a common pattern, so be careful about expectations that
// DB.mu will be held continuously across a set of calls.
mu struct {
sync.Mutex
formatVers struct {
// vers is the database's current format major version.
// Backwards-incompatible features are gated behind new
// format major versions and not enabled until a database's
// version is ratcheted upwards.
//
// Although this is under the `mu` prefix, readers may read vers
// atomically without holding d.mu. Writers must only write to this
// value through finalizeFormatVersUpgrade which requires d.mu is
// held.
vers atomic.Uint64
// marker is the atomic marker for the format major version.
// When a database's version is ratcheted upwards, the
// marker is moved in order to atomically record the new
// version.
marker *atomicfs.Marker
// ratcheting when set to true indicates that the database is
// currently in the process of ratcheting the format major version
// to vers + 1. As a part of ratcheting the format major version,
// migrations may drop and re-acquire the mutex.
ratcheting bool
}
// The ID of the next job. Job IDs are passed to event listener
// notifications and act as a mechanism for tying together the events and
// log messages for a single job such as a flush, compaction, or file
// ingestion. Job IDs are not serialized to disk or used for correctness.
nextJobID JobID
// The collection of immutable versions and state about the log and visible
// sequence numbers. Use the pointer here to ensure the atomic fields in
// version set are aligned properly.
versions *versionSet
log struct {
// manager is not protected by mu, but calls to Create must be
// serialized, and happen after the previous writer is closed.
manager wal.Manager
// The Writer is protected by commitPipeline.mu. This allows log writes
// to be performed without holding DB.mu, but requires both
// commitPipeline.mu and DB.mu to be held when rotating the WAL/memtable
// (i.e. makeRoomForWrite). Can be nil.
writer wal.Writer
metrics struct {
// fsyncLatency has its own internal synchronization, and is not
// protected by mu.
fsyncLatency prometheus.Histogram
// Updated whenever a wal.Writer is closed.
record.LogWriterMetrics
}
}
mem struct {
// The current mutable memTable. Readers of the pointer may hold
// either DB.mu or commitPipeline.mu.
//
// Its internal fields are protected by commitPipeline.mu. This
// allows batch commits to be performed without DB.mu as long as no
// memtable rotation is required.
//
// Both commitPipeline.mu and DB.mu must be held when rotating the
// memtable.
mutable *memTable
// Queue of flushables (the mutable memtable is at end). Elements are
// added to the end of the slice and removed from the beginning. Once an
// index is set it is never modified making a fixed slice immutable and
// safe for concurrent reads.
queue flushableList
// nextSize is the size of the next memtable. The memtable size starts at
// min(256KB,Options.MemTableSize) and doubles each time a new memtable
// is allocated up to Options.MemTableSize. This reduces the memory
// footprint of memtables when lots of DB instances are used concurrently
// in test environments.
nextSize uint64
}
compact struct {
// Condition variable used to signal when a flush or compaction has
// completed. Used by the write-stall mechanism to wait for the stall
// condition to clear. See DB.makeRoomForWrite().
cond sync.Cond
// True when a flush is in progress.
flushing bool
// The number of ongoing non-download compactions.
compactingCount int
// The number of download compactions.
downloadingCount int
// The list of deletion hints, suggesting ranges for delete-only
// compactions.
deletionHints []deleteCompactionHint
// The list of manual compactions. The next manual compaction to perform
// is at the start of the list. New entries are added to the end.
manual []*manualCompaction
// downloads is the list of pending download tasks. The next download to
// perform is at the start of the list. New entries are added to the end.
downloads []*downloadSpanTask
// inProgress is the set of in-progress flushes and compactions.
// It's used in the calculation of some metrics and to initialize L0
// sublevels' state. Some of the compactions contained within this
// map may have already committed an edit to the version but are
// lingering performing cleanup, like deleting obsolete files.
inProgress map[*compaction]struct{}
// rescheduleReadCompaction indicates to an iterator that a read compaction
// should be scheduled.
rescheduleReadCompaction bool
// readCompactions is a readCompactionQueue which keeps track of the
// compactions which we might have to perform.
readCompactions readCompactionQueue
// The cumulative duration of all completed compactions since Open.
// Does not include flushes.
duration time.Duration
// Flush throughput metric.
flushWriteThroughput ThroughputMetric
// The idle start time for the flush "loop", i.e., when the flushing
// bool above transitions to false.
noOngoingFlushStartTime time.Time
}
// Non-zero when file cleaning is disabled. The disabled count acts as a
// reference count to prohibit file cleaning. See
// DB.{disable,Enable}FileDeletions().
disableFileDeletions int
snapshots struct {
// The list of active snapshots.
snapshotList
// The cumulative count and size of snapshot-pinned keys written to
// sstables.
cumulativePinnedCount uint64
cumulativePinnedSize uint64
}
tableStats struct {
// Condition variable used to signal the completion of a
// job to collect table stats.
cond sync.Cond
// True when a stat collection operation is in progress.
loading bool
// True if stat collection has loaded statistics for all tables
// other than those listed explicitly in pending. This flag starts
// as false when a database is opened and flips to true once stat
// collection has caught up.
loadedInitial bool
// A slice of files for which stats have not been computed.
// Compactions, ingests, flushes append files to be processed. An
// active stat collection goroutine clears the list and processes
// them.
pending []manifest.NewFileEntry
}
tableValidation struct {
// cond is a condition variable used to signal the completion of a
// job to validate one or more sstables.
cond sync.Cond
// pending is a slice of metadata for sstables waiting to be
// validated. Only physical sstables should be added to the pending
// queue.
pending []newFileEntry
// validating is set to true when validation is running.
validating bool
}
// annotators contains various instances of manifest.Annotator which
// should be protected from concurrent access.
annotators struct {
totalSize *manifest.Annotator[uint64]
remoteSize *manifest.Annotator[uint64]
externalSize *manifest.Annotator[uint64]
}
}
// Normally equal to time.Now() but may be overridden in tests.
timeNow func() time.Time
// the time at database Open; may be used to compute metrics like effective
// compaction concurrency
openedAt time.Time
}
var _ Reader = (*DB)(nil)
var _ Writer = (*DB)(nil)
// TestOnlyWaitForCleaning MUST only be used in tests.
func (d *DB) TestOnlyWaitForCleaning() {
d.cleanupManager.Wait()
}
// Get gets the value for the given key. It returns ErrNotFound if the DB does
// not contain the key.
//
// The caller should not modify the contents of the returned slice, but it is
// safe to modify the contents of the argument after Get returns. The returned
// slice will remain valid until the returned Closer is closed. On success, the
// caller MUST call closer.Close() or a memory leak will occur.
func (d *DB) Get(key []byte) ([]byte, io.Closer, error) {
return d.getInternal(key, nil /* batch */, nil /* snapshot */)
}
type getIterAlloc struct {
dbi Iterator
keyBuf []byte
get getIter
}
var getIterAllocPool = sync.Pool{
New: func() interface{} {
return &getIterAlloc{}
},
}
func (d *DB) getInternal(key []byte, b *Batch, s *Snapshot) ([]byte, io.Closer, error) {
if err := d.closed.Load(); err != nil {
panic(err)
}
// Grab and reference the current readState. This prevents the underlying
// files in the associated version from being deleted if there is a current
// compaction. The readState is unref'd by Iterator.Close().
readState := d.loadReadState()
// Determine the seqnum to read at after grabbing the read state (current and
// memtables) above.
var seqNum base.SeqNum
if s != nil {
seqNum = s.seqNum
} else {
seqNum = d.mu.versions.visibleSeqNum.Load()
}
buf := getIterAllocPool.Get().(*getIterAlloc)
get := &buf.get
*get = getIter{
comparer: d.opts.Comparer,
newIters: d.newIters,
snapshot: seqNum,
iterOpts: IterOptions{
// TODO(sumeer): replace with a parameter provided by the caller.
CategoryAndQoS: sstable.CategoryAndQoS{
Category: "pebble-get",
QoSLevel: sstable.LatencySensitiveQoSLevel,
},
logger: d.opts.Logger,
snapshotForHideObsoletePoints: seqNum,
},
key: key,
// Compute the key prefix for bloom filtering.
prefix: key[:d.opts.Comparer.Split(key)],
batch: b,
mem: readState.memtables,
l0: readState.current.L0SublevelFiles,
version: readState.current,
}
// Strip off memtables which cannot possibly contain the seqNum being read
// at.
for len(get.mem) > 0 {
n := len(get.mem)
if logSeqNum := get.mem[n-1].logSeqNum; logSeqNum < seqNum {
break
}
get.mem = get.mem[:n-1]
}
i := &buf.dbi
pointIter := get
*i = Iterator{
ctx: context.Background(),
getIterAlloc: buf,
iter: pointIter,
pointIter: pointIter,
merge: d.merge,
comparer: *d.opts.Comparer,
readState: readState,
keyBuf: buf.keyBuf,
}
if !i.First() {
err := i.Close()
if err != nil {
return nil, nil, err
}
return nil, nil, ErrNotFound
}
return i.Value(), i, nil
}
// Set sets the value for the given key. It overwrites any previous value
// for that key; a DB is not a multi-map.
//
// It is safe to modify the contents of the arguments after Set returns.
func (d *DB) Set(key, value []byte, opts *WriteOptions) error {
b := newBatch(d)
_ = b.Set(key, value, opts)
if err := d.Apply(b, opts); err != nil {
return err
}
// Only release the batch on success.
return b.Close()
}
// Delete deletes the value for the given key. Deletes are blind all will
// succeed even if the given key does not exist.
//
// It is safe to modify the contents of the arguments after Delete returns.
func (d *DB) Delete(key []byte, opts *WriteOptions) error {
b := newBatch(d)
_ = b.Delete(key, opts)
if err := d.Apply(b, opts); err != nil {
return err
}
// Only release the batch on success.
return b.Close()
}
// DeleteSized behaves identically to Delete, but takes an additional
// argument indicating the size of the value being deleted. DeleteSized
// should be preferred when the caller has the expectation that there exists
// a single internal KV pair for the key (eg, the key has not been
// overwritten recently), and the caller knows the size of its value.
//
// DeleteSized will record the value size within the tombstone and use it to
// inform compaction-picking heuristics which strive to reduce space
// amplification in the LSM. This "calling your shot" mechanic allows the
// storage engine to more accurately estimate and reduce space amplification.
//
// It is safe to modify the contents of the arguments after DeleteSized
// returns.
func (d *DB) DeleteSized(key []byte, valueSize uint32, opts *WriteOptions) error {
b := newBatch(d)
_ = b.DeleteSized(key, valueSize, opts)
if err := d.Apply(b, opts); err != nil {
return err
}
// Only release the batch on success.
return b.Close()
}
// SingleDelete adds an action to the batch that single deletes the entry for key.
// See Writer.SingleDelete for more details on the semantics of SingleDelete.
//
// It is safe to modify the contents of the arguments after SingleDelete returns.
func (d *DB) SingleDelete(key []byte, opts *WriteOptions) error {
b := newBatch(d)
_ = b.SingleDelete(key, opts)
if err := d.Apply(b, opts); err != nil {
return err
}
// Only release the batch on success.
return b.Close()
}
// DeleteRange deletes all of the keys (and values) in the range [start,end)
// (inclusive on start, exclusive on end).
//
// It is safe to modify the contents of the arguments after DeleteRange
// returns.
func (d *DB) DeleteRange(start, end []byte, opts *WriteOptions) error {
b := newBatch(d)
_ = b.DeleteRange(start, end, opts)
if err := d.Apply(b, opts); err != nil {
return err
}
// Only release the batch on success.
return b.Close()
}
// Merge adds an action to the DB that merges the value at key with the new
// value. The details of the merge are dependent upon the configured merge
// operator.
//
// It is safe to modify the contents of the arguments after Merge returns.
func (d *DB) Merge(key, value []byte, opts *WriteOptions) error {
b := newBatch(d)
_ = b.Merge(key, value, opts)
if err := d.Apply(b, opts); err != nil {
return err
}
// Only release the batch on success.
return b.Close()
}
// LogData adds the specified to the batch. The data will be written to the
// WAL, but not added to memtables or sstables. Log data is never indexed,
// which makes it useful for testing WAL performance.
//
// It is safe to modify the contents of the argument after LogData returns.
func (d *DB) LogData(data []byte, opts *WriteOptions) error {
b := newBatch(d)
_ = b.LogData(data, opts)
if err := d.Apply(b, opts); err != nil {
return err
}
// Only release the batch on success.
return b.Close()
}
// RangeKeySet sets a range key mapping the key range [start, end) at the MVCC
// timestamp suffix to value. The suffix is optional. If any portion of the key
// range [start, end) is already set by a range key with the same suffix value,
// RangeKeySet overrides it.
//
// It is safe to modify the contents of the arguments after RangeKeySet returns.
func (d *DB) RangeKeySet(start, end, suffix, value []byte, opts *WriteOptions) error {
b := newBatch(d)
_ = b.RangeKeySet(start, end, suffix, value, opts)
if err := d.Apply(b, opts); err != nil {
return err
}
// Only release the batch on success.
return b.Close()
}
// RangeKeyUnset removes a range key mapping the key range [start, end) at the
// MVCC timestamp suffix. The suffix may be omitted to remove an unsuffixed
// range key. RangeKeyUnset only removes portions of range keys that fall within
// the [start, end) key span, and only range keys with suffixes that exactly
// match the unset suffix.
//
// It is safe to modify the contents of the arguments after RangeKeyUnset
// returns.
func (d *DB) RangeKeyUnset(start, end, suffix []byte, opts *WriteOptions) error {
b := newBatch(d)
_ = b.RangeKeyUnset(start, end, suffix, opts)
if err := d.Apply(b, opts); err != nil {
return err
}
// Only release the batch on success.
return b.Close()
}
// RangeKeyDelete deletes all of the range keys in the range [start,end)
// (inclusive on start, exclusive on end). It does not delete point keys (for
// that use DeleteRange). RangeKeyDelete removes all range keys within the
// bounds, including those with or without suffixes.
//
// It is safe to modify the contents of the arguments after RangeKeyDelete
// returns.
func (d *DB) RangeKeyDelete(start, end []byte, opts *WriteOptions) error {
b := newBatch(d)
_ = b.RangeKeyDelete(start, end, opts)
if err := d.Apply(b, opts); err != nil {
return err
}
// Only release the batch on success.
return b.Close()
}
// Apply the operations contained in the batch to the DB. If the batch is large
// the contents of the batch may be retained by the database. If that occurs
// the batch contents will be cleared preventing the caller from attempting to
// reuse them.
//
// It is safe to modify the contents of the arguments after Apply returns.
//
// Apply returns ErrInvalidBatch if the provided batch is invalid in any way.
func (d *DB) Apply(batch *Batch, opts *WriteOptions) error {
return d.applyInternal(batch, opts, false)
}
// ApplyNoSyncWait must only be used when opts.Sync is true and the caller
// does not want to wait for the WAL fsync to happen. The method will return
// once the mutation is applied to the memtable and is visible (note that a
// mutation is visible before the WAL sync even in the wait case, so we have
// not weakened the durability semantics). The caller must call Batch.SyncWait
// to wait for the WAL fsync. The caller must not Close the batch without
// first calling Batch.SyncWait.
//
// RECOMMENDATION: Prefer using Apply unless you really understand why you
// need ApplyNoSyncWait.
// EXPERIMENTAL: API/feature subject to change. Do not yet use outside
// CockroachDB.
func (d *DB) ApplyNoSyncWait(batch *Batch, opts *WriteOptions) error {
if !opts.Sync {
return errors.Errorf("cannot request asynchonous apply when WriteOptions.Sync is false")
}
return d.applyInternal(batch, opts, true)
}
// REQUIRES: noSyncWait => opts.Sync
func (d *DB) applyInternal(batch *Batch, opts *WriteOptions, noSyncWait bool) error {
if err := d.closed.Load(); err != nil {
panic(err)
}
if batch.committing {
panic("pebble: batch already committing")
}
if batch.applied.Load() {
panic("pebble: batch already applied")
}
if d.opts.ReadOnly {
return ErrReadOnly
}
if batch.db != nil && batch.db != d {
panic(fmt.Sprintf("pebble: batch db mismatch: %p != %p", batch.db, d))
}
sync := opts.GetSync()
if sync && d.opts.DisableWAL {
return errors.New("pebble: WAL disabled")
}
if fmv := d.FormatMajorVersion(); fmv < batch.minimumFormatMajorVersion {
panic(fmt.Sprintf(
"pebble: batch requires at least format major version %d (current: %d)",
batch.minimumFormatMajorVersion, fmv,
))
}
if batch.countRangeKeys > 0 {
if d.split == nil {
return errNoSplit
}
}
batch.committing = true
if batch.db == nil {
if err := batch.refreshMemTableSize(); err != nil {
return err
}
}
if batch.memTableSize >= d.largeBatchThreshold {
var err error
batch.flushable, err = newFlushableBatch(batch, d.opts.Comparer)
if err != nil {
return err
}
}
if err := d.commit.Commit(batch, sync, noSyncWait); err != nil {
// There isn't much we can do on an error here. The commit pipeline will be
// horked at this point.
d.opts.Logger.Fatalf("pebble: fatal commit error: %v", err)
}
// If this is a large batch, we need to clear the batch contents as the
// flushable batch may still be present in the flushables queue.
//
// TODO(peter): Currently large batches are written to the WAL. We could
// skip the WAL write and instead wait for the large batch to be flushed to
// an sstable. For a 100 MB batch, this might actually be faster. For a 1
// GB batch this is almost certainly faster.
if batch.flushable != nil {
batch.data = nil
}
return nil
}
func (d *DB) commitApply(b *Batch, mem *memTable) error {
if b.flushable != nil {
// This is a large batch which was already added to the immutable queue.
return nil
}
err := mem.apply(b, b.SeqNum())
if err != nil {
return err
}
// If the batch contains range tombstones and the database is configured
// to flush range deletions, schedule a delayed flush so that disk space
// may be reclaimed without additional writes or an explicit flush.
if b.countRangeDels > 0 && d.opts.FlushDelayDeleteRange > 0 {
d.mu.Lock()
d.maybeScheduleDelayedFlush(mem, d.opts.FlushDelayDeleteRange)
d.mu.Unlock()
}
// If the batch contains range keys and the database is configured to flush
// range keys, schedule a delayed flush so that the range keys are cleared
// from the memtable.
if b.countRangeKeys > 0 && d.opts.FlushDelayRangeKey > 0 {
d.mu.Lock()
d.maybeScheduleDelayedFlush(mem, d.opts.FlushDelayRangeKey)
d.mu.Unlock()
}
if mem.writerUnref() {
d.mu.Lock()
d.maybeScheduleFlush()
d.mu.Unlock()
}
return nil
}
func (d *DB) commitWrite(b *Batch, syncWG *sync.WaitGroup, syncErr *error) (*memTable, error) {
var size int64
repr := b.Repr()
if b.flushable != nil {
// We have a large batch. Such batches are special in that they don't get
// added to the memtable, and are instead inserted into the queue of
// memtables. The call to makeRoomForWrite with this batch will force the
// current memtable to be flushed. We want the large batch to be part of
// the same log, so we add it to the WAL here, rather than after the call
// to makeRoomForWrite().
//
// Set the sequence number since it was not set to the correct value earlier
// (see comment in newFlushableBatch()).
b.flushable.setSeqNum(b.SeqNum())
if !d.opts.DisableWAL {
var err error
size, err = d.mu.log.writer.WriteRecord(repr, wal.SyncOptions{Done: syncWG, Err: syncErr}, b)
if err != nil {
panic(err)
}
}
}
var err error
// Grab a reference to the memtable. We don't hold DB.mu, but we do hold
// d.commit.mu. It's okay for readers of d.mu.mem.mutable to only hold one of
// d.commit.mu or d.mu, because memtable rotations require holding both.
mem := d.mu.mem.mutable
// Batches which contain keys of kind InternalKeyKindIngestSST will
// never be applied to the memtable, so we don't need to make room for
// write.
if !b.ingestedSSTBatch {
// Flushable batches will require a rotation of the memtable regardless,
// so only attempt an optimistic reservation of space in the current
// memtable if this batch is not a large flushable batch.
if b.flushable == nil {
err = d.mu.mem.mutable.prepare(b)
}
if b.flushable != nil || err == arenaskl.ErrArenaFull {
// Slow path.
// We need to acquire DB.mu and rotate the memtable.
func() {
d.mu.Lock()
defer d.mu.Unlock()
err = d.makeRoomForWrite(b)
mem = d.mu.mem.mutable
}()
}
}
if err != nil {
return nil, err
}
if d.opts.DisableWAL {
return mem, nil
}
d.logBytesIn.Add(uint64(len(repr)))
if b.flushable == nil {
size, err = d.mu.log.writer.WriteRecord(repr, wal.SyncOptions{Done: syncWG, Err: syncErr}, b)
if err != nil {
panic(err)
}
}
d.logSize.Store(uint64(size))
return mem, err
}
type iterAlloc struct {
dbi Iterator
keyBuf []byte
boundsBuf [2][]byte
prefixOrFullSeekKey []byte
merging mergingIter
mlevels [3 + numLevels]mergingIterLevel
levels [3 + numLevels]levelIter