-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
pebble.go
2303 lines (2056 loc) · 74.5 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"
"encoding/binary"
"fmt"
"io"
"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/keys"
"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/buildutil"
"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"
"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/rangekey"
"github.com/cockroachdb/pebble/replay"
"github.com/cockroachdb/pebble/sstable"
"github.com/cockroachdb/pebble/vfs"
"github.com/cockroachdb/redact"
humanize "github.com/dustin/go-humanize"
)
const maxSyncDurationFatalOnExceededDefault = true
// Default for MaxSyncDuration below.
var maxSyncDurationDefault = envutil.EnvOrDefaultDuration("COCKROACH_ENGINE_MAX_SYNC_DURATION_DEFAULT", 20*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(
settings.TenantWritable,
"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(
settings.TenantWritable,
"storage.max_sync_duration.fatal.enabled",
"if true, fatal the process when a disk operation exceeds storage.max_sync_duration",
maxSyncDurationFatalOnExceededDefault,
)
// valueBlocksEnabled controls whether older versions of MVCC keys in the same
// sstable will have their values written to value blocks. This only affects
// sstables that will be written in the future, as part of flushes or
// compactions, and does not eagerly change the encoding of existing sstables.
// Reads can correctly read both kinds of sstables.
var valueBlocksEnabled = settings.RegisterBoolSetting(
settings.SystemOnly,
"storage.value_blocks.enabled",
"set to true to enable writing of value blocks in sstables",
false).WithPublic()
// 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. If the
// separator is found to be at -1 for both keys, then we are comparing bare
// suffixes without a user key part. Pebble requires bare suffixes to be
// comparable with the same ordering as if they had a common user key.
aSep := aEnd - int(a[aEnd])
bSep := bEnd - int(b[bEnd])
if aSep == -1 && bSep == -1 {
aSep, bSep = 0, 0 // comparing bare suffixes
}
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.
aVer := a[aSep:aEnd]
bVer := b[bSep:bEnd]
if len(aVer) == 0 {
if len(bVer) == 0 {
return 0
}
return -1
} else if len(bVer) == 0 {
return 1
}
aVer = normalizeEngineKeyVersionForCompare(aVer)
bVer = normalizeEngineKeyVersionForCompare(bVer)
return bytes.Compare(bVer, aVer)
}
// EngineKeyEqual checks for equality of cockroach keys, including the version
// (which could be MVCC timestamps).
func EngineKeyEqual(a, b []byte) bool {
// 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.Equal(a, b)
}
// Last byte is the version length + 1 when there is a version,
// else it is 0.
aVerLen := int(a[aEnd])
bVerLen := int(b[bEnd])
// Fast-path. If the key version is empty or contains only a walltime
// component then normalizeEngineKeyVersionForCompare is a no-op, so we don't
// need to split the "user key" from the version suffix before comparing to
// compute equality. Instead, we can check for byte equality immediately.
const withWall = mvccEncodedTimeSentinelLen + mvccEncodedTimeWallLen
const withLockTableLen = mvccEncodedTimeSentinelLen + engineKeyVersionLockTableLen
if (aVerLen <= withWall && bVerLen <= withWall) || (aVerLen == withLockTableLen && bVerLen == withLockTableLen) {
return bytes.Equal(a, b)
}
// Compute the index of the separator between the key and the version. If the
// separator is found to be at -1 for both keys, then we are comparing bare
// suffixes without a user key part. Pebble requires bare suffixes to be
// comparable with the same ordering as if they had a common user key.
aSep := aEnd - aVerLen
bSep := bEnd - bVerLen
if aSep == -1 && bSep == -1 {
aSep, bSep = 0, 0 // comparing bare suffixes
}
if aSep < 0 || bSep < 0 {
// This should never happen unless there is some sort of corruption of
// the keys.
return bytes.Equal(a, b)
}
// Compare the "user key" part of the key.
if !bytes.Equal(a[:aSep], b[:bSep]) {
return false
}
// Compare the version part of the key.
aVer := a[aSep:aEnd]
bVer := b[bSep:bEnd]
aVer = normalizeEngineKeyVersionForCompare(aVer)
bVer = normalizeEngineKeyVersionForCompare(bVer)
return bytes.Equal(aVer, bVer)
}
var zeroLogical [mvccEncodedTimeLogicalLen]byte
//gcassert:inline
func normalizeEngineKeyVersionForCompare(a []byte) []byte {
// In general, the version could also be a non-timestamp version, but we know
// that engineKeyVersionLockTableLen+mvccEncodedTimeSentinelLen is a different
// constant than the above, so there is no danger here of stripping parts from
// a non-timestamp version.
const withWall = mvccEncodedTimeSentinelLen + mvccEncodedTimeWallLen
const withLogical = withWall + mvccEncodedTimeLogicalLen
const withSynthetic = withLogical + mvccEncodedTimeSyntheticLen
if len(a) == withSynthetic {
// Strip the synthetic bit component from the timestamp version. The
// presence of the synthetic bit does not affect key ordering or equality.
a = a[:withLogical]
}
if len(a) == withLogical {
// If the timestamp version contains a logical timestamp component that is
// zero, strip the component. encodeMVCCTimestampToBuf will typically omit
// the entire logical component in these cases as an optimization, but it
// does not guarantee to never include a zero logical component.
// Additionally, we can fall into this case after stripping off other
// components of the key version earlier on in this function.
if bytes.Equal(a[withWall:], zeroLogical[:]) {
a = a[:withWall]
}
}
return a
}
// EngineComparer is a pebble.Comparer object that implements MVCC-specific
// comparator settings for use with Pebble.
var EngineComparer = &pebble.Comparer{
Compare: EngineKeyCompare,
Equal: EngineKeyEqual,
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)
},
ImmediateSuccessor: func(dst, a []byte) []byte {
// The key `a` is guaranteed to be a bare prefix: It's a
// `engineKeyNoVersion` key without a version—just a trailing 0-byte to
// signify the length of the version. For example the user key "foo" is
// encoded as: "foo\0". We need to encode the immediate successor to
// "foo", which in the natural byte ordering is "foo\0". Append a
// single additional zero, to encode the user key "foo\0" with a
// zero-length version.
return append(append(dst, a...), 0)
},
Split: func(k []byte) int {
keyLen := len(k)
if keyLen == 0 {
return 0
}
// Last byte is the version length + 1 when there is a version,
// else it is 0.
versionLen := int(k[keyLen-1])
// keyPartEnd points to the sentinel byte.
keyPartEnd := keyLen - 1 - versionLen
if keyPartEnd < 0 {
return keyLen
}
// 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 keyPartEnd + 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
},
}
// pebbleDataBlockMVCCTimeIntervalPointCollector implements
// pebble.DataBlockIntervalCollector for point keys.
type pebbleDataBlockMVCCTimeIntervalPointCollector struct {
pebbleDataBlockMVCCTimeIntervalCollector
}
var (
_ sstable.DataBlockIntervalCollector = (*pebbleDataBlockMVCCTimeIntervalPointCollector)(nil)
_ sstable.SuffixReplaceableBlockCollector = (*pebbleDataBlockMVCCTimeIntervalPointCollector)(nil)
)
func (tc *pebbleDataBlockMVCCTimeIntervalPointCollector) Add(
key pebble.InternalKey, _ []byte,
) error {
return tc.add(key.UserKey)
}
// pebbleDataBlockMVCCTimeIntervalRangeCollector implements
// pebble.DataBlockIntervalCollector for range keys.
type pebbleDataBlockMVCCTimeIntervalRangeCollector struct {
pebbleDataBlockMVCCTimeIntervalCollector
}
var (
_ sstable.DataBlockIntervalCollector = (*pebbleDataBlockMVCCTimeIntervalRangeCollector)(nil)
_ sstable.SuffixReplaceableBlockCollector = (*pebbleDataBlockMVCCTimeIntervalRangeCollector)(nil)
)
func (tc *pebbleDataBlockMVCCTimeIntervalRangeCollector) Add(
key pebble.InternalKey, value []byte,
) error {
// TODO(erikgrinaker): should reuse a buffer for keysDst, but keyspan.Key is
// not exported by Pebble.
span, err := rangekey.Decode(key, value, nil)
if err != nil {
return errors.Wrapf(err, "decoding range key at %s", key)
}
for _, k := range span.Keys {
if err := tc.add(k.Suffix); err != nil {
return errors.Wrapf(err, "recording suffix %x for range key at %s", k.Suffix, key)
}
}
return nil
}
// pebbleDataBlockMVCCTimeIntervalCollector is a helper for a
// pebble.DataBlockIntervalCollector that is used to construct a
// pebble.BlockPropertyCollector. This provides per-block filtering, which
// also gets aggregated to the sstable-level and filters out sstables. It must
// only be used for MVCCKeyIterKind iterators, since it will ignore
// blocks/sstables that contain intents (and any other key that is not a real
// MVCC key).
//
// This is wrapped by structs for point or range key collection, which actually
// implement pebble.DataBlockIntervalCollector.
type pebbleDataBlockMVCCTimeIntervalCollector struct {
// min, max are the encoded timestamps.
min, max []byte
}
// add collects the given slice in the collector. The slice may be an entire
// encoded MVCC key, or the bare suffix of an encoded key.
func (tc *pebbleDataBlockMVCCTimeIntervalCollector) add(b []byte) error {
if len(b) == 0 {
return nil
}
// Last byte is the version length + 1 when there is a version,
// else it is 0.
versionLen := int(b[len(b)-1])
if versionLen == 0 {
// This is not an MVCC key that we can collect.
return nil
}
// prefixPartEnd points to the sentinel byte, unless this is a bare suffix, in
// which case the index is -1.
prefixPartEnd := len(b) - 1 - versionLen
// Sanity check: the index should be >= -1. Additionally, if the index is >=
// 0, it should point to the sentinel byte, as this is a full EngineKey.
if prefixPartEnd < -1 || (prefixPartEnd >= 0 && b[prefixPartEnd] != sentinel) {
return errors.Errorf("invalid key %s", roachpb.Key(b).String())
}
// We don't need the last byte (the version length).
versionLen--
// Only collect if this looks like an MVCC timestamp.
if versionLen == engineKeyVersionWallTimeLen ||
versionLen == engineKeyVersionWallAndLogicalTimeLen ||
versionLen == engineKeyVersionWallLogicalAndSyntheticTimeLen {
// INVARIANT: -1 <= prefixPartEnd < len(b) - 1.
// Version consists of the bytes after the sentinel and before the length.
b = b[prefixPartEnd+1 : len(b)-1]
// Lexicographic comparison on the encoded timestamps is equivalent to the
// comparison on decoded timestamps, so delay decoding.
if len(tc.min) == 0 || bytes.Compare(b, tc.min) < 0 {
tc.min = append(tc.min[:0], b...)
}
if len(tc.max) == 0 || bytes.Compare(b, tc.max) > 0 {
tc.max = append(tc.max[:0], b...)
}
}
return nil
}
func decodeWallTime(ts []byte) uint64 {
return binary.BigEndian.Uint64(ts[0:engineKeyVersionWallTimeLen])
}
func (tc *pebbleDataBlockMVCCTimeIntervalCollector) FinishDataBlock() (
lower uint64,
upper uint64,
err error,
) {
if len(tc.min) == 0 {
// No calls to Add that contained a timestamped key.
return 0, 0, nil
}
// Construct a [lower, upper) walltime that will contain all the
// hlc.Timestamps in this block.
lower = decodeWallTime(tc.min)
// Remember that we have to reset tc.min and tc.max to get ready for the
// next data block, as specified in the DataBlockIntervalCollector interface
// help and help too.
tc.min = tc.min[:0]
// The actual value encoded into walltime is an int64, so +1 will not
// overflow.
upper = decodeWallTime(tc.max) + 1
tc.max = tc.max[:0]
if lower >= upper {
return 0, 0,
errors.Errorf("corrupt timestamps lower %d >= upper %d", lower, upper)
}
return lower, upper, nil
}
func (tc *pebbleDataBlockMVCCTimeIntervalCollector) UpdateKeySuffixes(
_ []byte, _, newSuffix []byte,
) error {
return tc.add(newSuffix)
}
const mvccWallTimeIntervalCollector = "MVCCTimeInterval"
var _ pebble.BlockPropertyFilterMask = (*mvccWallTimeIntervalRangeKeyMask)(nil)
type mvccWallTimeIntervalRangeKeyMask struct {
sstable.BlockIntervalFilter
}
// SetSuffix implements the pebble.BlockPropertyFilterMask interface.
func (m *mvccWallTimeIntervalRangeKeyMask) SetSuffix(suffix []byte) error {
if len(suffix) == 0 {
// This is currently impossible, because the only range key Cockroach
// writes today is the MVCC Delete Range that's always suffixed.
return nil
}
ts, err := DecodeMVCCTimestampSuffix(suffix)
if err != nil {
return err
}
m.BlockIntervalFilter.SetInterval(uint64(ts.WallTime), math.MaxUint64)
return nil
}
// PebbleBlockPropertyCollectors is the list of functions to construct
// BlockPropertyCollectors.
var PebbleBlockPropertyCollectors = []func() pebble.BlockPropertyCollector{
func() pebble.BlockPropertyCollector {
return sstable.NewBlockIntervalCollector(
mvccWallTimeIntervalCollector,
&pebbleDataBlockMVCCTimeIntervalPointCollector{},
&pebbleDataBlockMVCCTimeIntervalRangeCollector{},
)
},
}
// 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,
FS: vfs.Default,
L0CompactionThreshold: 2,
L0StopWritesThreshold: 1000,
LBaseMaxBytes: 64 << 20, // 64 MB
Levels: make([]pebble.LevelOptions, 7),
MaxConcurrentCompactions: func() int { return maxConcurrentCompactions },
MemTableSize: 64 << 20, // 64 MB
MemTableStopWritesThreshold: 4,
Merger: MVCCMerger,
BlockPropertyCollectors: PebbleBlockPropertyCollectors,
}
// 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.FlushDelayDeleteRange = 10 * time.Second
// Automatically flush 10s after the first range key is added to a memtable.
// This ensures that range keys are quickly flushed, allowing use of lazy
// combined iteration within Pebble.
opts.FlushDelayRangeKey = 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
// Validate min/max keys in each SSTable when performing a compaction. This
// serves as a simple protection against corruption or programmer-error in
// Pebble.
opts.Experimental.KeyValidationFunc = func(userKey []byte) error {
engineKey, ok := DecodeEngineKey(userKey)
if !ok {
return errors.Newf("key %s could not be decoded as an EngineKey", string(userKey))
}
if err := engineKey.Validate(); err != nil {
return err
}
return nil
}
opts.Experimental.ShortAttributeExtractor = shortAttributeExtractorForValues
opts.Experimental.RequiredInPlaceValueBound = pebble.UserKeyPrefixBound{
Lower: keys.LocalRangeLockTablePrefix,
Upper: keys.LocalRangeLockTablePrefix.PrefixEnd(),
}
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()
}
return opts
}
func shortAttributeExtractorForValues(
key []byte, keyPrefixLen int, value []byte,
) (pebble.ShortAttribute, error) {
suffixLen := len(key) - keyPrefixLen
const lockTableSuffixLen = engineKeyVersionLockTableLen + sentinelLen
if suffixLen == engineKeyNoVersion || suffixLen == lockTableSuffixLen {
// Not a versioned MVCC value.
return 0, nil
}
isTombstone, err := EncodedMVCCValueIsTombstone(value)
if err != nil {
return 0, err
}
if isTombstone {
return 1, nil
}
return 0, nil
}
// wrapFilesystemMiddleware wraps the Option's vfs.FS with disk-health checking
// and ENOSPC detection. It mutates the provided options to set the FS and
// returns a Closer that should be invoked when the filesystem will no longer be
// used.
func wrapFilesystemMiddleware(opts *pebble.Options) io.Closer {
// 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
}
// Instantiate a file system with disk health checking enabled. This FS
// wraps the filesystem with a layer that times all write-oriented
// operations.
var closer io.Closer
opts.FS, closer = vfs.WithDiskHealthChecks(opts.FS, diskHealthCheckInterval,
func(name string, duration time.Duration) {
opts.EventListener.DiskSlow(pebble.DiskSlowInfo{
Path: name,
Duration: duration,
})
})
// If we encounter ENOSPC, exit with an informative exit code.
opts.FS = vfs.OnDiskFull(opts.FS, func() {
exit.WithCode(exit.DiskFull())
})
return closer
}
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 {
atomic struct {
// compactionConcurrency is the current compaction concurrency set on
// the Pebble store. The compactionConcurrency option in the Pebble
// Options struct is a closure which will return
// Pebble.atomic.compactionConcurrency.
//
// This mechanism allows us to change the Pebble compactionConcurrency
// on the fly without restarting Pebble.
compactionConcurrency uint64
}
db *pebble.DB
closed bool
readOnly bool
path string
auxDir string
ballastPath string
ballastSize int64
maxSize int64
attrs roachpb.Attributes
properties roachpb.StoreProperties
// settings must be non-nil if this Pebble instance will be used to write
// intents.
settings *cluster.Settings
encryption *EncryptionEnv
fileRegistry *PebbleFileRegistry
// Stats updated by pebble.EventListener invocations, and returned in
// GetMetrics. Updated and retrieved atomically.
writeStallCount int64
writeStallDuration time.Duration
writeStallStartNanos int64
diskSlowCount int64
diskStallCount int64
// Relevant options copied over from pebble.Options.
fs vfs.FS
unencryptedFS vfs.FS
logCtx context.Context
logger pebble.Logger
eventListener *pebble.EventListener
mu struct {
// This mutex is the lowest in any lock ordering.
syncutil.Mutex
flushCompletedCallback func()
}
// supportsRangeKeys is 1 if the database supports range keys. It must
// be accessed atomically.
//
// TODO(erikgrinaker): Remove this after 22.2 when all databases support it.
supportsRangeKeys int32
// closer is populated when the database is opened. The closer is associated
// with the filesyetem
closer io.Closer
wrappedIntentWriter intentDemuxWriter
storeIDPebbleLog *base.StoreIDContainer
replayer *replay.WorkloadCollector
}
// WorkloadCollector implements an workloadCollectorGetter and returns the
// workload collector stored on Pebble. This method is invoked following a
// successful cast of an Engine to a `workloadCollectorGetter` type. This method
// allows for pebble exclusive functionality to be used without modifying the
// Engine interface.
func (p *Pebble) WorkloadCollector() *replay.WorkloadCollector {
return p.replayer
}
// EncryptionEnv describes the encryption-at-rest environment, providing
// access to a filesystem with on-the-fly encryption.
type EncryptionEnv struct {
// Closer closes the encryption-at-rest environment. Once the
// environment is closed, the environment's VFS may no longer be
// used.
Closer io.Closer
// FS provides the encrypted virtual filesystem. New files are
// transparently encrypted.
FS vfs.FS
// StatsHandler exposes encryption-at-rest state for observability.
StatsHandler EncryptionStatsHandler
}
var _ Engine = &Pebble{}
// WorkloadCollectorEnabled specifies if the workload collector will be enabled
var WorkloadCollectorEnabled = envutil.EnvOrDefaultBool("COCKROACH_STORAGE_WORKLOAD_COLLECTOR", false)
// 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) (*EncryptionEnv, 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)
}
// SetCompactionConcurrency will return the previous compaction concurrency.
func (p *Pebble) SetCompactionConcurrency(n uint64) uint64 {
prevConcurrency := atomic.SwapUint64(&p.atomic.compactionConcurrency, n)
return prevConcurrency
}
// 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, *EncryptionEnv, 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 env *EncryptionEnv
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
env, err = NewEncryptedEnvFunc(
cfg.Opts.FS,
fileRegistry,
cfg.Dir,
cfg.Opts.ReadOnly,
cfg.EncryptionOptions,
)
if err != nil {
return nil, nil, err
}
// TODO(jackson): Should this just return an EncryptionEnv,
// rather than mutating cfg.Opts?
cfg.Opts.FS = env.FS
}
return fileRegistry, env, nil
}
// NewPebble creates a new Pebble instance, at the specified path.
func NewPebble(ctx context.Context, cfg PebbleConfig) (p *Pebble, err 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()
}
// Initialize the FS, wrapping it with disk health-checking and
// ENOSPC-detection.
filesystemCloser := wrapFilesystemMiddleware(cfg.Opts)
defer func() {
if err != nil {
filesystemCloser.Close()
}
}()
// 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))
// 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)
logCtx = logtags.AddTag(logCtx, "pebble", nil)
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)
}
cfg.Opts.Experimental.EnableValueBlocks = func() bool {
version := settings.Version.ActiveVersionOrEmpty(logCtx)
return !version.Less(clusterversion.ByKey(
clusterversion.V23_1EnablePebbleFormatSSTableValueBlocks)) &&
valueBlocksEnabled.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)
// For some purposes, we want to always use an unencrypted
// filesystem. The call below to ResolveEncryptedEnvOptions will
// replace cfg.Opts.FS with a VFS wrapped with encryption-at-rest if
// necessary. Before we do that, save a handle on the unencrypted
// FS for those that need it. Some call sites need the unencrypted
// FS for the purpose of atomic renames.
unencryptedFS := cfg.Opts.FS
fileRegistry, env, err := ResolveEncryptedEnvOptions(&cfg)
if err != nil {
return nil, err
}
// If no logger was passed, the previous call to `EnsureDefaults` on
// `cfg.Opts` will set the logger to pebble's `DefaultLogger`. In
// crdb, we want pebble-related logs to go to the storage channel,
// so we update the logger here accordingly.
if cfg.Opts.Logger == nil || cfg.Opts.Logger == pebble.DefaultLogger {
cfg.Opts.Logger = pebbleLogger{
ctx: logCtx,
depth: 1,
}
}
// 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.
if !cfg.Opts.ReadOnly {
du, err := unencryptedFS.GetDiskUsage(cfg.Dir)
// If the FS is an in-memory FS, GetDiskUsage returns
// vfs.ErrUnsupported and we skip ballast creation.
if err != nil && !errors.Is(err, vfs.ErrUnsupported) {
return nil, errors.Wrap(err, "retrieving disk usage")
} else if err == nil {
resized, err := maybeEstablishBallast(unencryptedFS, 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))
}
}
}
storeProps := computeStoreProperties(ctx, cfg.Dir, cfg.Opts.ReadOnly, env != nil /* encryptionEnabled */)
p = &Pebble{
readOnly: cfg.Opts.ReadOnly,
path: cfg.Dir,
auxDir: auxDir,
ballastPath: ballastPath,
ballastSize: cfg.BallastSize,
maxSize: cfg.MaxSize,
attrs: cfg.Attrs,
properties: storeProps,
settings: cfg.Settings,
encryption: env,
fileRegistry: fileRegistry,
fs: cfg.Opts.FS,
unencryptedFS: unencryptedFS,
logger: cfg.Opts.Logger,
logCtx: logCtx,
storeIDPebbleLog: storeIDContainer,
closer: filesystemCloser,
replayer: replay.NewWorkloadCollector(cfg.StorageConfig.Dir),
}
// MaxConcurrentCompactions can be set by multiple sources, but all the
// sources will eventually call NewPebble. So, we override
// Opts.MaxConcurrentCompactions to a closure which will return
// Pebble.atomic.compactionConcurrency. This will allow us to both honor
// the compactions concurrency which has already been set and allow us
// to update the compactionConcurrency on the fly by changing the
// Pebble.atomic.compactionConcurrency variable.
p.atomic.compactionConcurrency = uint64(cfg.Opts.MaxConcurrentCompactions())
cfg.Opts.MaxConcurrentCompactions = func() int {
return int(atomic.LoadUint64(&p.atomic.compactionConcurrency))
}
el := pebble.TeeEventListener(
pebble.MakeLoggingEventListener(pebbleLogger{
ctx: logCtx,
depth: 2, // skip over the EventListener stack frame
}),
p.makeMetricEtcEventListener(ctx),
)
p.eventListener = &el
cfg.Opts.EventListener = &el
p.wrappedIntentWriter = wrapIntentWriter(p)
// Read the current store cluster version.
storeClusterVersion, err := getMinVersion(unencryptedFS, cfg.Dir)