-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
printer.go
751 lines (687 loc) · 21.4 KB
/
printer.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
// Copyright 2015 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 keys
import (
"bytes"
"fmt"
"strconv"
"strings"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/util/encoding"
"github.com/cockroachdb/cockroach/pkg/util/uuid"
"github.com/pkg/errors"
)
// PrettyPrintTimeseriesKey is a hook for pretty printing a timeseries key. The
// timeseries key prefix will already have been stripped off.
var PrettyPrintTimeseriesKey func(key roachpb.Key) string
// DictEntry contains info on pretty-printing and pretty-scanning keys in a
// region of the key space.
type DictEntry struct {
Name string
prefix roachpb.Key
// print the key's pretty value, key has been removed prefix data
ppFunc func(valDirs []encoding.Direction, key roachpb.Key) string
// PSFunc parses the relevant prefix of the input into a roachpb.Key,
// returning the remainder and the key corresponding to the consumed prefix of
// 'input'. Allowed to panic on errors.
PSFunc KeyParserFunc
}
// KeyParserFunc is a function able to reverse pretty-printed keys.
type KeyParserFunc func(input string) (string, roachpb.Key)
func parseUnsupported(_ string) (string, roachpb.Key) {
panic(&ErrUglifyUnsupported{})
}
// KeyComprehensionTable contains information about how to decode pretty-printed
// keys, split by key spans.
type KeyComprehensionTable []struct {
Name string
start roachpb.Key
end roachpb.Key
Entries []DictEntry
}
var (
// ConstKeyDict translates some pretty-printed keys.
ConstKeyDict = []struct {
Name string
Value roachpb.Key
}{
{"/Max", MaxKey},
{"/Min", MinKey},
{"/Meta1/Max", Meta1KeyMax},
{"/Meta2/Max", Meta2KeyMax},
}
// KeyDict drives the pretty-printing and pretty-scanning of the key space.
KeyDict = KeyComprehensionTable{
{Name: "/Local", start: localPrefix, end: LocalMax, Entries: []DictEntry{
{Name: "/Store", prefix: roachpb.Key(localStorePrefix),
ppFunc: localStoreKeyPrint, PSFunc: localStoreKeyParse},
{Name: "/RangeID", prefix: roachpb.Key(LocalRangeIDPrefix),
ppFunc: localRangeIDKeyPrint, PSFunc: localRangeIDKeyParse},
{Name: "/Range", prefix: LocalRangePrefix, ppFunc: localRangeKeyPrint,
PSFunc: parseUnsupported},
}},
{Name: "/Meta1", start: Meta1Prefix, end: Meta1KeyMax, Entries: []DictEntry{
{Name: "", prefix: Meta1Prefix, ppFunc: print,
PSFunc: func(input string) (string, roachpb.Key) {
input = mustShiftSlash(input)
unq, err := strconv.Unquote(input)
if err != nil {
panic(err)
}
if len(unq) == 0 {
return "", Meta1Prefix
}
return "", RangeMetaKey(RangeMetaKey(MustAddr(
roachpb.Key(unq)))).AsRawKey()
},
}},
},
{Name: "/Meta2", start: Meta2Prefix, end: Meta2KeyMax, Entries: []DictEntry{
{Name: "", prefix: Meta2Prefix, ppFunc: print,
PSFunc: func(input string) (string, roachpb.Key) {
input = mustShiftSlash(input)
unq, err := strconv.Unquote(input)
if err != nil {
panic(&ErrUglifyUnsupported{err})
}
if len(unq) == 0 {
return "", Meta2Prefix
}
return "", RangeMetaKey(MustAddr(roachpb.Key(unq))).AsRawKey()
},
}},
},
{Name: "/System", start: SystemPrefix, end: SystemMax, Entries: []DictEntry{
{Name: "/NodeLiveness", prefix: NodeLivenessPrefix,
ppFunc: decodeKeyPrint,
PSFunc: parseUnsupported,
},
{Name: "/NodeLivenessMax", prefix: NodeLivenessKeyMax,
ppFunc: decodeKeyPrint,
PSFunc: parseUnsupported,
},
{Name: "/StatusNode", prefix: StatusNodePrefix,
ppFunc: decodeKeyPrint,
PSFunc: parseUnsupported,
},
{Name: "/tsd", prefix: TimeseriesPrefix,
ppFunc: timeseriesKeyPrint,
PSFunc: parseUnsupported,
},
}},
{Name: "/NamespaceTable", start: NamespaceTableMin, end: NamespaceTableMax, Entries: []DictEntry{
{Name: "", prefix: nil, ppFunc: decodeKeyPrint, PSFunc: parseUnsupported},
}},
{Name: "/Table", start: TableDataMin, end: TableDataMax, Entries: []DictEntry{
{Name: "", prefix: nil, ppFunc: decodeKeyPrint, PSFunc: tableKeyParse},
}},
{Name: "/Tenant", start: TenantTableDataMin, end: TenantTableDataMax, Entries: []DictEntry{
{Name: "", prefix: nil, ppFunc: tenantKeyPrint, PSFunc: tenantKeyParse},
}},
}
// keyofKeyDict means the key of suffix which is itself a key,
// should recursively pretty print it, see issue #3228
keyOfKeyDict = []struct {
name string
prefix []byte
}{
{name: "/Meta2", prefix: Meta2Prefix},
{name: "/Meta1", prefix: Meta1Prefix},
}
rangeIDSuffixDict = []struct {
name string
suffix []byte
ppFunc func(key roachpb.Key) string
psFunc func(rangeID roachpb.RangeID, input string) (string, roachpb.Key)
}{
{name: "AbortSpan", suffix: LocalAbortSpanSuffix, ppFunc: abortSpanKeyPrint, psFunc: abortSpanKeyParse},
{name: "RangeTombstone", suffix: LocalRangeTombstoneSuffix},
{name: "RaftHardState", suffix: LocalRaftHardStateSuffix},
{name: "RangeAppliedState", suffix: LocalRangeAppliedStateSuffix},
{name: "RaftAppliedIndex", suffix: LocalRaftAppliedIndexLegacySuffix},
{name: "LeaseAppliedIndex", suffix: LocalLeaseAppliedIndexLegacySuffix},
{name: "RaftLog", suffix: LocalRaftLogSuffix,
ppFunc: raftLogKeyPrint,
psFunc: raftLogKeyParse,
},
{name: "RaftTruncatedState", suffix: LocalRaftTruncatedStateLegacySuffix},
{name: "RangeLastReplicaGCTimestamp", suffix: LocalRangeLastReplicaGCTimestampSuffix},
{name: "RangeLease", suffix: LocalRangeLeaseSuffix},
{name: "RangeStats", suffix: LocalRangeStatsLegacySuffix},
{name: "RangeLastGC", suffix: LocalRangeLastGCSuffix},
}
rangeSuffixDict = []struct {
name string
suffix []byte
atEnd bool
}{
{name: "RangeDescriptor", suffix: LocalRangeDescriptorSuffix, atEnd: true},
{name: "Transaction", suffix: LocalTransactionSuffix, atEnd: false},
{name: "QueueLastProcessed", suffix: LocalQueueLastProcessedSuffix, atEnd: false},
}
)
var constSubKeyDict = []struct {
name string
key roachpb.RKey
}{
{"/storeIdent", localStoreIdentSuffix},
{"/gossipBootstrap", localStoreGossipSuffix},
{"/clusterVersion", localStoreClusterVersionSuffix},
{"/suggestedCompaction", localStoreSuggestedCompactionSuffix},
}
func suggestedCompactionKeyPrint(key roachpb.Key) string {
start, end, err := DecodeStoreSuggestedCompactionKey(key)
if err != nil {
return fmt.Sprintf("<invalid: %s>", err)
}
return fmt.Sprintf("{%s-%s}", start, end)
}
func localStoreKeyPrint(_ []encoding.Direction, key roachpb.Key) string {
for _, v := range constSubKeyDict {
if bytes.HasPrefix(key, v.key) {
if v.key.Equal(localStoreSuggestedCompactionSuffix) {
return v.name + "/" + suggestedCompactionKeyPrint(
append(roachpb.Key(nil), append(localStorePrefix, key...)...),
)
}
return v.name
}
}
return fmt.Sprintf("%q", []byte(key))
}
func localStoreKeyParse(input string) (remainder string, output roachpb.Key) {
for _, s := range constSubKeyDict {
if strings.HasPrefix(input, s.name) {
if s.key.Equal(localStoreSuggestedCompactionSuffix) {
panic(&ErrUglifyUnsupported{errors.New("cannot parse suggested compaction key")})
}
output = MakeStoreKey(s.key, nil)
return
}
}
input = mustShiftSlash(input)
slashPos := strings.IndexByte(input, '/')
if slashPos < 0 {
slashPos = len(input)
}
remainder = input[slashPos:] // `/something/else` -> `/else`
output = roachpb.Key(input[:slashPos])
return
}
const strTable = "/Table/"
const strSystemConfigSpan = "SystemConfigSpan"
const strSystemConfigSpanStart = "Start"
func tenantKeyParse(input string) (remainder string, output roachpb.Key) {
input = mustShiftSlash(input)
slashPos := strings.Index(input, "/")
if slashPos < 0 {
slashPos = len(input)
}
remainder = input[slashPos:] // `/something/else` -> `/else`
tenantIDStr := input[:slashPos]
tenantID, err := strconv.ParseUint(tenantIDStr, 10, 64)
fmt.Println(tenantID, err)
if err != nil {
panic(&ErrUglifyUnsupported{err})
}
output = MakeTenantPrefix(roachpb.TenantID(tenantID))
if strings.HasPrefix(remainder, strTable) {
var indexKey roachpb.Key
remainder = remainder[len(strTable)-1:]
remainder, indexKey = tableKeyParse(remainder)
output = append(output, indexKey...)
}
return remainder, output
}
func tableKeyParse(input string) (remainder string, output roachpb.Key) {
input = mustShiftSlash(input)
slashPos := strings.Index(input, "/")
if slashPos < 0 {
slashPos = len(input)
}
remainder = input[slashPos:] // `/something/else` -> `/else`
tableIDStr := input[:slashPos]
if tableIDStr == strSystemConfigSpan {
if remainder[1:] == strSystemConfigSpanStart {
remainder = ""
}
output = SystemConfigSpan.Key
return
}
tableID, err := strconv.ParseUint(tableIDStr, 10, 32)
if err != nil {
panic(&ErrUglifyUnsupported{err})
}
output = encoding.EncodeUvarintAscending(nil /* key */, tableID)
if remainder != "" {
var indexKey roachpb.Key
remainder, indexKey = tableIndexParse(remainder)
output = append(output, indexKey...)
}
return remainder, output
}
// tableIndexParse parses an index id out of the input and returns the remainder.
// The input is expected to be of the form "/<index id>[/...]".
func tableIndexParse(input string) (string, roachpb.Key) {
input = mustShiftSlash(input)
slashPos := strings.Index(input, "/")
if slashPos < 0 {
// We accept simply "/<id>"; if there's no further slashes, the whole string
// has to be the index id.
slashPos = len(input)
}
remainder := input[slashPos:] // `/something/else` -> `/else`
indexIDStr := input[:slashPos]
indexID, err := strconv.ParseUint(indexIDStr, 10, 32)
if err != nil {
panic(&ErrUglifyUnsupported{err})
}
output := encoding.EncodeUvarintAscending(nil /* key */, indexID)
return remainder, output
}
const strLogIndex = "/logIndex:"
func raftLogKeyParse(rangeID roachpb.RangeID, input string) (string, roachpb.Key) {
if !strings.HasPrefix(input, strLogIndex) {
panic("expected log index")
}
input = input[len(strLogIndex):]
index, err := strconv.ParseUint(input, 10, 64)
if err != nil {
panic(err)
}
return "", RaftLogKey(rangeID, index)
}
func raftLogKeyPrint(key roachpb.Key) string {
var logIndex uint64
var err error
key, logIndex, err = encoding.DecodeUint64Ascending(key)
if err != nil {
return fmt.Sprintf("/err<%v:%q>", err, []byte(key))
}
return fmt.Sprintf("%s%d", strLogIndex, logIndex)
}
func mustShiftSlash(in string) string {
slash, out := mustShift(in)
if slash != "/" {
panic("expected /: " + in)
}
return out
}
func mustShift(in string) (first, remainder string) {
if len(in) == 0 {
panic("premature end of string")
}
return in[:1], in[1:]
}
func localRangeIDKeyParse(input string) (remainder string, key roachpb.Key) {
var rangeID int64
var err error
input = mustShiftSlash(input)
if endPos := strings.IndexByte(input, '/'); endPos > 0 {
rangeID, err = strconv.ParseInt(input[:endPos], 10, 64)
if err != nil {
panic(err)
}
input = input[endPos:]
} else {
panic(errors.Errorf("illegal RangeID: %q", input))
}
input = mustShiftSlash(input)
var infix string
infix, input = mustShift(input)
var replicated bool
switch {
case bytes.Equal(localRangeIDUnreplicatedInfix, []byte(infix)):
case bytes.Equal(LocalRangeIDReplicatedInfix, []byte(infix)):
replicated = true
default:
panic(errors.Errorf("invalid infix: %q", infix))
}
input = mustShiftSlash(input)
// Get the suffix.
var suffix roachpb.RKey
for _, s := range rangeIDSuffixDict {
if strings.HasPrefix(input, s.name) {
input = input[len(s.name):]
if s.psFunc != nil {
remainder, key = s.psFunc(roachpb.RangeID(rangeID), input)
return
}
suffix = roachpb.RKey(s.suffix)
break
}
}
maker := makeRangeIDUnreplicatedKey
if replicated {
maker = makeRangeIDReplicatedKey
}
if suffix != nil {
if input != "" {
panic(&ErrUglifyUnsupported{errors.New("nontrivial detail")})
}
var detail roachpb.RKey
// TODO(tschottdorf): can't do this, init cycle:
// detail, err := UglyPrint(input)
// if err != nil {
// return "", nil, err
// }
remainder = ""
key = maker(roachpb.RangeID(rangeID), suffix, detail)
return
}
panic(&ErrUglifyUnsupported{errors.New("unhandled general range key")})
}
func localRangeIDKeyPrint(valDirs []encoding.Direction, key roachpb.Key) string {
var buf bytes.Buffer
if encoding.PeekType(key) != encoding.Int {
return fmt.Sprintf("/err<%q>", []byte(key))
}
// Get the rangeID.
key, i, err := encoding.DecodeVarintAscending(key)
if err != nil {
return fmt.Sprintf("/err<%v:%q>", err, []byte(key))
}
fmt.Fprintf(&buf, "/%d", i)
// Print and remove the rangeID infix specifier.
if len(key) != 0 {
fmt.Fprintf(&buf, "/%s", string(key[0]))
key = key[1:]
}
// Get the suffix.
hasSuffix := false
for _, s := range rangeIDSuffixDict {
if bytes.HasPrefix(key, s.suffix) {
fmt.Fprintf(&buf, "/%s", s.name)
key = key[len(s.suffix):]
if s.ppFunc != nil && len(key) != 0 {
fmt.Fprintf(&buf, "%s", s.ppFunc(key))
return buf.String()
}
hasSuffix = true
break
}
}
// Get the encode values.
if hasSuffix {
fmt.Fprintf(&buf, "%s", decodeKeyPrint(valDirs, key))
} else {
fmt.Fprintf(&buf, "%q", []byte(key))
}
return buf.String()
}
func localRangeKeyPrint(valDirs []encoding.Direction, key roachpb.Key) string {
var buf bytes.Buffer
for _, s := range rangeSuffixDict {
if s.atEnd {
if bytes.HasSuffix(key, s.suffix) {
key = key[:len(key)-len(s.suffix)]
_, decodedKey, err := encoding.DecodeBytesAscending([]byte(key), nil)
if err != nil {
fmt.Fprintf(&buf, "%s/%s", decodeKeyPrint(valDirs, key), s.name)
} else {
fmt.Fprintf(&buf, "%s/%s", roachpb.Key(decodedKey), s.name)
}
return buf.String()
}
} else {
begin := bytes.Index(key, s.suffix)
if begin > 0 {
addrKey := key[:begin]
_, decodedAddrKey, err := encoding.DecodeBytesAscending([]byte(addrKey), nil)
if err != nil {
fmt.Fprintf(&buf, "%s/%s", decodeKeyPrint(valDirs, addrKey), s.name)
} else {
fmt.Fprintf(&buf, "%s/%s", roachpb.Key(decodedAddrKey), s.name)
}
if bytes.Equal(s.suffix, LocalTransactionSuffix) {
txnID, err := uuid.FromBytes(key[(begin + len(s.suffix)):])
if err != nil {
return fmt.Sprintf("/%q/err:%v", key, err)
}
fmt.Fprintf(&buf, "/%q", txnID)
} else {
id := key[(begin + len(s.suffix)):]
fmt.Fprintf(&buf, "/%q", []byte(id))
}
return buf.String()
}
}
}
_, decodedKey, err := encoding.DecodeBytesAscending([]byte(key), nil)
if err != nil {
fmt.Fprintf(&buf, "%s", decodeKeyPrint(valDirs, key))
} else {
fmt.Fprintf(&buf, "%s", roachpb.Key(decodedKey))
}
return buf.String()
}
// ErrUglifyUnsupported is returned when UglyPrint doesn't know how to process a
// key.
type ErrUglifyUnsupported struct {
Wrapped error
}
func (euu *ErrUglifyUnsupported) Error() string {
return fmt.Sprintf("unsupported pretty key: %v", euu.Wrapped)
}
func abortSpanKeyParse(rangeID roachpb.RangeID, input string) (string, roachpb.Key) {
var err error
input = mustShiftSlash(input)
_, input = mustShift(input[:len(input)-1])
if len(input) != len(uuid.UUID{}.String()) {
panic(&ErrUglifyUnsupported{errors.New("txn id not available")})
}
id, err := uuid.FromString(input)
if err != nil {
panic(&ErrUglifyUnsupported{err})
}
return "", AbortSpanKey(rangeID, id)
}
func abortSpanKeyPrint(key roachpb.Key) string {
_, id, err := encoding.DecodeBytesAscending([]byte(key), nil)
if err != nil {
return fmt.Sprintf("/%q/err:%v", key, err)
}
txnID, err := uuid.FromBytes(id)
if err != nil {
return fmt.Sprintf("/%q/err:%v", key, err)
}
return fmt.Sprintf("/%q", txnID)
}
func print(_ []encoding.Direction, key roachpb.Key) string {
return fmt.Sprintf("/%q", []byte(key))
}
func decodeKeyPrint(valDirs []encoding.Direction, key roachpb.Key) string {
if key.Equal(SystemConfigSpan.Key) {
return "/SystemConfigSpan/Start"
}
return encoding.PrettyPrintValue(valDirs, key, "/")
}
func timeseriesKeyPrint(_ []encoding.Direction, key roachpb.Key) string {
return PrettyPrintTimeseriesKey(key)
}
func tenantKeyPrint(valDirs []encoding.Direction, key roachpb.Key) string {
key, tID, err := DecodeTenantPrefix(key)
if err != nil {
return fmt.Sprintf("/err:%v", err)
}
if len(key) == 0 {
return fmt.Sprintf("/%s", tID)
}
return fmt.Sprintf("/%s%s", tID, key.StringWithDirs(valDirs, 0))
}
// prettyPrintInternal parse key with prefix in KeyDict.
// For table keys, valDirs correspond to the encoding direction of each encoded
// value in key.
// If valDirs is unspecified, the default encoding direction for each value
// type is used (see encoding.go:prettyPrintFirstValue).
// If the key doesn't match any prefix in KeyDict, return its byte value with
// quotation and false, or else return its human readable value and true.
func prettyPrintInternal(valDirs []encoding.Direction, key roachpb.Key, quoteRawKeys bool) string {
for _, k := range ConstKeyDict {
if key.Equal(k.Value) {
return k.Name
}
}
helper := func(key roachpb.Key) (string, bool) {
var b strings.Builder
for _, k := range KeyDict {
if key.Compare(k.start) >= 0 && (k.end == nil || key.Compare(k.end) <= 0) {
b.WriteString(k.Name)
if k.end != nil && k.end.Compare(key) == 0 {
b.WriteString("/Max")
return b.String(), true
}
hasPrefix := false
for _, e := range k.Entries {
if bytes.HasPrefix(key, e.prefix) {
hasPrefix = true
key = key[len(e.prefix):]
b.WriteString(e.Name)
b.WriteString(e.ppFunc(valDirs, key))
break
}
}
if !hasPrefix {
key = key[len(k.start):]
if quoteRawKeys {
b.WriteByte('/')
b.WriteByte('"')
}
b.Write([]byte(key))
if quoteRawKeys {
b.WriteByte('"')
}
}
return b.String(), true
}
}
if quoteRawKeys {
return fmt.Sprintf("%q", []byte(key)), false
}
return fmt.Sprintf("%s", []byte(key)), false
}
for _, k := range keyOfKeyDict {
if bytes.HasPrefix(key, k.prefix) {
key = key[len(k.prefix):]
str, formatted := helper(key)
if formatted {
return k.name + str
}
return k.name + "/" + str
}
}
str, _ := helper(key)
return str
}
// PrettyPrint prints the key in a human readable format, see TestPrettyPrint.
// The output does not indicate whether a key is part of the replicated or un-
// replicated keyspace.
//
// valDirs correspond to the encoding direction of each encoded value in key.
// For example, table keys could have column values encoded in ascending or
// descending directions.
// If valDirs is unspecified, the default encoding direction for each value
// type is used (see encoding.go:prettyPrintFirstValue).
//
// See keysutil.UglyPrint() for an inverse.
func PrettyPrint(valDirs []encoding.Direction, key roachpb.Key) string {
return prettyPrintInternal(valDirs, key, true /* quoteRawKeys */)
}
func init() {
roachpb.PrettyPrintKey = PrettyPrint
roachpb.PrettyPrintRange = PrettyPrintRange
}
// MassagePrettyPrintedSpanForTest does some transformations on pretty-printed spans and keys:
// - if dirs is not nil, replace all ints with their ones' complement for
// descendingly-encoded columns.
// - strips line numbers from error messages.
func MassagePrettyPrintedSpanForTest(span string, dirs []encoding.Direction) string {
var r string
colIdx := -1
for i := 0; i < len(span); i++ {
if dirs != nil {
var d int
if _, err := fmt.Sscanf(span[i:], "%d", &d); err != nil {
// We've managed to consume an int.
dir := dirs[colIdx]
i += len(strconv.Itoa(d)) - 1
x := d
if dir == encoding.Descending {
x = ^x
}
r += strconv.Itoa(x)
continue
}
}
r += string(span[i])
switch span[i] {
case '/':
colIdx++
case '-', ' ':
// We're switching from the start constraints to the end constraints,
// or starting another span.
colIdx = -1
}
}
return r
}
// PrettyPrintRange pretty prints a compact representation of a key range. The
// output is of the form:
// commonPrefix{remainingStart-remainingEnd}
// If the end key is empty, the outut is of the form:
// start
// It prints at most maxChars, truncating components as needed. See
// TestPrettyPrintRange for some examples.
func PrettyPrintRange(start, end roachpb.Key, maxChars int) string {
var b bytes.Buffer
if maxChars < 8 {
maxChars = 8
}
prettyStart := prettyPrintInternal(nil /* valDirs */, start, false /* quoteRawKeys */)
if len(end) == 0 {
if len(prettyStart) <= maxChars {
return prettyStart
}
b.WriteString(prettyStart[:maxChars-1])
b.WriteRune('…')
return b.String()
}
prettyEnd := prettyPrintInternal(nil /* valDirs */, end, false /* quoteRawKeys */)
i := 0
// Find the common prefix.
for ; i < len(prettyStart) && i < len(prettyEnd) && prettyStart[i] == prettyEnd[i]; i++ {
}
// If we don't have space for at least '{a…-b…}' after the prefix, only print
// the prefix (or part of it).
if i > maxChars-7 {
if i > maxChars-1 {
i = maxChars - 1
}
b.WriteString(prettyStart[:i])
b.WriteRune('…')
return b.String()
}
b.WriteString(prettyStart[:i])
remaining := (maxChars - i - 3) / 2
printTrunc := func(b *bytes.Buffer, what string, maxChars int) {
if len(what) <= maxChars {
b.WriteString(what)
} else {
b.WriteString(what[:maxChars-1])
b.WriteRune('…')
}
}
b.WriteByte('{')
printTrunc(&b, prettyStart[i:], remaining)
b.WriteByte('-')
printTrunc(&b, prettyEnd[i:], remaining)
b.WriteByte('}')
return b.String()
}