-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
pebble.go
2395 lines (2142 loc) · 76.3 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"
"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/syncutil"
"github.com/cockroachdb/cockroach/pkg/util/tracing"
"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/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", 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(
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,
)
// 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
if aVerLen <= withWall && bVerLen <= withWall {
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)
},
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
},
}
// TODO(sumeer): consider removing pebbleTimeBoundPropCollector for the 22.2
// release, since 22.1 nodes will be using BlockPropertyCollectors and there
// shouldn't be significant sstables that do not get rewritten for 6 months
// (we would have no time bound optimization for such sstables). Since it is
// possible for users to upgrade to 22.1 and then to 22.2 in quick succession
// this duration argument is not really valid. To be safe we could wait until
// 23.1.
// 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.
// The metadata unmarshaling logic discussed in the previous paragraph is
// flawed (see the comment
// https://github.com/cockroachdb/cockroach/issues/43799#issuecomment-576830234
// and its preceding comment), and we've worked around it as indicated in that
// issue. Due to that workaround, we need not unmarshal the metadata record at
// all.
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 := encodeMVCCTimestamp(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"
}
func (t *pebbleTimeBoundPropCollector) UpdateKeySuffixes(
oldProps map[string]string, oldSuffix []byte, newSuffix []byte,
) error {
t.updateBounds(newSuffix)
return nil
}
var _ sstable.SuffixReplaceableTableCollector = (*pebbleTimeBoundPropCollector)(nil)
// 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"
}
func (t *pebbleDeleteRangeCollector) UpdateKeySuffixes(
_ map[string]string, _ []byte, _ []byte,
) error {
return nil
}
var _ sstable.SuffixReplaceableTableCollector = (*pebbleTimeBoundPropCollector)(nil)
// PebbleTablePropertyCollectors is the list of Pebble TablePropertyCollectors.
var PebbleTablePropertyCollectors = []func() pebble.TablePropertyCollector{
func() pebble.TablePropertyCollector { return &pebbleTimeBoundPropCollector{} },
func() pebble.TablePropertyCollector { return &pebbleDeleteRangeCollector{} },
}
// pebbleDataBlockMVCCTimeIntervalCollector provides an implementation of
// 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).
type pebbleDataBlockMVCCTimeIntervalCollector struct {
// min, max are the encoded timestamps.
min, max []byte
}
var _ sstable.DataBlockIntervalCollector = &pebbleDataBlockMVCCTimeIntervalCollector{}
var _ sstable.SuffixReplaceableBlockCollector = (*pebbleDataBlockMVCCTimeIntervalCollector)(nil)
func (tc *pebbleDataBlockMVCCTimeIntervalCollector) Add(key pebble.InternalKey, _ []byte) error {
return tc.add(key.UserKey)
}
// 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"
// PebbleBlockPropertyCollectors is the list of functions to construct
// BlockPropertyCollectors.
var PebbleBlockPropertyCollectors = []func() pebble.BlockPropertyCollector{
func() pebble.BlockPropertyCollector {
return sstable.NewBlockIntervalCollector(
mvccWallTimeIntervalCollector,
&pebbleDataBlockMVCCTimeIntervalCollector{}, /* points */
nil, /* ranges */
)
},
}
// 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,
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.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
// 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
}
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
}
// 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,
})
})
// If we encounter ENOSPC, exit with an informative exit code.
opts.FS = vfs.OnDiskFull(opts.FS, func() {
exit.WithCode(exit.DiskFull())
})
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
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
diskSlowCount int64
diskStallCount int64
// Relevant options copied over from pebble.Options.
fs vfs.FS
unencryptedFS vfs.FS
logger pebble.Logger
eventListener *pebble.EventListener
mu struct {
// This mutex is the lowest in any lock ordering.
syncutil.Mutex
flushCompletedCallback func()
}
wrappedIntentWriter intentDemuxWriter
storeIDPebbleLog *base.StoreIDContainer
}
// 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{}
// 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)
}
// 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) (*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)
// 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
// TODO(jackson): Assert that unencryptedFS provides atomic renames.
fileRegistry, env, 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)
if cfg.Opts.Logger == nil {
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,
storeIDPebbleLog: storeIDContainer,
}
cfg.Opts.EventListener = pebble.TeeEventListener(
pebble.MakeLoggingEventListener(pebbleLogger{
ctx: logCtx,
depth: 2, // skip over the EventListener stack frame
}),
p.makeMetricEtcEventListener(ctx),
)
p.eventListener = &cfg.Opts.EventListener
p.wrappedIntentWriter = wrapIntentWriter(ctx, p)
// Read the current store cluster version.
storeClusterVersion, err := getMinVersion(unencryptedFS, cfg.Dir)
if err != nil {
return nil, err
}
db, err := pebble.Open(cfg.StorageConfig.Dir, cfg.Opts)
if err != nil {
return nil, err
}
p.db = db
if storeClusterVersion != (roachpb.Version{}) {
// The storage engine performs its own internal migrations
// through the setting of the store cluster version. When
// storage's min version is set, SetMinVersion writes to disk to
// commit to the new store cluster version. Then it idempotently
// applies any internal storage engine migrations necessitated
// or enabled by the new store cluster version. If we crash
// after committing the new store cluster version but before
// applying the internal migrations, we're left in an in-between
// state.
//
// To account for this, after the engine is open,
// unconditionally set the min cluster version again. If any
// storage engine state has not been updated, the call to
// SetMinVersion will update it. If all storage engine state is
// already updated, SetMinVersion is a noop.
if err := p.SetMinVersion(storeClusterVersion); err != nil {
p.Close()
return nil, err
}
}
return p, nil
}
func (p *Pebble) makeMetricEtcEventListener(ctx context.Context) pebble.EventListener {
return pebble.EventListener{
WriteStallBegin: func(info pebble.WriteStallBeginInfo) {
atomic.AddInt64(&p.writeStallCount, 1)
},
DiskSlow: func(info pebble.DiskSlowInfo) {
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.AddInt64(&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.AddInt64(&p.diskSlowCount, 1)
},
FlushEnd: func(info pebble.FlushInfo) {
if info.Err != nil {
return
}
p.mu.Lock()
cb := p.mu.flushCompletedCallback
p.mu.Unlock()
if cb != nil {
cb()