-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
rocksdb.go
2299 lines (2028 loc) · 63.6 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.
package engine
import (
"bytes"
"fmt"
"io/ioutil"
"math"
"os"
"path/filepath"
"runtime"
"runtime/debug"
"sort"
"strings"
"sync"
"time"
"unsafe"
"github.com/dustin/go-humanize"
"github.com/elastic/gosigar"
"github.com/pkg/errors"
"golang.org/x/net/context"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/settings"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/storage/engine/enginepb"
"github.com/cockroachdb/cockroach/pkg/util"
"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/protoutil"
"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/libroach/include
// #cgo LDFLAGS: -lroach
// #cgo LDFLAGS: -lprotobuf
// #cgo LDFLAGS: -lrocksdb
// #cgo LDFLAGS: -lsnappy
// #cgo linux LDFLAGS: -lrt -lpthread
// #cgo windows LDFLAGS: -lrpcrt4
//
// #include <stdlib.h>
// #include <libroach.h>
import "C"
var minWALSyncInterval = settings.RegisterDurationSetting(
"rocksdb.min_wal_sync_interval",
"minimum duration between syncs of the RocksDB WAL",
0*time.Millisecond,
)
//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 configures the size of a black. When reading a key-value
// pair from a table file, RocksDB loads an entire block into memory. The
// RocksDB default is 4KB. This sets it to 32KB.
defaultBlockSize = 32 << 10
// RecommendedMaxOpenFiles is the recommended value for RocksDB's
// max_open_files option.
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
)
// 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 worst case 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
}
// SSTableInfosByLevel maintains slices of SSTableInfo objects, one
// per level, sorted first by level and second by start key. This is
// different from the default sort order, which is by level, then
// size, then start key..
type SSTableInfosByLevel struct {
// Each level is a slice of SSTableInfos
levels [][]SSTableInfo
}
// NewSSTableInfosByLevel returns a new SSTableInfosByLevel object
// based on the supplied SSTableInfos slice.
func NewSSTableInfosByLevel(s SSTableInfos) SSTableInfosByLevel {
var result SSTableInfosByLevel
for _, t := range s {
for i := len(result.levels); i <= t.Level; i++ {
result.levels = append(result.levels, []SSTableInfo{})
}
result.levels[t.Level] = append(result.levels[t.Level], t)
}
// Sort each level by start key.
for _, l := range result.levels {
sort.Slice(l, func(i, j int) bool { return l[i].Start.Less(l[j].Start) })
}
return result
}
// MaxLevel returns the maximum level for which there are SSTables.
func (s *SSTableInfosByLevel) MaxLevel() int {
return len(s.levels) - 1
}
// MaxLevelSpanOverlapsContiguousSSTables returns the maximum level at
// which the specified key span overlaps either none, one, or at most
// two contiguous SSTables. Level 0 is returned if no level qualifies.
func (s *SSTableInfosByLevel) MaxLevelSpanOverlapsContiguousSSTables(span roachpb.Span) int {
overlapsMoreThanTwo := func(tables []SSTableInfo) bool {
// Search to find the first sstable which might overlap the span.
i := sort.Search(len(tables), func(i int) bool { return span.Key.Compare(tables[i].End.Key) < 0 })
// If no SSTable is overlapped, return false.
if i == -1 || i == len(tables) || span.EndKey.Compare(tables[i].Start.Key) < 0 {
return false
}
// Return true if the span is not subsumed by the combination of
// this sstable and the next.
return i < len(tables)-1 && span.EndKey.Compare(tables[i+1].End.Key) > 0
}
for i := len(s.levels) - 1; i > 0; i-- {
if !overlapsMoreThanTwo(s.levels[i]) {
return i
}
}
return 0
}
// 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)
}
}
// RocksDBConfig holds all configuration parameters and knobs used in setting
// up a new RocksDB instance.
type RocksDBConfig struct {
Attrs roachpb.Attributes
// Dir is the data directory for this store.
Dir string
// If true, creating the instance fails if the target directory does not hold
// an initialized RocksDB instance.
//
// Makes no sense for in-memory instances.
MustExist bool
// MaxSizeBytes is used for calculating free space and making rebalancing
// decisions. Zero indicates that there is no maximum size.
MaxSizeBytes int64
// MaxOpenFiles controls the maximum number of file descriptors RocksDB
// creates. If MaxOpenFiles is zero, this is set to DefaultMaxOpenFiles.
MaxOpenFiles uint64
// WarnLargeBatchThreshold controls if a log message is printed when a
// WriteBatch takes longer than WarnLargeBatchThreshold. If it is set to
// zero, no log messages are ever printed.
WarnLargeBatchThreshold time.Duration
// Settings instance for cluster-wide knobs.
Settings *cluster.Settings
// UseSwitchingEnv is true if the switching env is needed (eg: encryption-at-rest).
// This may force the store version to versionSwitchingEnv if currently lower.
UseSwitchingEnv bool
// ExtraOptions is a serialized protobuf set by Go CCL code and passed through
// to C CCL code.
ExtraOptions []byte
}
// RocksDB is a wrapper around a RocksDB database instance.
type RocksDB struct {
cfg RocksDBConfig
rdb *C.DBEngine
cache RocksDBCache // Shared cache.
// auxDir is used for storing auxiliary files. Ideally it is a subdirectory of Dir.
auxDir string
commit struct {
syncutil.Mutex
cond sync.Cond
committing bool
pending []*rocksDBBatch
}
syncer struct {
syncutil.Mutex
cond sync.Cond
closed 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(cfg RocksDBConfig, cache RocksDBCache) (*RocksDB, error) {
if cfg.Dir == "" {
return nil, errors.New("dir must be non-empty")
}
r := &RocksDB{
cfg: cfg,
cache: cache.ref(),
}
if err := r.setAuxiliaryDir(filepath.Join(cfg.Dir, "auxiliary")); err != nil {
return nil, err
}
if err := r.open(); err != nil {
return nil, err
}
return r, nil
}
func newMemRocksDB(
attrs roachpb.Attributes, cache RocksDBCache, MaxSizeBytes int64,
) (*RocksDB, error) {
r := &RocksDB{
cfg: RocksDBConfig{
Attrs: attrs,
MaxSizeBytes: MaxSizeBytes,
},
// dir: empty dir == "mem" RocksDB instance.
cache: cache.ref(),
}
auxDir, err := ioutil.TempDir(os.TempDir(), "cockroach-auxiliary")
if err != nil {
return nil, err
}
if err := r.setAuxiliaryDir(auxDir); err != nil {
return nil, err
}
if err := r.open(); err != nil {
return nil, err
}
return r, nil
}
// String formatter.
func (r *RocksDB) String() string {
dir := r.cfg.Dir
if r.cfg.Dir == "" {
dir = "<in-mem>"
}
attrs := r.Attrs().String()
if attrs == "" {
attrs = "<no-attributes>"
}
return fmt.Sprintf("%s=%s", attrs, dir)
}
func (r *RocksDB) open() error {
var existingVersion, newVersion storageVersion
if len(r.cfg.Dir) != 0 {
log.Infof(context.TODO(), "opening rocksdb instance at %q", r.cfg.Dir)
// Check the version number.
var err error
if existingVersion, err = getVersion(r.cfg.Dir); err != nil {
return err
}
if existingVersion < versionMinimum || existingVersion > 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, existingVersion, versionMinimum)
}
newVersion = existingVersion
if newVersion == versionNoFile {
// We currently set the default store version one before the switching env
// to allow downgrades to older binaries as long as encryption is not in use.
// TODO(mberhault): once enough releases supporting versionSwitchingEnv have passed, we can upgrade
// to it without worry.
newVersion = versionBeta20160331
}
// Using the switching environment forces the latest version. We can't downgrade!
if r.cfg.UseSwitchingEnv {
newVersion = versionCurrent
}
} else {
if log.V(2) {
log.Infof(context.TODO(), "opening in memory rocksdb instance")
}
// In memory dbs are always current.
existingVersion = versionCurrent
}
blockSize := envutil.EnvOrDefaultBytes("COCKROACH_ROCKSDB_BLOCK_SIZE", defaultBlockSize)
walTTL := envutil.EnvOrDefaultDuration("COCKROACH_ROCKSDB_WAL_TTL", 0).Seconds()
maxOpenFiles := uint64(RecommendedMaxOpenFiles)
if r.cfg.MaxOpenFiles != 0 {
maxOpenFiles = r.cfg.MaxOpenFiles
}
status := C.DBOpen(&r.rdb, goToCSlice([]byte(r.cfg.Dir)),
C.DBOptions{
cache: r.cache.cache,
block_size: C.uint64_t(blockSize),
wal_ttl_seconds: C.uint64_t(walTTL),
logging_enabled: C.bool(log.V(3)),
num_cpu: C.int(runtime.NumCPU()),
max_open_files: C.int(maxOpenFiles),
use_switching_env: C.bool(newVersion == versionCurrent),
must_exist: C.bool(r.cfg.MustExist),
extra_options: goToCSlice(r.cfg.ExtraOptions),
})
if err := statusToError(status); err != nil {
return errors.Wrap(err, "could not open rocksdb instance")
}
// Update or add the version file if needed and if on-disk.
if len(r.cfg.Dir) != 0 && existingVersion < newVersion {
if err := writeVersionFile(r.cfg.Dir, newVersion); err != nil {
return err
}
}
r.commit.cond.L = &r.commit.Mutex
r.syncer.cond.L = &r.syncer.Mutex
// NB: The sync goroutine acts as a check that the RocksDB instance was
// properly closed as the goroutine will leak otherwise.
go r.syncLoop()
return nil
}
func (r *RocksDB) syncLoop() {
s := &r.syncer
s.Lock()
defer s.Unlock()
var lastSync time.Time
for {
for len(s.pending) == 0 && !s.closed {
s.cond.Wait()
}
if s.closed {
return
}
var min time.Duration
if r.cfg.Settings != nil {
min = minWALSyncInterval.Get(&r.cfg.Settings.SV)
}
if delta := timeutil.Since(lastSync); delta < min {
s.Unlock()
time.Sleep(min - delta)
s.Lock()
}
pending := s.pending
s.pending = nil
s.Unlock()
var err error
if r.cfg.Dir != "" {
err = statusToError(C.DBSyncWAL(r.rdb))
lastSync = timeutil.Now()
}
for _, b := range pending {
b.commitErr = err
b.commitWG.Done()
}
s.Lock()
}
}
// 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.cfg.Dir) == 0 {
if log.V(1) {
log.Infof(context.TODO(), "closing in-memory rocksdb instance")
}
// Remove the temporary directory when the engine is in-memory.
if err := os.RemoveAll(r.auxDir); err != nil {
log.Warning(context.TODO(), err)
}
} else {
log.Infof(context.TODO(), "closing rocksdb instance at %q", r.cfg.Dir)
}
if r.rdb != nil {
C.DBClose(r.rdb)
r.rdb = nil
}
r.cache.Release()
r.syncer.Lock()
r.syncer.closed = true
r.syncer.cond.Signal()
r.syncer.Unlock()
}
// 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.cfg.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 protoutil.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.cfg.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.cfg.MaxSizeBytes,
Available: r.cfg.MaxSizeBytes,
}, 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)
// Find the total size of all the files in the r.dir and all its
// subdirectories.
var totalUsedBytes int64
if errOuter := filepath.Walk(r.cfg.Dir, func(path string, info os.FileInfo, err error) error {
if err != nil {
// This can happen if rocksdb removes files out from under us - just keep
// going to get the best estimate we can.
if os.IsNotExist(err) {
return nil
}
// Special-case: if the store-dir is configured using the root of some fs,
// e.g. "/mnt/db", we might have special fs-created files like lost+found
// that we can't read, so just ignore them rather than crashing.
if os.IsPermission(err) && filepath.Base(path) == "lost+found" {
return nil
}
return err
}
if info.Mode().IsRegular() {
totalUsedBytes += info.Size()
}
return nil
}); errOuter != nil {
return roachpb.StoreCapacity{}, errOuter
}
// 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.cfg.MaxSizeBytes == 0 || r.cfg.MaxSizeBytes >= fsuTotal || r.cfg.Dir == "" {
return roachpb.StoreCapacity{
Capacity: fsuTotal,
Available: fsuAvail,
Used: totalUsedBytes,
}, nil
}
available := r.cfg.MaxSizeBytes - totalUsedBytes
if available > fsuAvail {
available = fsuAvail
}
if available < 0 {
available = 0
}
return roachpb.StoreCapacity{
Capacity: r.cfg.MaxSizeBytes,
Available: available,
Used: totalUsedBytes,
}, nil
}
// Compact forces compaction over the entire database.
func (r *RocksDB) Compact() error {
return statusToError(C.DBCompact(r.rdb))
}
// CompactRange forces compaction over a specified range of keys in the database.
func (r *RocksDB) CompactRange(start, end MVCCKey) error {
return statusToError(C.DBCompactRange(r.rdb, goToCKey(start), goToCKey(end)))
}
// ApproximateDiskBytes returns the approximate on-disk size of the specified key range.
func (r *RocksDB) ApproximateDiskBytes(from, to roachpb.Key) (uint64, error) {
start := MVCCKey{Key: from}
end := MVCCKey{Key: to}
var result C.uint64_t
err := statusToError(C.DBApproximateDiskBytes(r.rdb, goToCKey(start), goToCKey(end), &result))
return uint64(result), err
}
// Destroy destroys the underlying filesystem data associated with the database.
func (r *RocksDB) Destroy() error {
return statusToError(C.DBDestroy(goToCSlice([]byte(r.cfg.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)
}
// NewTimeBoundIterator is like NewIterator, but returns a time-bound iterator.
func (r *RocksDB) NewTimeBoundIterator(start, end hlc.Timestamp) Iterator {
it := &rocksDBIterator{}
it.initTimeBound(r.rdb, start, end, r)
return it
}
// 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),
}
}
// NewReadOnly returns a new ReadWriter wrapping this rocksdb engine.
func (r *RocksDB) NewReadOnly() ReadWriter {
return &rocksDBReadOnly{
parent: r,
isClosed: false,
}
}
type rocksDBReadOnly struct {
parent *RocksDB
prefixIter reusableIterator
normalIter reusableIterator
isClosed bool
}
func (r *rocksDBReadOnly) Close() {
if r.isClosed {
panic("closing an already-closed rocksDBReadOnly")
}
r.isClosed = true
if i := &r.prefixIter.rocksDBIterator; i.iter != nil {
i.destroy()
}
if i := &r.normalIter.rocksDBIterator; i.iter != nil {
i.destroy()
}
}
// Read-only batches are not committed
func (r *rocksDBReadOnly) Closed() bool {
return r.isClosed
}
func (r *rocksDBReadOnly) Get(key MVCCKey) ([]byte, error) {
if r.isClosed {
panic("using a closed rocksDBReadOnly")
}
return dbGet(r.parent.rdb, key)
}
func (r *rocksDBReadOnly) GetProto(
key MVCCKey, msg protoutil.Message,
) (ok bool, keyBytes, valBytes int64, err error) {
if r.isClosed {
panic("using a closed rocksDBReadOnly")
}
return dbGetProto(r.parent.rdb, key, msg)
}
func (r *rocksDBReadOnly) Iterate(start, end MVCCKey, f func(MVCCKeyValue) (bool, error)) error {
if r.isClosed {
panic("using a closed rocksDBReadOnly")
}
return dbIterate(r.parent.rdb, r, start, end, f)
}
// NewIterator returns an iterator over the underlying engine. Note
// that the returned iterator is cached and re-used for the lifetime of the
// rocksDBReadOnly. A panic will be thrown if multiple prefix or normal (non-prefix)
// iterators are used simultaneously on the same rocksDBReadOnly.
func (r *rocksDBReadOnly) NewIterator(prefix bool) Iterator {
if r.isClosed {
panic("using a closed rocksDBReadOnly")
}
iter := &r.normalIter
if prefix {
iter = &r.prefixIter
}
if iter.rocksDBIterator.iter == nil {
iter.rocksDBIterator.init(r.parent.rdb, prefix, r)
}
if iter.inuse {
panic("iterator already in use")
}
iter.inuse = true
return iter
}
func (r *rocksDBReadOnly) NewTimeBoundIterator(start, end hlc.Timestamp) Iterator {
if r.isClosed {
panic("using a closed rocksDBReadOnly")
}
it := &rocksDBIterator{}
it.initTimeBound(r.parent.rdb, start, end, r)
return it
}
// Writer methods are not implemented for rocksDBReadOnly. Ideally, the code could be refactored so that
// a Reader could be supplied to evaluateBatch
// Writer is the write interface to an engine's data.
func (r *rocksDBReadOnly) ApplyBatchRepr(repr []byte, sync bool) error {
panic("not implemented")
}
func (r *rocksDBReadOnly) Clear(key MVCCKey) error {
panic("not implemented")
}
func (r *rocksDBReadOnly) ClearRange(start, end MVCCKey) error {
panic("not implemented")
}
func (r *rocksDBReadOnly) ClearIterRange(iter Iterator, start, end MVCCKey) error {
panic("not implemented")
}
func (r *rocksDBReadOnly) Merge(key MVCCKey, value []byte) error {
panic("not implemented")
}
func (r *rocksDBReadOnly) Put(key MVCCKey, value []byte) error {
panic("not implemented")
}
// 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 := protoutil.Unmarshal(buf, &ssts); err != nil {
return enginepb.SSTUserPropertiesCollection{}, err
}
if ssts.Error != "" {
return enginepb.SSTUserPropertiesCollection{}, errors.New(ssts.Error)
}
return ssts, nil