-
Notifications
You must be signed in to change notification settings - Fork 456
/
db.go
1428 lines (1286 loc) · 46.5 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 (
"fmt"
"io"
"runtime"
"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/invariants"
"github.com/cockroachdb/pebble/internal/manifest"
"github.com/cockroachdb/pebble/internal/manual"
"github.com/cockroachdb/pebble/internal/record"
"github.com/cockroachdb/pebble/vfs"
)
const (
// minTableCacheSize is the minimum size of the table cache.
minTableCacheSize = 64
// numNonTableCacheFiles is an approximation for the number of MaxOpenFiles
// that we don't use for table caches.
numNonTableCacheFiles = 10
)
var (
// ErrNotFound is returned when a get operation does not find the requested
// key.
ErrNotFound = base.ErrNotFound
// ErrClosed is returned when an operation is performed on a closed snapshot
// or DB.
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")
)
// 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
// 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
// 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 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 Delete 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
}
// 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 {
cacheID uint64
dirname string
walDirname 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 int
// The current OPTIONS file number.
optionsFileNum FileNum
fileLock io.Closer
dataDir vfs.File
walDir vfs.File
tableCache tableCache
newIters tableNewIters
commit *commitPipeline
// readState provides access to the state needed for reading without needing
// to acquire DB.mu.
readState struct {
sync.RWMutex
val *readState
}
// logRecycler holds a set of log file numbers that are available for
// reuse. Writing to a recycled log file is faster than to a new log file on
// some common filesystems (xfs, and ext3/4) due to avoiding metadata
// updates.
logRecycler logRecycler
closed int32 // updated atomically
// 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.
memTableCount int64
memTableReserved int64 // number of bytes reserved in the cache for memtables
compactionLimiter limiter
// bytesFlushed is the number of bytes flushed in the current flush. This
// must be read/written atomically since it is accessed by both the flush
// and compaction routines.
bytesFlushed uint64
// bytesCompacted is the number of bytes compacted in the current compaction.
// This is used as a dummy variable to increment during compaction, and the
// value is not used anywhere.
bytesCompacted uint64
flushLimiter limiter
// 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
// 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 int
// The collection of immutable versions and state about the log and visible
// sequence numbers.
versions versionSet
log struct {
// The queue of logs, containing both flushed and unflushed logs. The
// flushed logs will be a prefix, the unflushed logs a suffix. The
// delimeter between flushed and unflushed logs is
// versionSet.minUnflushedLogNum.
queue []FileNum
// The size of the current log file (i.e. queue[len(queue)-1].
size 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.
bytesIn uint64
// The LogWriter 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).
*record.LogWriter
}
mem struct {
// Condition variable used to serialize memtable switching. See
// DB.makeRoomForWrite().
cond sync.Cond
// The current mutable 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
// True when the memtable is actively been switched. Both mem.mutable and
// log.LogWriter are invalid while switching is true.
switching bool
// 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 int
}
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 compactions.
compactingCount int
// 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
// inProgress is the set of in-progress flushes and compactions.
inProgress map[*compaction]struct{}
}
cleaner struct {
// Condition variable used to signal the completion of a file cleaning
// operation or an increment to the value of disabled. File cleaning operations are
// serialized, and a caller trying to do a file cleaning operation may wait
// until the ongoing one is complete.
cond sync.Cond
// True when a file cleaning operation is in progress.
cleaning bool
// Non-zero when file cleaning is disabled. The disabled count acts as a
// reference count to prohibit file cleaning. See
// DB.{disable,Enable}FileDeletions().
disabled int
}
// The list of active snapshots.
snapshots snapshotList
}
// Normally equal to time.Now() but may be overridden in tests.
timeNow func() time.Time
}
var _ Reader = (*DB)(nil)
var _ Writer = (*DB)(nil)
// 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 */)
}
func (d *DB) getInternal(key []byte, b *Batch, s *Snapshot) ([]byte, io.Closer, error) {
if atomic.LoadInt32(&d.closed) != 0 {
panic(ErrClosed)
}
// 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 uint64
if s != nil {
seqNum = s.seqNum
} else {
seqNum = atomic.LoadUint64(&d.mu.versions.visibleSeqNum)
}
var buf struct {
dbi Iterator
get getIter
}
get := &buf.get
get.logger = d.opts.Logger
get.cmp = d.cmp
get.equal = d.equal
get.newIters = d.newIters
get.snapshot = seqNum
get.key = key
get.batch = b
get.mem = readState.memtables
get.l0 = readState.current.L0SubLevels.Files
get.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
i.cmp = d.cmp
i.equal = d.equal
i.merge = d.merge
i.split = d.split
i.iter = get
i.readState = readState
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.
b.release()
return nil
}
// 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.
b.release()
return nil
}
// 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.
b.release()
return nil
}
// 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.
b.release()
return nil
}
// 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.
b.release()
return nil
}
// 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.
b.release()
return nil
}
// 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.
func (d *DB) Apply(batch *Batch, opts *WriteOptions) error {
if atomic.LoadInt32(&d.closed) != 0 {
panic(ErrClosed)
}
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 batch.db == nil {
batch.refreshMemTableSize()
}
if int(batch.memTableSize) >= d.largeBatchThreshold {
batch.flushable = newFlushableBatch(batch, d.opts.Comparer)
}
if err := d.commit.Commit(batch, sync); 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("%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 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.SyncRecord(repr, syncWG, syncErr)
if err != nil {
panic(err)
}
}
}
d.mu.Lock()
// Switch out the memtable if there was not enough room to store the batch.
err := d.makeRoomForWrite(b)
if err == nil && !d.opts.DisableWAL {
d.mu.log.bytesIn += uint64(len(repr))
}
// Grab a reference to the memtable while holding DB.mu. Note that for
// non-flushable batches (b.flushable == nil) makeRoomForWrite() added a
// reference to the memtable which will prevent it from being flushed until
// we unreference it. This reference is dropped in DB.commitApply().
mem := d.mu.mem.mutable
d.mu.Unlock()
if err != nil {
return nil, err
}
if d.opts.DisableWAL {
return mem, nil
}
if b.flushable == nil {
size, err = d.mu.log.SyncRecord(repr, syncWG, syncErr)
if err != nil {
panic(err)
}
}
atomic.StoreUint64(&d.mu.log.size, uint64(size))
return mem, err
}
type iterAlloc struct {
dbi Iterator
merging mergingIter
mlevels [3 + numLevels]mergingIterLevel
levels [3 + numLevels]levelIter
}
var iterAllocPool = sync.Pool{
New: func() interface{} {
return &iterAlloc{}
},
}
// newIterInternal constructs a new iterator, merging in batchIter as an extra
// level.
func (d *DB) newIterInternal(
batchIter internalIterator, batchRangeDelIter internalIterator, s *Snapshot, o *IterOptions,
) *Iterator {
if atomic.LoadInt32(&d.closed) != 0 {
panic(ErrClosed)
}
// 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 uint64
if s != nil {
seqNum = s.seqNum
} else {
seqNum = atomic.LoadUint64(&d.mu.versions.visibleSeqNum)
}
// Bundle various structures under a single umbrella in order to allocate
// them together.
buf := iterAllocPool.Get().(*iterAlloc)
dbi := &buf.dbi
*dbi = Iterator{
alloc: buf,
cmp: d.cmp,
equal: d.equal,
iter: &buf.merging,
merge: d.merge,
split: d.split,
readState: readState,
}
if o != nil {
dbi.opts = *o
}
dbi.opts.logger = d.opts.Logger
mlevels := buf.mlevels[:0]
if batchIter != nil {
mlevels = append(mlevels, mergingIterLevel{
iter: batchIter,
rangeDelIter: batchRangeDelIter,
})
}
memtables := readState.memtables
for i := len(memtables) - 1; i >= 0; i-- {
mem := memtables[i]
// We only need to read from memtables which contain sequence numbers older
// than seqNum.
if logSeqNum := mem.logSeqNum; logSeqNum >= seqNum {
continue
}
mlevels = append(mlevels, mergingIterLevel{
iter: mem.newIter(&dbi.opts),
rangeDelIter: mem.newRangeDelIter(&dbi.opts),
})
}
// Determine the final size for mlevels so that we can avoid any more
// reallocations. This is important because each levelIter will hold a
// reference to elements in mlevels.
start := len(mlevels)
current := readState.current
for sl := 0; sl < len(current.L0SubLevels.Files); sl++ {
if len(current.L0SubLevels.Files[sl]) > 0 {
mlevels = append(mlevels, mergingIterLevel{})
}
}
for level := 1; level < len(current.Files); level++ {
if len(current.Files[level]) == 0 {
continue
}
mlevels = append(mlevels, mergingIterLevel{})
}
finalMLevels := mlevels
mlevels = mlevels[start:]
levels := buf.levels[:]
addLevelIterForFiles := func(files []*manifest.FileMetadata, level int) {
if len(files) == 0 {
return
}
var li *levelIter
if len(levels) > 0 {
li = &levels[0]
levels = levels[1:]
} else {
li = &levelIter{}
}
li.init(dbi.opts, d.cmp, d.newIters, files, level, nil)
li.initRangeDel(&mlevels[0].rangeDelIter)
li.initSmallestLargestUserKey(&mlevels[0].smallestUserKey, &mlevels[0].largestUserKey,
&mlevels[0].isLargestUserKeyRangeDelSentinel)
mlevels[0].iter = li
mlevels = mlevels[1:]
}
// Add level iterators for the L0 sublevels, iterating from newest to
// oldest.
for i := len(current.L0SubLevels.Files) - 1; i >= 0; i-- {
addLevelIterForFiles(current.L0SubLevels.Files[i], 0)
}
// Add level iterators for the non-empty non-L0 levels.
for level := 1; level < len(current.Files); level++ {
addLevelIterForFiles(current.Files[level], level)
}
buf.merging.init(&dbi.opts, d.cmp, finalMLevels...)
buf.merging.snapshot = seqNum
buf.merging.elideRangeTombstones = true
return dbi
}
// NewBatch returns a new empty write-only batch. Any reads on the batch will
// return an error. If the batch is committed it will be applied to the DB.
func (d *DB) NewBatch() *Batch {
return newBatch(d)
}
// NewIndexedBatch returns a new empty read-write batch. Any reads on the batch
// will read from both the batch and the DB. If the batch is committed it will
// be applied to the DB. An indexed batch is slower that a non-indexed batch
// for insert operations. If you do not need to perform reads on the batch, use
// NewBatch instead.
func (d *DB) NewIndexedBatch() *Batch {
return newIndexedBatch(d, d.opts.Comparer)
}
// 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. The iterator provides a point-in-time view of the current DB
// state. This view is maintained by preventing file deletions and preventing
// memtables referenced by the iterator from being deleted. Using an iterator
// to maintain a long-lived point-in-time view of the DB state can lead to an
// apparent memory and disk usage leak. Use snapshots (see NewSnapshot) for
// point-in-time snapshots which avoids these problems.
func (d *DB) NewIter(o *IterOptions) *Iterator {
return d.newIterInternal(nil, /* batchIter */
nil /* batchRangeDelIter */, nil /* snapshot */, o)
}
// NewSnapshot returns a point-in-time view of the current DB state. Iterators
// created with this handle will all observe a stable snapshot of the current
// DB state. The caller must call Snapshot.Close() when the snapshot is no
// longer needed. Snapshots are not persisted across DB restarts (close ->
// open). Unlike the implicit snapshot maintained by an iterator, a snapshot
// will not prevent memtables from being released or sstables from being
// deleted. Instead, a snapshot prevents deletion of sequence numbers
// referenced by the snapshot.
func (d *DB) NewSnapshot() *Snapshot {
if atomic.LoadInt32(&d.closed) != 0 {
panic(ErrClosed)
}
s := &Snapshot{
db: d,
seqNum: atomic.LoadUint64(&d.mu.versions.visibleSeqNum),
}
d.mu.Lock()
d.mu.snapshots.pushBack(s)
d.mu.Unlock()
return s
}
// Close closes the DB.
//
// It is not safe to close a DB until all outstanding iterators are closed
// or to call Close concurrently with any other DB method. It is not valid
// to call any of a DB's methods after the DB has been closed.
func (d *DB) Close() error {
d.mu.Lock()
defer d.mu.Unlock()
if atomic.LoadInt32(&d.closed) != 0 {
panic(ErrClosed)
}
atomic.StoreInt32(&d.closed, 1)
defer d.opts.Cache.Unref()
for d.mu.compact.compactingCount > 0 || d.mu.compact.flushing {
d.mu.compact.cond.Wait()
}
var err error
if n := len(d.mu.compact.inProgress); n > 0 {
err = errors.Errorf("pebble: %d unexpected in-progress compactions", errors.Safe(n))
}
err = firstError(err, d.tableCache.Close())
if !d.opts.ReadOnly {
err = firstError(err, d.mu.log.Close())
} else if d.mu.log.LogWriter != nil {
panic("pebble: log-writer should be nil in read-only mode")
}
err = firstError(err, d.fileLock.Close())
// Note that versionSet.close() only closes the MANIFEST. The versions list
// is still valid for the checks below.
err = firstError(err, d.mu.versions.close())
err = firstError(err, d.dataDir.Close())
if d.dataDir != d.walDir {
err = firstError(err, d.walDir.Close())
}
if err == nil {
d.readState.val.unrefLocked()
current := d.mu.versions.currentVersion()
for v := d.mu.versions.versions.Front(); true; v = v.Next() {
refs := v.Refs()
if v == current {
if refs != 1 {
return errors.Errorf("leaked iterators: current\n%s", v)
}
break
}
if refs != 0 {
return errors.Errorf("leaked iterators:\n%s", v)
}
}
for _, mem := range d.mu.mem.queue {
mem.readerUnref()
}
if reserved := atomic.LoadInt64(&d.memTableReserved); reserved != 0 {
return errors.Errorf("leaked memtable reservation: %d", errors.Safe(reserved))
}
}
// No more cleaning can start. Wait for any async cleaning to complete.
for d.mu.cleaner.cleaning {
d.mu.cleaner.cond.Wait()
}
return err
}
// Compact the specified range of keys in the database.
func (d *DB) Compact(
start, end []byte, /* CompactionOptions */
) error {
if atomic.LoadInt32(&d.closed) != 0 {
panic(ErrClosed)
}
if d.opts.ReadOnly {
return ErrReadOnly
}
iStart := base.MakeInternalKey(start, InternalKeySeqNumMax, InternalKeyKindMax)
iEnd := base.MakeInternalKey(end, 0, 0)
meta := []*fileMetadata{&fileMetadata{Smallest: iStart, Largest: iEnd}}
d.mu.Lock()
maxLevelWithFiles := 1
cur := d.mu.versions.currentVersion()
for level := 0; level < numLevels; level++ {
if len(cur.Overlaps(level, d.cmp, start, end)) > 0 {
maxLevelWithFiles = level + 1
}
}
// Determine if any memtable overlaps with the compaction range. We wait for
// any such overlap to flush (initiating a flush if necessary).
mem, err := func() (*flushableEntry, error) {
// Check to see if any files overlap with any of the memtables. The queue
// is ordered from oldest to newest with the mutable memtable being the
// last element in the slice. We want to wait for the newest table that
// overlaps.
for i := len(d.mu.mem.queue) - 1; i >= 0; i-- {
mem := d.mu.mem.queue[i]
if ingestMemtableOverlaps(d.cmp, mem, meta) {
var err error
if mem.flushable == d.mu.mem.mutable {
// We have to hold both commitPipeline.mu and DB.mu when calling
// makeRoomForWrite(). Lock order requirements elsewhere force us to
// unlock DB.mu in order to grab commitPipeline.mu first.
d.mu.Unlock()
d.commit.mu.Lock()
d.mu.Lock()
defer d.commit.mu.Unlock()
if mem.flushable == d.mu.mem.mutable {
// Only flush if the active memtable is unchanged.
err = d.makeRoomForWrite(nil)
}
}
mem.flushForced = true
d.maybeScheduleFlush()
return mem, err
}
}
return nil, nil
}()
d.mu.Unlock()
if err != nil {
return err
}
if mem != nil {
<-mem.flushed
}
for level := 0; level < maxLevelWithFiles; {
manual := &manualCompaction{
done: make(chan error, 1),
level: level,
start: iStart,
end: iEnd,
}
if err := d.manualCompact(manual); err != nil {
return err
}
level = manual.outputLevel
if level == numLevels-1 {
// A manual compaction of the bottommost level occured. There is no next
// level to try and compact.
break
}
}
return nil
}
func (d *DB) manualCompact(manual *manualCompaction) error {
d.mu.Lock()
d.mu.compact.manual = append(d.mu.compact.manual, manual)
d.maybeScheduleCompaction()
d.mu.Unlock()
return <-manual.done
}
// Flush the memtable to stable storage.
func (d *DB) Flush() error {
flushDone, err := d.AsyncFlush()
if err != nil {
return err
}
<-flushDone
return nil
}
// AsyncFlush asynchronously flushes the memtable to stable storage.
//
// If no error is returned, the caller can receive from the returned channel in
// order to wait for the flush to complete.
func (d *DB) AsyncFlush() (<-chan struct{}, error) {
if atomic.LoadInt32(&d.closed) != 0 {
panic(ErrClosed)
}
if d.opts.ReadOnly {
return nil, ErrReadOnly
}
d.commit.mu.Lock()
defer d.commit.mu.Unlock()
d.mu.Lock()
defer d.mu.Unlock()
flushed := d.mu.mem.queue[len(d.mu.mem.queue)-1].flushed
err := d.makeRoomForWrite(nil)
if err != nil {
return nil, err
}
return flushed, nil
}
// Metrics returns metrics about the database.
func (d *DB) Metrics() *Metrics {
metrics := &Metrics{}