-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
pebble.go
1958 lines (1742 loc) · 59.1 KB
/
pebble.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 2019 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package storage
import (
"bytes"
"context"
"fmt"
"io"
"io/ioutil"
"math"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/cli/exit"
"github.com/cockroachdb/cockroach/pkg/clusterversion"
"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/enginepb"
"github.com/cockroachdb/cockroach/pkg/storage/fs"
"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/uuid"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/errors/oserror"
"github.com/cockroachdb/logtags"
"github.com/cockroachdb/pebble"
"github.com/cockroachdb/pebble/bloom"
"github.com/cockroachdb/pebble/vfs"
"github.com/cockroachdb/redact"
"github.com/dustin/go-humanize"
)
const maxSyncDurationFatalOnExceededDefault = true
// Default for MaxSyncDuration below.
var maxSyncDurationDefault = envutil.EnvOrDefaultDuration("COCKROACH_ENGINE_MAX_SYNC_DURATION_DEFAULT", 60*time.Second)
// MaxSyncDuration is the threshold above which an observed engine sync duration
// triggers either a warning or a fatal error.
var MaxSyncDuration = settings.RegisterDurationSetting(
"storage.max_sync_duration",
"maximum duration for disk operations; any operations that take longer"+
" than this setting trigger a warning log entry or process crash",
maxSyncDurationDefault,
)
// MaxSyncDurationFatalOnExceeded governs whether disk stalls longer than
// MaxSyncDuration fatal the Cockroach process. Defaults to true.
var MaxSyncDurationFatalOnExceeded = settings.RegisterBoolSetting(
"storage.max_sync_duration.fatal.enabled",
"if true, fatal the process when a disk operation exceeds storage.max_sync_duration",
maxSyncDurationFatalOnExceededDefault,
)
// EngineKeyCompare compares cockroach keys, including the version (which
// could be MVCC timestamps).
func EngineKeyCompare(a, b []byte) int {
// NB: For performance, this routine manually splits the key into the
// user-key and version components rather than using DecodeEngineKey. In
// most situations, use DecodeEngineKey or GetKeyPartFromEngineKey or
// SplitMVCCKey instead of doing this.
aEnd := len(a) - 1
bEnd := len(b) - 1
if aEnd < 0 || bEnd < 0 {
// This should never happen unless there is some sort of corruption of
// the keys.
return bytes.Compare(a, b)
}
// Compute the index of the separator between the key and the version.
aSep := aEnd - int(a[aEnd])
bSep := bEnd - int(b[bEnd])
if aSep < 0 || bSep < 0 {
// This should never happen unless there is some sort of corruption of
// the keys.
return bytes.Compare(a, b)
}
// Compare the "user key" part of the key.
if c := bytes.Compare(a[:aSep], b[:bSep]); c != 0 {
return c
}
// Compare the version part of the key. Note that when the version is a
// timestamp, the timestamp encoding causes byte comparison to be equivalent
// to timestamp comparison.
aTS := a[aSep:aEnd]
bTS := b[bSep:bEnd]
if len(aTS) == 0 {
if len(bTS) == 0 {
return 0
}
return -1
} else if len(bTS) == 0 {
return 1
}
return bytes.Compare(bTS, aTS)
}
// EngineComparer is a pebble.Comparer object that implements MVCC-specific
// comparator settings for use with Pebble.
var EngineComparer = &pebble.Comparer{
Compare: EngineKeyCompare,
AbbreviatedKey: func(k []byte) uint64 {
key, ok := GetKeyPartFromEngineKey(k)
if !ok {
return 0
}
return pebble.DefaultComparer.AbbreviatedKey(key)
},
FormatKey: func(k []byte) fmt.Formatter {
decoded, ok := DecodeEngineKey(k)
if !ok {
return mvccKeyFormatter{err: errors.Errorf("invalid encoded engine key: %x", k)}
}
if decoded.IsMVCCKey() {
mvccKey, err := decoded.ToMVCCKey()
if err != nil {
return mvccKeyFormatter{err: err}
}
return mvccKeyFormatter{key: mvccKey}
}
return EngineKeyFormatter{key: decoded}
},
Separator: func(dst, a, b []byte) []byte {
aKey, ok := GetKeyPartFromEngineKey(a)
if !ok {
return append(dst, a...)
}
bKey, ok := GetKeyPartFromEngineKey(b)
if !ok {
return append(dst, a...)
}
// If the keys are the same just return a.
if bytes.Equal(aKey, bKey) {
return append(dst, a...)
}
n := len(dst)
// Engine key comparison uses bytes.Compare on the roachpb.Key, which is the same semantics as
// pebble.DefaultComparer, so reuse the latter's Separator implementation.
dst = pebble.DefaultComparer.Separator(dst, aKey, bKey)
// Did it pick a separator different than aKey -- if it did not we can't do better than a.
buf := dst[n:]
if bytes.Equal(aKey, buf) {
return append(dst[:n], a...)
}
// The separator is > aKey, so we only need to add the sentinel.
return append(dst, 0)
},
Successor: func(dst, a []byte) []byte {
aKey, ok := GetKeyPartFromEngineKey(a)
if !ok {
return append(dst, a...)
}
n := len(dst)
// Engine key comparison uses bytes.Compare on the roachpb.Key, which is the same semantics as
// pebble.DefaultComparer, so reuse the latter's Successor implementation.
dst = pebble.DefaultComparer.Successor(dst, aKey)
// Did it pick a successor different than aKey -- if it did not we can't do better than a.
buf := dst[n:]
if bytes.Equal(aKey, buf) {
return append(dst[:n], a...)
}
// The successor is > aKey, so we only need to add the sentinel.
return append(dst, 0)
},
Split: func(k []byte) int {
key, ok := GetKeyPartFromEngineKey(k)
if !ok {
return len(k)
}
// Pebble requires that keys generated via a split be comparable with
// normal encoded engine keys. Encoded engine keys have a suffix
// indicating the number of bytes of version data. Engine keys without a
// version have a suffix of 0. We're careful in EncodeKey to make sure
// that the user-key always has a trailing 0. If there is no version this
// falls out naturally. If there is a version we prepend a 0 to the
// encoded version data.
return len(key) + 1
},
Name: "cockroach_comparator",
}
// MVCCMerger is a pebble.Merger object that implements the merge operator used
// by Cockroach.
var MVCCMerger = &pebble.Merger{
Name: "cockroach_merge_operator",
Merge: func(_, value []byte) (pebble.ValueMerger, error) {
res := &MVCCValueMerger{}
err := res.MergeNewer(value)
if err != nil {
return nil, err
}
return res, nil
},
}
// pebbleTimeBoundPropCollector implements a property collector for MVCC
// Timestamps. Its behavior matches TimeBoundTblPropCollector in
// table_props.cc.
//
// The handling of timestamps in intents is mildly complicated. Consider:
//
// a@<meta> -> <MVCCMetadata: Timestamp=t2>
// a@t2 -> <value>
// a@t1 -> <value>
//
// The metadata record (a.k.a. the intent) for a key always sorts first. The
// timestamp field always points to the next record. In this case, the meta
// record contains t2 and the next record is t2. Because of this duplication of
// the timestamp both in the intent and in the timestamped record that
// immediately follows it, we only need to unmarshal the MVCCMetadata if it is
// the last key in the sstable.
type pebbleTimeBoundPropCollector struct {
min, max []byte
lastValue []byte
}
func (t *pebbleTimeBoundPropCollector) Add(key pebble.InternalKey, value []byte) error {
engineKey, ok := DecodeEngineKey(key.UserKey)
if !ok {
return errors.Errorf("failed to split engine key")
}
if engineKey.IsMVCCKey() && len(engineKey.Version) > 0 {
t.lastValue = t.lastValue[:0]
t.updateBounds(engineKey.Version)
} else {
t.lastValue = append(t.lastValue[:0], value...)
}
return nil
}
func (t *pebbleTimeBoundPropCollector) Finish(userProps map[string]string) error {
if len(t.lastValue) > 0 {
// The last record in the sstable was an intent. Unmarshal the metadata and
// update the bounds with the timestamp it contains.
meta := &enginepb.MVCCMetadata{}
if err := protoutil.Unmarshal(t.lastValue, meta); err != nil {
// We're unable to parse the MVCCMetadata. Fail open by not setting the
// min/max timestamp properties. This mimics the behavior of
// TimeBoundTblPropCollector.
// TODO(petermattis): Return the error here and in C++, see #43422.
return nil //nolint:returnerrcheck
}
if meta.Txn != nil {
ts := encodeTimestamp(meta.Timestamp.ToTimestamp())
t.updateBounds(ts)
}
}
userProps["crdb.ts.min"] = string(t.min)
userProps["crdb.ts.max"] = string(t.max)
return nil
}
func (t *pebbleTimeBoundPropCollector) updateBounds(ts []byte) {
if len(t.min) == 0 || bytes.Compare(ts, t.min) < 0 {
t.min = append(t.min[:0], ts...)
}
if len(t.max) == 0 || bytes.Compare(ts, t.max) > 0 {
t.max = append(t.max[:0], ts...)
}
}
func (t *pebbleTimeBoundPropCollector) Name() string {
// This constant needs to match the one used by the RocksDB version of this
// table property collector. DO NOT CHANGE.
return "TimeBoundTblPropCollectorFactory"
}
// pebbleDeleteRangeCollector is the equivalent table collector as the RocksDB
// DeleteRangeTblPropCollector. Pebble does not require it because Pebble will
// prioritize its own compactions of range tombstones.
type pebbleDeleteRangeCollector struct{}
func (pebbleDeleteRangeCollector) Add(_ pebble.InternalKey, _ []byte) error {
return nil
}
func (pebbleDeleteRangeCollector) Finish(_ map[string]string) error {
return nil
}
func (pebbleDeleteRangeCollector) Name() string {
// This constant needs to match the one used by the RocksDB version of this
// table property collector. DO NOT CHANGE.
return "DeleteRangeTblPropCollectorFactory"
}
// PebbleTablePropertyCollectors is the list of Pebble TablePropertyCollectors.
var PebbleTablePropertyCollectors = []func() pebble.TablePropertyCollector{
func() pebble.TablePropertyCollector { return &pebbleTimeBoundPropCollector{} },
func() pebble.TablePropertyCollector { return &pebbleDeleteRangeCollector{} },
}
// DefaultPebbleOptions returns the default pebble options.
func DefaultPebbleOptions() *pebble.Options {
// In RocksDB, the concurrency setting corresponds to both flushes and
// compactions. In Pebble, there is always a slot for a flush, and
// compactions are counted separately.
maxConcurrentCompactions := rocksdbConcurrency - 1
if maxConcurrentCompactions < 1 {
maxConcurrentCompactions = 1
}
opts := &pebble.Options{
Comparer: EngineComparer,
L0CompactionThreshold: 2,
L0StopWritesThreshold: 1000,
LBaseMaxBytes: 64 << 20, // 64 MB
Levels: make([]pebble.LevelOptions, 7),
MaxConcurrentCompactions: maxConcurrentCompactions,
MemTableSize: 64 << 20, // 64 MB
MemTableStopWritesThreshold: 4,
Merger: MVCCMerger,
TablePropertyCollectors: PebbleTablePropertyCollectors,
}
// Automatically flush 10s after the first range tombstone is added to a
// memtable. This ensures that we can reclaim space even when there's no
// activity on the database generating flushes.
opts.Experimental.DeleteRangeFlushDelay = 10 * time.Second
// Enable deletion pacing. This helps prevent disk slowness events on some
// SSDs, that kick off an expensive GC if a lot of files are deleted at
// once.
opts.Experimental.MinDeletionRate = 128 << 20 // 128 MB
// Disable read sampling and by extension read-triggered compactions. Read-
// triggered compactions are known to cause excessively high write
// amplification on some read heavy workloads. See:
// https://github.com/cockroachdb/pebble/issues/1143
//
// TODO(bilal): Remove this line when the above issue is addressed.
opts.Experimental.ReadSamplingMultiplier = -1
for i := 0; i < len(opts.Levels); i++ {
l := &opts.Levels[i]
l.BlockSize = 32 << 10 // 32 KB
l.IndexBlockSize = 256 << 10 // 256 KB
l.FilterPolicy = bloom.FilterPolicy(10)
l.FilterType = pebble.TableFilter
if i > 0 {
l.TargetFileSize = opts.Levels[i-1].TargetFileSize * 2
}
l.EnsureDefaults()
}
// Do not create bloom filters for the last level (i.e. the largest level
// which contains data in the LSM store). This configuration reduces the size
// of the bloom filters by 10x. This is significant given that bloom filters
// require 1.25 bytes (10 bits) per key which can translate into gigabytes of
// memory given typical key and value sizes. The downside is that bloom
// filters will only be usable on the higher levels, but that seems
// acceptable. We typically see read amplification of 5-6x on clusters
// (i.e. there are 5-6 levels of sstables) which means we'll achieve 80-90%
// of the benefit of having bloom filters on every level for only 10% of the
// memory cost.
opts.Levels[6].FilterPolicy = nil
// Set disk health check interval to min(5s, maxSyncDurationDefault). This
// is mostly to ease testing; the default of 5s is too infrequent to test
// conveniently. See the disk-stalled roachtest for an example of how this
// is used.
diskHealthCheckInterval := 5 * time.Second
if diskHealthCheckInterval.Seconds() > maxSyncDurationDefault.Seconds() {
diskHealthCheckInterval = maxSyncDurationDefault
}
// If we encounter ENOSPC, exit with an informative exit code.
opts.FS = vfs.OnDiskFull(opts.FS, func() {
exit.WithCode(exit.DiskFull())
})
// Instantiate a file system with disk health checking enabled. This FS wraps
// vfs.Default, and can be wrapped for encryption-at-rest.
opts.FS = vfs.WithDiskHealthChecks(vfs.Default, diskHealthCheckInterval,
func(name string, duration time.Duration) {
opts.EventListener.DiskSlow(pebble.DiskSlowInfo{
Path: name,
Duration: duration,
})
})
return opts
}
type pebbleLogger struct {
ctx context.Context
depth int
}
func (l pebbleLogger) Infof(format string, args ...interface{}) {
log.Storage.InfofDepth(l.ctx, l.depth, format, args...)
}
func (l pebbleLogger) Fatalf(format string, args ...interface{}) {
log.Storage.FatalfDepth(l.ctx, l.depth, format, args...)
}
// PebbleConfig holds all configuration parameters and knobs used in setting up
// a new Pebble instance.
type PebbleConfig struct {
// StorageConfig contains storage configs for all storage engines.
// A non-nil cluster.Settings must be provided in the StorageConfig for a
// Pebble instance that will be used to write intents.
base.StorageConfig
// Pebble specific options.
Opts *pebble.Options
}
// EncryptionStatsHandler provides encryption related stats.
type EncryptionStatsHandler interface {
// Returns a serialized enginepbccl.EncryptionStatus.
GetEncryptionStatus() ([]byte, error)
// Returns a serialized enginepbccl.DataKeysRegistry, scrubbed of key contents.
GetDataKeysRegistry() ([]byte, error)
// Returns the ID of the active data key, or "plain" if none.
GetActiveDataKeyID() (string, error)
// Returns the enum value of the encryption type.
GetActiveStoreKeyType() int32
// Returns the KeyID embedded in the serialized EncryptionSettings.
GetKeyIDFromSettings(settings []byte) (string, error)
}
// Pebble is a wrapper around a Pebble database instance.
type Pebble struct {
db *pebble.DB
closed bool
path string
auxDir string
ballastPath string
ballastSize int64
maxSize int64
attrs roachpb.Attributes
// settings must be non-nil if this Pebble instance will be used to write
// intents.
settings *cluster.Settings
statsHandler EncryptionStatsHandler
fileRegistry *PebbleFileRegistry
eventListener *pebble.EventListener
// Stats updated by pebble.EventListener invocations, and returned in
// GetStats. Updated and retrieved atomically.
diskSlowCount, diskStallCount uint64
// Relevant options copied over from pebble.Options.
fs vfs.FS
logger pebble.Logger
wrappedIntentWriter intentDemuxWriter
storeIDPebbleLog *base.StoreIDContainer
}
var _ Engine = &Pebble{}
// NewEncryptedEnvFunc creates an encrypted environment and returns the vfs.FS to use for reading
// and writing data. This should be initialized by calling engineccl.Init() before calling
// NewPebble(). The optionBytes is a binary serialized baseccl.EncryptionOptions, so that non-CCL
// code does not depend on CCL code.
var NewEncryptedEnvFunc func(fs vfs.FS, fr *PebbleFileRegistry, dbDir string, readOnly bool, optionBytes []byte) (vfs.FS, EncryptionStatsHandler, error)
// StoreIDSetter is used to set the store id in the log.
type StoreIDSetter interface {
// SetStoreID can be used to atomically set the store
// id as a tag in the pebble logs. Once set, the store id will be visible
// in pebble logs in cockroach.
SetStoreID(ctx context.Context, storeID int32)
}
// SetStoreID adds the store id to pebble logs.
func (p *Pebble) SetStoreID(ctx context.Context, storeID int32) {
if p == nil {
return
}
if p.storeIDPebbleLog == nil {
return
}
p.storeIDPebbleLog.Set(ctx, storeID)
}
// ResolveEncryptedEnvOptions fills in cfg.Opts.FS with an encrypted vfs if this
// store has encryption-at-rest enabled. Also returns the associated file
// registry and EncryptionStatsHandler.
func ResolveEncryptedEnvOptions(
cfg *PebbleConfig,
) (*PebbleFileRegistry, EncryptionStatsHandler, error) {
fileRegistry := &PebbleFileRegistry{FS: cfg.Opts.FS, DBDir: cfg.Dir, ReadOnly: cfg.Opts.ReadOnly}
if cfg.UseFileRegistry {
if err := fileRegistry.Load(); err != nil {
return nil, nil, err
}
} else {
if err := fileRegistry.checkNoRegistryFile(); err != nil {
return nil, nil, fmt.Errorf("encryption was used on this store before, but no encryption flags " +
"specified. You need a CCL build and must fully specify the --enterprise-encryption flag")
}
fileRegistry = nil
}
var statsHandler EncryptionStatsHandler
if cfg.IsEncrypted() {
// Encryption is enabled.
if !cfg.UseFileRegistry {
return nil, nil, fmt.Errorf("file registry is needed to support encryption")
}
if NewEncryptedEnvFunc == nil {
return nil, nil, fmt.Errorf("encryption is enabled but no function to create the encrypted env")
}
var err error
cfg.Opts.FS, statsHandler, err =
NewEncryptedEnvFunc(cfg.Opts.FS, fileRegistry, cfg.Dir, cfg.Opts.ReadOnly, cfg.EncryptionOptions)
if err != nil {
return nil, nil, err
}
}
return fileRegistry, statsHandler, nil
}
// NewPebble creates a new Pebble instance, at the specified path.
func NewPebble(ctx context.Context, cfg PebbleConfig) (*Pebble, error) {
// pebble.Open also calls EnsureDefaults, but only after doing a clone. Call
// EnsureDefaults beforehand so we have a matching cfg here for when we save
// cfg.FS and cfg.ReadOnly later on.
if cfg.Opts == nil {
cfg.Opts = DefaultPebbleOptions()
}
cfg.Opts.EnsureDefaults()
cfg.Opts.ErrorIfNotExists = cfg.MustExist
if settings := cfg.Settings; settings != nil {
cfg.Opts.WALMinSyncInterval = func() time.Duration {
return minWALSyncInterval.Get(&settings.SV)
}
}
auxDir := cfg.Opts.FS.PathJoin(cfg.Dir, base.AuxiliaryDir)
if err := cfg.Opts.FS.MkdirAll(auxDir, 0755); err != nil {
return nil, err
}
ballastPath := base.EmergencyBallastFile(cfg.Opts.FS.PathJoin, cfg.Dir)
fileRegistry, statsHandler, err := ResolveEncryptedEnvOptions(&cfg)
if err != nil {
return nil, err
}
// The context dance here is done so that we have a clean context without
// timeouts that has a copy of the log tags.
logCtx := logtags.WithTags(context.Background(), logtags.FromContext(ctx))
logCtx = logtags.AddTag(logCtx, "pebble", nil)
// The store id, could not necessarily be determined when this function
// is called. Therefore, we use a container for the store id.
storeIDContainer := &base.StoreIDContainer{}
logCtx = logtags.AddTag(logCtx, "s", storeIDContainer)
cfg.Opts.Logger = pebbleLogger{
ctx: logCtx,
depth: 1,
}
cfg.Opts.EventListener = pebble.MakeLoggingEventListener(pebbleLogger{
ctx: logCtx,
depth: 2, // skip over the EventListener stack frame
})
// Establish the emergency ballast if we can. If there's not sufficient
// disk space, the ballast will be reestablished from Capacity when the
// store's capacity is queried periodically. Only try if the store is not
// an in-memory store. vfs.MemFS will error if you retrieve disk usage.
if cfg.Dir != "" /* if not in-memory */ {
du, err := cfg.Opts.FS.GetDiskUsage(cfg.Dir)
if err != nil {
return nil, errors.Wrap(err, "retrieving disk usage")
}
resized, err := maybeEstablishBallast(cfg.Opts.FS, ballastPath, cfg.BallastSize, du)
if err != nil {
return nil, errors.Wrap(err, "resizing ballast")
}
if resized {
cfg.Opts.Logger.Infof("resized ballast %s to size %s",
ballastPath, humanizeutil.IBytes(cfg.BallastSize))
}
}
p := &Pebble{
path: cfg.Dir,
auxDir: auxDir,
ballastPath: ballastPath,
ballastSize: cfg.BallastSize,
maxSize: cfg.MaxSize,
attrs: cfg.Attrs,
settings: cfg.Settings,
statsHandler: statsHandler,
fileRegistry: fileRegistry,
fs: cfg.Opts.FS,
logger: cfg.Opts.Logger,
storeIDPebbleLog: storeIDContainer,
}
p.connectEventMetrics(ctx, &cfg.Opts.EventListener)
p.eventListener = &cfg.Opts.EventListener
p.wrappedIntentWriter = wrapIntentWriter(ctx, p, cfg.Settings, true /* isLongLived */)
db, err := pebble.Open(cfg.StorageConfig.Dir, cfg.Opts)
if err != nil {
return nil, err
}
p.db = db
return p, nil
}
func newPebbleInMem(
ctx context.Context,
attrs roachpb.Attributes,
cacheSize, storeSize int64,
settings *cluster.Settings,
) *Pebble {
opts := DefaultPebbleOptions()
opts.Cache = pebble.NewCache(cacheSize)
defer opts.Cache.Unref()
opts.FS = vfs.NewMem()
db, err := NewPebble(
ctx,
PebbleConfig{
StorageConfig: base.StorageConfig{
Attrs: attrs,
MaxSize: storeSize,
Settings: settings,
},
Opts: opts,
})
if err != nil {
panic(err)
}
return db
}
func (p *Pebble) connectEventMetrics(ctx context.Context, eventListener *pebble.EventListener) {
oldDiskSlow := eventListener.DiskSlow
eventListener.DiskSlow = func(info pebble.DiskSlowInfo) {
oldDiskSlow(info)
maxSyncDuration := maxSyncDurationDefault
fatalOnExceeded := maxSyncDurationFatalOnExceededDefault
if p.settings != nil {
maxSyncDuration = MaxSyncDuration.Get(&p.settings.SV)
fatalOnExceeded = MaxSyncDurationFatalOnExceeded.Get(&p.settings.SV)
}
if info.Duration.Seconds() >= maxSyncDuration.Seconds() {
atomic.AddUint64(&p.diskStallCount, 1)
// Note that the below log messages go to the main cockroach log, not
// the pebble-specific log.
if fatalOnExceeded {
log.Fatalf(ctx, "disk stall detected: pebble unable to write to %s in %.2f seconds",
info.Path, redact.Safe(info.Duration.Seconds()))
} else {
log.Errorf(ctx, "disk stall detected: pebble unable to write to %s in %.2f seconds",
info.Path, redact.Safe(info.Duration.Seconds()))
}
return
}
atomic.AddUint64(&p.diskSlowCount, 1)
}
}
func (p *Pebble) String() string {
dir := p.path
if dir == "" {
dir = "<in-mem>"
}
attrs := p.attrs.String()
if attrs == "" {
attrs = "<no-attributes>"
}
return fmt.Sprintf("%s=%s", attrs, dir)
}
// Close implements the Engine interface.
func (p *Pebble) Close() {
if p.closed {
p.logger.Infof("closing unopened pebble instance")
return
}
p.closed = true
_ = p.db.Close()
}
// Closed implements the Engine interface.
func (p *Pebble) Closed() bool {
return p.closed
}
// ExportMVCCToSst is part of the engine.Reader interface.
func (p *Pebble) ExportMVCCToSst(
startKey, endKey roachpb.Key,
startTS, endTS hlc.Timestamp,
exportAllRevisions bool,
targetSize, maxSize uint64,
useTBI bool,
dest io.Writer,
) (roachpb.BulkOpSummary, roachpb.Key, error) {
r := wrapReader(p)
// Doing defer r.Free() does not inline.
maxIntentCount := MaxIntentsPerWriteIntentError.Get(&p.settings.SV)
summary, k, err := pebbleExportToSst(r, startKey, endKey, startTS, endTS, exportAllRevisions, targetSize,
maxSize, useTBI, dest, maxIntentCount)
r.Free()
return summary, k, err
}
// MVCCGet implements the Engine interface.
func (p *Pebble) MVCCGet(key MVCCKey) ([]byte, error) {
if len(key.Key) == 0 {
return nil, emptyKeyError()
}
r := wrapReader(p)
// Doing defer r.Free() does not inline.
v, err := r.MVCCGet(key)
r.Free()
return v, err
}
func (p *Pebble) rawGet(key []byte) ([]byte, error) {
ret, closer, err := p.db.Get(key)
if closer != nil {
retCopy := make([]byte, len(ret))
copy(retCopy, ret)
ret = retCopy
closer.Close()
}
if errors.Is(err, pebble.ErrNotFound) || len(ret) == 0 {
return nil, nil
}
return ret, err
}
// MVCCGetProto implements the Engine interface.
func (p *Pebble) MVCCGetProto(
key MVCCKey, msg protoutil.Message,
) (ok bool, keyBytes, valBytes int64, err error) {
return pebbleGetProto(p, key, msg)
}
// MVCCIterate implements the Engine interface.
func (p *Pebble) MVCCIterate(
start, end roachpb.Key, iterKind MVCCIterKind, f func(MVCCKeyValue) error,
) error {
if iterKind == MVCCKeyAndIntentsIterKind {
r := wrapReader(p)
// Doing defer r.Free() does not inline.
err := iterateOnReader(r, start, end, iterKind, f)
r.Free()
return err
}
return iterateOnReader(p, start, end, iterKind, f)
}
// NewMVCCIterator implements the Engine interface.
func (p *Pebble) NewMVCCIterator(iterKind MVCCIterKind, opts IterOptions) MVCCIterator {
if iterKind == MVCCKeyAndIntentsIterKind {
r := wrapReader(p)
// Doing defer r.Free() does not inline.
iter := r.NewMVCCIterator(iterKind, opts)
r.Free()
if util.RaceEnabled {
iter = wrapInUnsafeIter(iter)
}
return iter
}
iter := MVCCIterator(newPebbleIterator(p.db, nil, opts))
if iter == nil {
panic("couldn't create a new iterator")
}
if util.RaceEnabled {
iter = wrapInUnsafeIter(iter)
}
return iter
}
// NewEngineIterator implements the Engine interface.
func (p *Pebble) NewEngineIterator(opts IterOptions) EngineIterator {
iter := newPebbleIterator(p.db, nil, opts)
if iter == nil {
panic("couldn't create a new iterator")
}
return iter
}
// ConsistentIterators implements the Engine interface.
func (p *Pebble) ConsistentIterators() bool {
return false
}
// ApplyBatchRepr implements the Engine interface.
func (p *Pebble) ApplyBatchRepr(repr []byte, sync bool) error {
// batch.SetRepr takes ownership of the underlying slice, so make a copy.
reprCopy := make([]byte, len(repr))
copy(reprCopy, repr)
batch := p.db.NewBatch()
if err := batch.SetRepr(reprCopy); err != nil {
return err
}
opts := pebble.NoSync
if sync {
opts = pebble.Sync
}
return batch.Commit(opts)
}
// ClearMVCC implements the Engine interface.
func (p *Pebble) ClearMVCC(key MVCCKey) error {
if key.Timestamp.IsEmpty() {
panic("ClearMVCC timestamp is empty")
}
return p.clear(key)
}
// ClearUnversioned implements the Engine interface.
func (p *Pebble) ClearUnversioned(key roachpb.Key) error {
return p.clear(MVCCKey{Key: key})
}
// ClearIntent implements the Engine interface.
func (p *Pebble) ClearIntent(
key roachpb.Key, state PrecedingIntentState, txnDidNotUpdateMeta bool, txnUUID uuid.UUID,
) (int, error) {
_, separatedIntentCountDelta, err :=
p.wrappedIntentWriter.ClearIntent(key, state, txnDidNotUpdateMeta, txnUUID, nil)
return separatedIntentCountDelta, err
}
// ClearEngineKey implements the Engine interface.
func (p *Pebble) ClearEngineKey(key EngineKey) error {
if len(key.Key) == 0 {
return emptyKeyError()
}
return p.db.Delete(key.Encode(), pebble.Sync)
}
func (p *Pebble) clear(key MVCCKey) error {
if len(key.Key) == 0 {
return emptyKeyError()
}
return p.db.Delete(EncodeKey(key), pebble.Sync)
}
// SingleClearEngineKey implements the Engine interface.
func (p *Pebble) SingleClearEngineKey(key EngineKey) error {
if len(key.Key) == 0 {
return emptyKeyError()
}
return p.db.SingleDelete(key.Encode(), pebble.Sync)
}
// ClearRawRange implements the Engine interface.
func (p *Pebble) ClearRawRange(start, end roachpb.Key) error {
return p.clearRange(MVCCKey{Key: start}, MVCCKey{Key: end})
}
// ClearMVCCRangeAndIntents implements the Engine interface.
func (p *Pebble) ClearMVCCRangeAndIntents(start, end roachpb.Key) error {
_, err := p.wrappedIntentWriter.ClearMVCCRangeAndIntents(start, end, nil)
return err
}
// ClearMVCCRange implements the Engine interface.
func (p *Pebble) ClearMVCCRange(start, end MVCCKey) error {
return p.clearRange(start, end)
}
func (p *Pebble) clearRange(start, end MVCCKey) error {
bufStart := EncodeKey(start)
bufEnd := EncodeKey(end)
return p.db.DeleteRange(bufStart, bufEnd, pebble.Sync)
}
// ClearIterRange implements the Engine interface.
func (p *Pebble) ClearIterRange(iter MVCCIterator, start, end roachpb.Key) error {
// Write all the tombstones in one batch.
batch := p.NewUnindexedBatch(true /* writeOnly */)
defer batch.Close()
if err := batch.ClearIterRange(iter, start, end); err != nil {
return err
}
return batch.Commit(true)
}
// Merge implements the Engine interface.
func (p *Pebble) Merge(key MVCCKey, value []byte) error {
if len(key.Key) == 0 {
return emptyKeyError()
}
return p.db.Merge(EncodeKey(key), value, pebble.Sync)
}
// PutMVCC implements the Engine interface.
func (p *Pebble) PutMVCC(key MVCCKey, value []byte) error {
if key.Timestamp.IsEmpty() {
panic("PutMVCC timestamp is empty")
}
return p.put(key, value)
}
// PutUnversioned implements the Engine interface.
func (p *Pebble) PutUnversioned(key roachpb.Key, value []byte) error {
return p.put(MVCCKey{Key: key}, value)
}
// PutIntent implements the Engine interface.
func (p *Pebble) PutIntent(
ctx context.Context,
key roachpb.Key,
value []byte,
state PrecedingIntentState,
txnDidNotUpdateMeta bool,
txnUUID uuid.UUID,
) (int, error) {
_, separatedIntentCountDelta, err :=
p.wrappedIntentWriter.PutIntent(ctx, key, value, state, txnDidNotUpdateMeta, txnUUID, nil)
return separatedIntentCountDelta, err
}
// PutEngineKey implements the Engine interface.
func (p *Pebble) PutEngineKey(key EngineKey, value []byte) error {
if len(key.Key) == 0 {
return emptyKeyError()
}
return p.db.Set(key.Encode(), value, pebble.Sync)
}
// SafeToWriteSeparatedIntents implements the Engine interface.
func (p *Pebble) SafeToWriteSeparatedIntents(ctx context.Context) (bool, error) {
// This is not fast. Pebble should not be used by writers that want
// performance. They should use pebbleBatch.
return p.wrappedIntentWriter.safeToWriteSeparatedIntents(ctx)
}
// IsSeparatedIntentsEnabledForTesting implements the Engine interface.
func (p *Pebble) IsSeparatedIntentsEnabledForTesting(ctx context.Context) bool {
return !p.settings.Version.ActiveVersionOrEmpty(ctx).Less(
clusterversion.ByKey(clusterversion.SeparatedIntents)) && SeparatedIntentsEnabled.Get(&p.settings.SV)
}
func (p *Pebble) put(key MVCCKey, value []byte) error {
if len(key.Key) == 0 {
return emptyKeyError()
}
return p.db.Set(EncodeKey(key), value, pebble.Sync)
}
// LogData implements the Engine interface.
func (p *Pebble) LogData(data []byte) error {
return p.db.LogData(data, pebble.Sync)
}
// LogLogicalOp implements the Engine interface.
func (p *Pebble) LogLogicalOp(op MVCCLogicalOpType, details MVCCLogicalOpDetails) {
// No-op. Logical logging disabled.
}
// Attrs implements the Engine interface.
func (p *Pebble) Attrs() roachpb.Attributes {
return p.attrs
}
// Capacity implements the Engine interface.
func (p *Pebble) Capacity() (roachpb.StoreCapacity, error) {
dir := p.path
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