forked from cockroachdb/cockroach
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rocksdb.go
1818 lines (1600 loc) · 49.2 KB
/
rocksdb.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 2014 The Cockroach Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
//
// Author: Spencer Kimball (spencer.kimball@gmail.com)
// Author: Andrew Bonventre (andybons@gmail.com)
// Author: Tobias Schottdorf (tobias.schottdorf@gmail.com)
// Author: Jiang-Ming Yang (jiangming.yang@gmail.com)
package engine
import (
"bytes"
"fmt"
"math"
"os"
"path/filepath"
"runtime"
"runtime/debug"
"sort"
"sync"
"time"
"unsafe"
"github.com/dustin/go-humanize"
"github.com/elastic/gosigar"
"github.com/gogo/protobuf/proto"
"github.com/pkg/errors"
"golang.org/x/net/context"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/storage/engine/enginepb"
"github.com/cockroachdb/cockroach/pkg/util/envutil"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/humanizeutil"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/syncutil"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
)
// TODO(tamird): why does rocksdb not link jemalloc,snappy statically?
// #cgo CPPFLAGS: -I../../../c-deps/rocksdb.src/include
// #cgo CPPFLAGS: -I../../../c-deps/protobuf.src/src
// #cgo LDFLAGS: -lprotobuf
// #cgo LDFLAGS: -lrocksdb
// #cgo LDFLAGS: -ljemalloc
// #cgo LDFLAGS: -lsnappy
// #cgo CXXFLAGS: -std=c++11 -Werror -Wall -Wno-sign-compare
// #cgo linux LDFLAGS: -lrt -lm -lpthread
// #cgo windows LDFLAGS: -lrpcrt4
//
// #include <stdlib.h>
// #include "db.h"
import "C"
//export rocksDBLog
func rocksDBLog(s *C.char, n C.int) {
// Note that rocksdb logging is only enabled if log.V(3) is true
// when RocksDB.Open() is called.
log.Info(context.TODO(), C.GoStringN(s, n))
}
//export prettyPrintKey
func prettyPrintKey(cKey C.DBKey) *C.char {
mvccKey := MVCCKey{
Key: C.GoBytes(unsafe.Pointer(cKey.key.data), cKey.key.len),
Timestamp: hlc.Timestamp{
WallTime: int64(cKey.wall_time),
Logical: int32(cKey.logical),
},
}
return C.CString(mvccKey.String())
}
const (
defaultBlockSize = 32 << 10 // 32KB (rocksdb default is 4KB)
// DefaultMaxOpenFiles is the default value for rocksDB's max_open_files
// option.
DefaultMaxOpenFiles = -1
// RecommendedMaxOpenFiles is the recommended value for rocksDB's
// max_open_files option. If more file descriptors are available than the
// recommended number, than the default value is used.
RecommendedMaxOpenFiles = 10000
// MinimumMaxOpenFiles is The minimum value that rocksDB's max_open_files
// option can be set to. While this should be set as high as possible, the
// minimum total for a single store node must be under 2048 for Windows
// compatibility. See:
// https://wpdev.uservoice.com/forums/266908-command-prompt-console-bash-on-ubuntu-on-windo/suggestions/17310124-add-ability-to-change-max-number-of-open-files-for
MinimumMaxOpenFiles = 1700
)
var useDirectWrites = envutil.EnvOrDefaultBool("COCKROACH_USE_DIRECT_WRITES", false)
// SSTableInfo contains metadata about a single RocksDB sstable. This mirrors
// the C.DBSSTable struct contents.
type SSTableInfo struct {
Level int
Size int64
Start MVCCKey
End MVCCKey
}
// SSTableInfos is a slice of SSTableInfo structures.
type SSTableInfos []SSTableInfo
func (s SSTableInfos) Len() int {
return len(s)
}
func (s SSTableInfos) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s SSTableInfos) Less(i, j int) bool {
switch {
case s[i].Level < s[j].Level:
return true
case s[i].Level > s[j].Level:
return false
case s[i].Size > s[j].Size:
return true
case s[i].Size < s[j].Size:
return false
default:
return s[i].Start.Less(s[j].Start)
}
}
func (s SSTableInfos) String() string {
const (
KB = 1 << 10
MB = 1 << 20
GB = 1 << 30
TB = 1 << 40
)
roundTo := func(val, to int64) int64 {
return (val + to/2) / to
}
// We're intentionally not using humanizeutil here as we want a slightly more
// compact representation.
humanize := func(size int64) string {
switch {
case size < MB:
return fmt.Sprintf("%dK", roundTo(size, KB))
case size < GB:
return fmt.Sprintf("%dM", roundTo(size, MB))
case size < TB:
return fmt.Sprintf("%dG", roundTo(size, GB))
default:
return fmt.Sprintf("%dT", roundTo(size, TB))
}
}
type levelInfo struct {
size int64
count int
}
var levels []*levelInfo
for _, t := range s {
for i := len(levels); i <= t.Level; i++ {
levels = append(levels, &levelInfo{})
}
info := levels[t.Level]
info.size += t.Size
info.count++
}
var maxSize int
var maxLevelCount int
for _, info := range levels {
size := len(humanize(info.size))
if maxSize < size {
maxSize = size
}
count := 1 + int(math.Log10(float64(info.count)))
if maxLevelCount < count {
maxLevelCount = count
}
}
levelFormat := fmt.Sprintf("%%d [ %%%ds %%%dd ]:", maxSize, maxLevelCount)
level := -1
var buf bytes.Buffer
var lastSize string
var lastSizeCount int
flushLastSize := func() {
if lastSizeCount > 0 {
fmt.Fprintf(&buf, " %s", lastSize)
if lastSizeCount > 1 {
fmt.Fprintf(&buf, "[%d]", lastSizeCount)
}
lastSizeCount = 0
}
}
maybeFlush := func(newLevel, i int) {
if level == newLevel {
return
}
flushLastSize()
if buf.Len() > 0 {
buf.WriteString("\n")
}
level = newLevel
if level >= 0 {
info := levels[level]
fmt.Fprintf(&buf, levelFormat, level, humanize(info.size), info.count)
}
}
for i, t := range s {
maybeFlush(t.Level, i)
size := humanize(t.Size)
if size == lastSize {
lastSizeCount++
} else {
flushLastSize()
lastSize = size
lastSizeCount = 1
}
}
maybeFlush(-1, 0)
return buf.String()
}
// ReadAmplification returns RocksDB's read amplification, which is the number
// of level-0 sstables plus the number of levels, other than level 0, with at
// least one sstable.
//
// This definition comes from here:
// https://github.com/facebook/rocksdb/wiki/RocksDB-Tuning-Guide#level-style-compaction
func (s SSTableInfos) ReadAmplification() int {
var readAmp int
seenLevel := make(map[int]bool)
for _, t := range s {
if t.Level == 0 {
readAmp++
} else if !seenLevel[t.Level] {
readAmp++
seenLevel[t.Level] = true
}
}
return readAmp
}
// RocksDBCache is a wrapper around C.DBCache
type RocksDBCache struct {
cache *C.DBCache
}
// NewRocksDBCache creates a new cache of the specified size. Note that the
// cache is refcounted internally and starts out with a refcount of one (i.e.
// Release() should be called after having used the cache).
func NewRocksDBCache(cacheSize int64) RocksDBCache {
return RocksDBCache{cache: C.DBNewCache(C.uint64_t(cacheSize))}
}
func (c RocksDBCache) ref() RocksDBCache {
if c.cache != nil {
c.cache = C.DBRefCache(c.cache)
}
return c
}
// Release releases the cache. Note that the cache will continue to be used
// until all of the RocksDB engines it was attached to have been closed, and
// that RocksDB engines which use it auto-release when they close.
func (c RocksDBCache) Release() {
if c.cache != nil {
C.DBReleaseCache(c.cache)
}
}
// RocksDB is a wrapper around a RocksDB database instance.
type RocksDB struct {
rdb *C.DBEngine
attrs roachpb.Attributes // Attributes for this engine
dir string // The data directory
tempDir string // A path for storing temp files (ideally under dir).
cache RocksDBCache // Shared cache.
maxSize int64 // Used for calculating rebalancing and free space.
maxOpenFiles int // The maximum number of open files this instance will use.
deallocated chan struct{} // Closed when the underlying handle is deallocated.
commit struct {
syncutil.Mutex
cond *sync.Cond
committing bool
commitSeq uint64
pendingSeq uint64
pendingSync bool
pending []*rocksDBBatch
}
}
var _ Engine = &RocksDB{}
// NewRocksDB allocates and returns a new RocksDB object.
// This creates options and opens the database. If the database
// doesn't yet exist at the specified directory, one is initialized
// from scratch.
// The caller must call the engine's Close method when the engine is no longer
// needed.
func NewRocksDB(
attrs roachpb.Attributes, dir string, cache RocksDBCache, maxSize int64, maxOpenFiles int,
) (*RocksDB, error) {
if dir == "" {
panic("dir must be non-empty")
}
r := &RocksDB{
attrs: attrs,
dir: dir,
cache: cache.ref(),
maxSize: maxSize,
maxOpenFiles: maxOpenFiles,
deallocated: make(chan struct{}),
}
temp := filepath.Join(dir, "tmp")
if err := os.RemoveAll(temp); err != nil {
return nil, err
}
if err := r.SetTempDir(temp); err != nil {
return nil, err
}
if err := r.open(); err != nil {
return nil, err
}
return r, nil
}
func newMemRocksDB(attrs roachpb.Attributes, cache RocksDBCache, maxSize int64) (*RocksDB, error) {
r := &RocksDB{
attrs: attrs,
// dir: empty dir == "mem" RocksDB instance.
cache: cache.ref(),
maxSize: maxSize,
deallocated: make(chan struct{}),
}
if err := r.SetTempDir(os.TempDir()); err != nil {
return nil, err
}
if err := r.open(); err != nil {
return nil, err
}
return r, nil
}
// String formatter.
func (r *RocksDB) String() string {
return fmt.Sprintf("%s=%s", r.attrs.Attrs, r.dir)
}
func (r *RocksDB) open() error {
var ver storageVersion
if len(r.dir) != 0 {
log.Infof(context.TODO(), "opening rocksdb instance at %q", r.dir)
// Check the version number.
var err error
if ver, err = getVersion(r.dir); err != nil {
return err
}
if ver < versionMinimum || ver > versionCurrent {
// Instead of an error, we should call a migration if possible when
// one is needed immediately following the DBOpen call.
return fmt.Errorf("incompatible rocksdb data version, current:%d, on disk:%d, minimum:%d",
versionCurrent, ver, versionMinimum)
}
} else {
if log.V(2) {
log.Infof(context.TODO(), "opening in memory rocksdb instance")
}
// In memory dbs are always current.
ver = versionCurrent
}
blockSize := envutil.EnvOrDefaultBytes("COCKROACH_ROCKSDB_BLOCK_SIZE", defaultBlockSize)
walTTL := envutil.EnvOrDefaultDuration("COCKROACH_ROCKSDB_WAL_TTL", 0).Seconds()
status := C.DBOpen(&r.rdb, goToCSlice([]byte(r.dir)),
C.DBOptions{
cache: r.cache.cache,
block_size: C.uint64_t(blockSize),
wal_ttl_seconds: C.uint64_t(walTTL),
use_direct_writes: C.bool(useDirectWrites),
logging_enabled: C.bool(log.V(3)),
num_cpu: C.int(runtime.NumCPU()),
max_open_files: C.int(r.maxOpenFiles),
})
if err := statusToError(status); err != nil {
return errors.Errorf("could not open rocksdb instance: %s", err)
}
// Update or add the version file if needed.
if ver < versionCurrent {
if err := writeVersionFile(r.dir); err != nil {
return err
}
}
r.commit.cond = sync.NewCond(&r.commit.Mutex)
// Start a goroutine that will finish when the underlying handle
// is deallocated. This is used to check a leak in tests.
go func() {
<-r.deallocated
}()
return nil
}
// Close closes the database by deallocating the underlying handle.
func (r *RocksDB) Close() {
if r.rdb == nil {
log.Errorf(context.TODO(), "closing unopened rocksdb instance")
return
}
if len(r.dir) == 0 {
if log.V(1) {
log.Infof(context.TODO(), "closing in-memory rocksdb instance")
}
} else {
log.Infof(context.TODO(), "closing rocksdb instance at %q", r.dir)
}
if r.rdb != nil {
C.DBClose(r.rdb)
r.rdb = nil
}
r.cache.Release()
close(r.deallocated)
}
// Closed returns true if the engine is closed.
func (r *RocksDB) Closed() bool {
return r.rdb == nil
}
// Attrs returns the list of attributes describing this engine. This
// may include a specification of disk type (e.g. hdd, ssd, fio, etc.)
// and potentially other labels to identify important attributes of
// the engine.
func (r *RocksDB) Attrs() roachpb.Attributes {
return r.attrs
}
// Put sets the given key to the value provided.
//
// The key and value byte slices may be reused safely. put takes a copy of
// them before returning.
func (r *RocksDB) Put(key MVCCKey, value []byte) error {
return dbPut(r.rdb, key, value)
}
// Merge implements the RocksDB merge operator using the function goMergeInit
// to initialize missing values and goMerge to merge the old and the given
// value into a new value, which is then stored under key.
// Currently 64-bit counter logic is implemented. See the documentation of
// goMerge and goMergeInit for details.
//
// The key and value byte slices may be reused safely. merge takes a copy
// of them before returning.
func (r *RocksDB) Merge(key MVCCKey, value []byte) error {
return dbMerge(r.rdb, key, value)
}
// ApplyBatchRepr atomically applies a set of batched updates. Created by
// calling Repr() on a batch. Using this method is equivalent to constructing
// and committing a batch whose Repr() equals repr.
func (r *RocksDB) ApplyBatchRepr(repr []byte, sync bool) error {
return dbApplyBatchRepr(r.rdb, repr, sync)
}
// Get returns the value for the given key.
func (r *RocksDB) Get(key MVCCKey) ([]byte, error) {
return dbGet(r.rdb, key)
}
// GetProto fetches the value at the specified key and unmarshals it.
func (r *RocksDB) GetProto(
key MVCCKey, msg proto.Message,
) (ok bool, keyBytes, valBytes int64, err error) {
return dbGetProto(r.rdb, key, msg)
}
// Clear removes the item from the db with the given key.
func (r *RocksDB) Clear(key MVCCKey) error {
return dbClear(r.rdb, key)
}
// ClearRange removes a set of entries, from start (inclusive) to end
// (exclusive).
func (r *RocksDB) ClearRange(start, end MVCCKey) error {
return dbClearRange(r.rdb, start, end)
}
// ClearIterRange removes a set of entries, from start (inclusive) to end
// (exclusive).
func (r *RocksDB) ClearIterRange(iter Iterator, start, end MVCCKey) error {
return dbClearIterRange(r.rdb, iter, start, end)
}
// Iterate iterates from start to end keys, invoking f on each
// key/value pair. See engine.Iterate for details.
func (r *RocksDB) Iterate(start, end MVCCKey, f func(MVCCKeyValue) (bool, error)) error {
return dbIterate(r.rdb, r, start, end, f)
}
// Capacity queries the underlying file system for disk capacity information.
func (r *RocksDB) Capacity() (roachpb.StoreCapacity, error) {
fileSystemUsage := gosigar.FileSystemUsage{}
dir := r.dir
if dir == "" {
// This is an in-memory instance. Pretend we're empty since we
// don't know better and only use this for testing. Using any
// part of the actual file system here can throw off allocator
// rebalancing in a hard-to-trace manner. See #7050.
return roachpb.StoreCapacity{
Capacity: r.maxSize,
Available: r.maxSize,
}, nil
}
if err := fileSystemUsage.Get(dir); err != nil {
return roachpb.StoreCapacity{}, err
}
if fileSystemUsage.Total > math.MaxInt64 {
return roachpb.StoreCapacity{}, fmt.Errorf("unsupported disk size %s, max supported size is %s",
humanize.IBytes(fileSystemUsage.Total), humanizeutil.IBytes(math.MaxInt64))
}
if fileSystemUsage.Avail > math.MaxInt64 {
return roachpb.StoreCapacity{}, fmt.Errorf("unsupported disk size %s, max supported size is %s",
humanize.IBytes(fileSystemUsage.Avail), humanizeutil.IBytes(math.MaxInt64))
}
fsuTotal := int64(fileSystemUsage.Total)
fsuAvail := int64(fileSystemUsage.Avail)
// If no size limitation have been placed on the store size or if the
// limitation is greater than what's available, just return the actual
// totals.
if r.maxSize == 0 || r.maxSize >= fsuTotal || r.dir == "" {
return roachpb.StoreCapacity{
Capacity: fsuTotal,
Available: fsuAvail,
}, nil
}
// Find the total size of all the files in the r.dir and all its
// subdirectories.
var totalUsedBytes int64
if errOuter := filepath.Walk(r.dir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return nil
}
if info.Mode().IsRegular() {
totalUsedBytes += info.Size()
}
return nil
}); errOuter != nil {
return roachpb.StoreCapacity{}, errOuter
}
available := r.maxSize - totalUsedBytes
if available > fsuAvail {
available = fsuAvail
}
if available < 0 {
available = 0
}
return roachpb.StoreCapacity{
Capacity: r.maxSize,
Available: available,
}, nil
}
// Compact forces compaction on the database.
func (r *RocksDB) Compact() error {
return statusToError(C.DBCompact(r.rdb))
}
// Destroy destroys the underlying filesystem data associated with the database.
func (r *RocksDB) Destroy() error {
return statusToError(C.DBDestroy(goToCSlice([]byte(r.dir))))
}
// Flush causes RocksDB to write all in-memory data to disk immediately.
func (r *RocksDB) Flush() error {
return statusToError(C.DBFlush(r.rdb))
}
// NewIterator returns an iterator over this rocksdb engine.
func (r *RocksDB) NewIterator(prefix bool) Iterator {
return newRocksDBIterator(r.rdb, prefix, r)
}
// NewSnapshot creates a snapshot handle from engine and returns a
// read-only rocksDBSnapshot engine.
func (r *RocksDB) NewSnapshot() Reader {
if r.rdb == nil {
panic("RocksDB is not initialized yet")
}
return &rocksDBSnapshot{
parent: r,
handle: C.DBNewSnapshot(r.rdb),
}
}
// NewBatch returns a new batch wrapping this rocksdb engine.
func (r *RocksDB) NewBatch() Batch {
return newRocksDBBatch(r, false /* writeOnly */)
}
// NewWriteOnlyBatch returns a new write-only batch wrapping this rocksdb
// engine.
func (r *RocksDB) NewWriteOnlyBatch() Batch {
return newRocksDBBatch(r, true /* writeOnly */)
}
// GetSSTables retrieves metadata about this engine's live sstables.
func (r *RocksDB) GetSSTables() SSTableInfos {
var n C.int
tables := C.DBGetSSTables(r.rdb, &n)
// We can't index into tables because it is a pointer, not a slice. The
// hackery below treats the pointer as an array and then constructs a slice
// from it.
tablesPtr := uintptr(unsafe.Pointer(tables))
tableSize := unsafe.Sizeof(C.DBSSTable{})
tableVal := func(i int) C.DBSSTable {
return *(*C.DBSSTable)(unsafe.Pointer(tablesPtr + uintptr(i)*tableSize))
}
res := make(SSTableInfos, n)
for i := range res {
r := &res[i]
tv := tableVal(i)
r.Level = int(tv.level)
r.Size = int64(tv.size)
r.Start = cToGoKey(tv.start_key)
r.End = cToGoKey(tv.end_key)
if ptr := tv.start_key.key.data; ptr != nil {
C.free(unsafe.Pointer(ptr))
}
if ptr := tv.end_key.key.data; ptr != nil {
C.free(unsafe.Pointer(ptr))
}
}
C.free(unsafe.Pointer(tables))
sort.Sort(res)
return res
}
// getUserProperties fetches the user properties stored in each sstable's
// metadata.
func (r *RocksDB) getUserProperties() (enginepb.SSTUserPropertiesCollection, error) {
buf := cStringToGoBytes(C.DBGetUserProperties(r.rdb))
var ssts enginepb.SSTUserPropertiesCollection
if err := ssts.Unmarshal(buf); err != nil {
return enginepb.SSTUserPropertiesCollection{}, err
}
if ssts.Error != "" {
return enginepb.SSTUserPropertiesCollection{}, errors.New(ssts.Error)
}
return ssts, nil
}
// GetStats retrieves stats from this engine's RocksDB instance and
// returns it in a new instance of Stats.
func (r *RocksDB) GetStats() (*Stats, error) {
var s C.DBStatsResult
if err := statusToError(C.DBGetStats(r.rdb, &s)); err != nil {
return nil, err
}
return &Stats{
BlockCacheHits: int64(s.block_cache_hits),
BlockCacheMisses: int64(s.block_cache_misses),
BlockCacheUsage: int64(s.block_cache_usage),
BlockCachePinnedUsage: int64(s.block_cache_pinned_usage),
BloomFilterPrefixChecked: int64(s.bloom_filter_prefix_checked),
BloomFilterPrefixUseful: int64(s.bloom_filter_prefix_useful),
MemtableHits: int64(s.memtable_hits),
MemtableMisses: int64(s.memtable_misses),
MemtableTotalSize: int64(s.memtable_total_size),
Flushes: int64(s.flushes),
Compactions: int64(s.compactions),
TableReadersMemEstimate: int64(s.table_readers_mem_estimate),
}, nil
}
type rocksDBSnapshot struct {
parent *RocksDB
handle *C.DBEngine
}
// Close releases the snapshot handle.
func (r *rocksDBSnapshot) Close() {
C.DBClose(r.handle)
r.handle = nil
}
// Closed returns true if the engine is closed.
func (r *rocksDBSnapshot) Closed() bool {
return r.handle == nil
}
// Get returns the value for the given key, nil otherwise using
// the snapshot handle.
func (r *rocksDBSnapshot) Get(key MVCCKey) ([]byte, error) {
return dbGet(r.handle, key)
}
func (r *rocksDBSnapshot) GetProto(
key MVCCKey, msg proto.Message,
) (ok bool, keyBytes, valBytes int64, err error) {
return dbGetProto(r.handle, key, msg)
}
// Iterate iterates over the keys between start inclusive and end
// exclusive, invoking f() on each key/value pair using the snapshot
// handle.
func (r *rocksDBSnapshot) Iterate(start, end MVCCKey, f func(MVCCKeyValue) (bool, error)) error {
return dbIterate(r.handle, r, start, end, f)
}
// NewIterator returns a new instance of an Iterator over the
// engine using the snapshot handle.
func (r *rocksDBSnapshot) NewIterator(prefix bool) Iterator {
return newRocksDBIterator(r.handle, prefix, r)
}
// reusableIterator wraps rocksDBIterator and allows reuse of an iterator
// for the lifetime of a batch.
type reusableIterator struct {
rocksDBIterator
inuse bool
}
func (r *reusableIterator) Close() {
// reusableIterator.Close() leaves the underlying rocksdb iterator open until
// the associated batch is closed.
if !r.inuse {
panic("closing idle iterator")
}
r.inuse = false
}
type distinctBatch struct {
*rocksDBBatch
prefixIter reusableIterator
normalIter reusableIterator
}
func (r *distinctBatch) Close() {
if !r.distinctOpen {
panic("distinct batch not open")
}
r.distinctOpen = false
}
// NewIterator returns an iterator over the batch and underlying engine. Note
// that the returned iterator is cached and re-used for the lifetime of the
// batch. A panic will be thrown if multiple prefix or normal (non-prefix)
// iterators are used simultaneously on the same batch.
func (r *distinctBatch) NewIterator(prefix bool) Iterator {
// Used the cached iterator, creating it on first access.
iter := &r.normalIter
if prefix {
iter = &r.prefixIter
}
if iter.rocksDBIterator.iter == nil {
if r.writeOnly {
iter.rocksDBIterator.init(r.parent.rdb, prefix, r)
} else {
iter.rocksDBIterator.init(r.batch, prefix, r)
}
}
if iter.inuse {
panic("iterator already in use")
}
iter.inuse = true
return iter
}
func (r *distinctBatch) Get(key MVCCKey) ([]byte, error) {
if r.writeOnly {
return dbGet(r.parent.rdb, key)
}
return dbGet(r.batch, key)
}
func (r *distinctBatch) GetProto(
key MVCCKey, msg proto.Message,
) (ok bool, keyBytes, valBytes int64, err error) {
if r.writeOnly {
return dbGetProto(r.parent.rdb, key, msg)
}
return dbGetProto(r.batch, key, msg)
}
func (r *distinctBatch) Iterate(start, end MVCCKey, f func(MVCCKeyValue) (bool, error)) error {
return dbIterate(r.batch, r, start, end, f)
}
func (r *distinctBatch) Put(key MVCCKey, value []byte) error {
r.builder.Put(key, value)
return nil
}
func (r *distinctBatch) Merge(key MVCCKey, value []byte) error {
r.builder.Merge(key, value)
return nil
}
func (r *distinctBatch) Clear(key MVCCKey) error {
r.builder.Clear(key)
return nil
}
func (r *distinctBatch) ClearRange(start, end MVCCKey) error {
if !r.writeOnly {
panic("readable batch")
}
r.flushMutations()
r.flushes++ // make sure that Repr() doesn't take a shortcut
return dbClearRange(r.batch, start, end)
}
func (r *distinctBatch) ClearIterRange(iter Iterator, start, end MVCCKey) error {
r.flushMutations()
r.flushes++ // make sure that Repr() doesn't take a shortcut
return dbClearIterRange(r.batch, iter, start, end)
}
func (r *distinctBatch) close() {
if i := &r.prefixIter.rocksDBIterator; i.iter != nil {
i.destroy()
}
if i := &r.normalIter.rocksDBIterator; i.iter != nil {
i.destroy()
}
}
// rocksDBBatchIterator wraps rocksDBIterator and allows reuse of an iterator
// for the lifetime of a batch.
type rocksDBBatchIterator struct {
iter rocksDBIterator
batch *rocksDBBatch
}
func (r *rocksDBBatchIterator) Close() {
// rocksDBBatchIterator.Close() leaves the underlying rocksdb iterator open
// until the associated batch is closed.
if r.batch == nil {
panic("closing idle iterator")
}
r.batch = nil
}
func (r *rocksDBBatchIterator) Seek(key MVCCKey) {
r.batch.flushMutations()
r.iter.Seek(key)
}
func (r *rocksDBBatchIterator) SeekReverse(key MVCCKey) {
r.batch.flushMutations()
r.iter.SeekReverse(key)
}
func (r *rocksDBBatchIterator) Valid() (bool, error) {
return r.iter.Valid()
}
func (r *rocksDBBatchIterator) Next() {
r.batch.flushMutations()
r.iter.Next()
}
func (r *rocksDBBatchIterator) Prev() {
r.batch.flushMutations()
r.iter.Prev()
}
func (r *rocksDBBatchIterator) NextKey() {
r.batch.flushMutations()
r.iter.NextKey()
}
func (r *rocksDBBatchIterator) PrevKey() {
r.batch.flushMutations()
r.iter.PrevKey()
}
func (r *rocksDBBatchIterator) ComputeStats(
start, end MVCCKey, nowNanos int64,
) (enginepb.MVCCStats, error) {
r.batch.flushMutations()
return r.iter.ComputeStats(start, end, nowNanos)
}
func (r *rocksDBBatchIterator) Key() MVCCKey {
return r.iter.Key()
}
func (r *rocksDBBatchIterator) Value() []byte {
return r.iter.Value()
}
func (r *rocksDBBatchIterator) ValueProto(msg proto.Message) error {
return r.iter.ValueProto(msg)
}
func (r *rocksDBBatchIterator) UnsafeKey() MVCCKey {
return r.iter.UnsafeKey()
}
func (r *rocksDBBatchIterator) UnsafeValue() []byte {
return r.iter.UnsafeValue()
}
func (r *rocksDBBatchIterator) Less(key MVCCKey) bool {
return r.iter.Less(key)
}
func (r *rocksDBBatchIterator) getIter() *C.DBIterator {
return r.iter.iter
}
type rocksDBBatch struct {
parent *RocksDB
batch *C.DBEngine
flushes int
flushedCount int
flushedSize int
prefixIter rocksDBBatchIterator
normalIter rocksDBBatchIterator
builder RocksDBBatchBuilder
distinct distinctBatch
distinctOpen bool
distinctNeedsFlush bool
writeOnly bool
commitErr error
}
func newRocksDBBatch(parent *RocksDB, writeOnly bool) *rocksDBBatch {
r := &rocksDBBatch{
parent: parent,
batch: C.DBNewBatch(parent.rdb, C.bool(writeOnly)),
writeOnly: writeOnly,
}
r.distinct.rocksDBBatch = r
return r
}
func (r *rocksDBBatch) Close() {
r.distinct.close()
if i := &r.prefixIter.iter; i.iter != nil {
i.destroy()
}
if i := &r.normalIter.iter; i.iter != nil {
i.destroy()
}
if r.batch != nil {
C.DBClose(r.batch)
r.batch = nil
}
}
// Closed returns true if the engine is closed.
func (r *rocksDBBatch) Closed() bool {
return r.batch == nil
}
func (r *rocksDBBatch) Put(key MVCCKey, value []byte) error {
if r.distinctOpen {
panic("distinct batch open")