-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
printer.go
393 lines (356 loc) · 11.5 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
// Copyright 2015 The Cockroach Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
//
// Author: Veteran Lu (23907238@qq.com)
package keys
import (
"bytes"
"fmt"
"strconv"
"strings"
"time"
"github.com/cockroachdb/cockroach/roachpb"
"github.com/cockroachdb/cockroach/util/encoding"
"github.com/cockroachdb/decimal"
)
type dictEntry struct {
name string
prefix roachpb.Key
// print the key's pretty value, key has been removed prefix data
ppFunc func(key roachpb.Key) string
}
var (
keyDict = []struct {
name string
start roachpb.Key
end roachpb.Key
entries []dictEntry
}{
{name: "/Local", start: localPrefix, end: LocalMax, entries: []dictEntry{
{name: "/Store", prefix: roachpb.Key(localStorePrefix), ppFunc: localStoreKeyPrint},
{name: "/RangeID", prefix: roachpb.Key(LocalRangeIDPrefix), ppFunc: localRangeIDKeyPrint},
{name: "/Range", prefix: LocalRangePrefix, ppFunc: localRangeKeyPrint},
}},
{name: "/Meta1", start: Meta1Prefix, end: Meta1KeyMax, entries: []dictEntry{
{name: "", prefix: Meta1Prefix, ppFunc: print},
}},
{name: "/Meta2", start: Meta2Prefix, end: Meta2KeyMax, entries: []dictEntry{
{name: "", prefix: Meta2Prefix, ppFunc: print},
}},
{name: "/System", start: SystemPrefix, end: SystemMax, entries: []dictEntry{
{name: "/StatusStore", prefix: StatusStorePrefix, ppFunc: decodeKeyPrint},
{name: "/StatusNode", prefix: StatusNodePrefix, ppFunc: decodeKeyPrint},
}},
{name: "/Table", start: TableDataMin, end: TableDataMax, entries: []dictEntry{
{name: "", prefix: nil, ppFunc: decodeKeyPrint},
}},
}
rangeIDSuffixDict = []struct {
name string
suffix []byte
ppFunc func(key roachpb.Key) string
}{
{name: "SequenceCache", suffix: LocalSequenceCacheSuffix, ppFunc: sequenceCacheKeyPrint},
{name: "RaftLeaderLease", suffix: localRaftLeaderLeaseSuffix},
{name: "RaftTombstone", suffix: localRaftTombstoneSuffix},
{name: "RaftHardState", suffix: localRaftHardStateSuffix},
{name: "RaftAppliedIndex", suffix: localRaftAppliedIndexSuffix},
{name: "RaftLog", suffix: localRaftLogSuffix, ppFunc: raftLogKeyPrint},
{name: "RaftTruncatedState", suffix: localRaftTruncatedStateSuffix},
{name: "RaftLastIndex", suffix: localRaftLastIndexSuffix},
{name: "RangeLastVerificationTimestamp", suffix: localRangeLastVerificationTimestampSuffix},
{name: "RangeStats", suffix: localRangeStatsSuffix},
}
rangeSuffixDict = []struct {
name string
suffix []byte
atEnd bool
}{
{name: "RangeDescriptor", suffix: LocalRangeDescriptorSuffix, atEnd: true},
{name: "RangeTreeNode", suffix: localRangeTreeNodeSuffix, atEnd: true},
{name: "Transaction", suffix: localTransactionSuffix, atEnd: false},
}
)
func localStoreKeyPrint(key roachpb.Key) string {
if bytes.HasPrefix(key, localStoreIdentSuffix) {
return "/storeIdent"
} else if bytes.HasPrefix(key, localStoreGossipSuffix) {
return "/gossipBootstrap"
}
return fmt.Sprintf("%q", []byte(key))
}
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("/logIndex:%d", logIndex)
}
func localRangeIDKeyPrint(key roachpb.Key) string {
var buf bytes.Buffer
if encoding.PeekType(key) != encoding.Int {
return fmt.Sprintf("/err<%q>", []byte(key))
}
// get range id
key, i, err := encoding.DecodeVarintAscending(key)
if err != nil {
return fmt.Sprintf("/err<%v:%q>", err, []byte(key))
}
fmt.Fprintf(&buf, "/%d", i)
// get 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 encode values
if hasSuffix {
fmt.Fprintf(&buf, "%s", decodeKeyPrint(key))
} else {
fmt.Fprintf(&buf, "%q", []byte(key))
}
return buf.String()
}
func localRangeKeyPrint(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)]
fmt.Fprintf(&buf, "/%s%s", s.name, decodeKeyPrint(key))
return buf.String()
}
} else {
begin := bytes.Index(key, s.suffix)
if begin > 0 {
addrKey := key[:begin]
id := key[(begin + len(s.suffix)):]
fmt.Fprintf(&buf, "/%s/addrKey:%s/id:%q", s.name, decodeKeyPrint(addrKey), []byte(id))
return buf.String()
}
}
}
fmt.Fprintf(&buf, "%s", decodeKeyPrint(key))
return buf.String()
}
func sequenceCacheKeyPrint(key roachpb.Key) string {
b, id, err := encoding.DecodeBytesAscending([]byte(key), nil)
if err != nil {
return fmt.Sprintf("/%q/err:%v", key, err)
}
if len(b) == 0 {
return fmt.Sprintf("/%q", id)
}
b, epoch, err := encoding.DecodeUint32Descending(b)
if err != nil {
return fmt.Sprintf("/%q/err:%v", id, err)
}
_, seq, err := encoding.DecodeUint32Descending(b)
if err != nil {
return fmt.Sprintf("/%q/epoch:%d/err:%v", id, epoch, err)
}
return fmt.Sprintf("/%q/epoch:%d/seq:%d", id, epoch, seq)
}
func print(key roachpb.Key) string {
return fmt.Sprintf("/%q", []byte(key))
}
func decodeKeyPrint(key roachpb.Key) string {
var buf bytes.Buffer
for k := 0; len(key) > 0; k++ {
var err error
switch encoding.PeekType(key) {
case encoding.Null:
key, _ = encoding.DecodeIfNull(key)
fmt.Fprintf(&buf, "/NULL")
case encoding.NotNull:
key, _ = encoding.DecodeIfNotNull(key)
fmt.Fprintf(&buf, "/#")
case encoding.Int:
var i int64
key, i, err = encoding.DecodeVarintAscending(key)
if err == nil {
fmt.Fprintf(&buf, "/%d", i)
}
case encoding.Float:
// Decode both floats and decimals as decimals to avoid
// overflow.
// TODO(nvanbenschoten) This doesn't work with infinity or NaN.
var d decimal.Decimal
key, d, err = encoding.DecodeDecimalAscending(key, nil)
if err == nil {
fmt.Fprintf(&buf, "/%s", d)
}
case encoding.Bytes:
var s string
key, s, err = encoding.DecodeStringAscending(key, nil)
if err == nil {
fmt.Fprintf(&buf, "/%q", s)
}
case encoding.BytesDesc:
var s string
key, s, err = encoding.DecodeStringDescending(key, nil)
if err == nil {
fmt.Fprintf(&buf, "/%q", s)
}
case encoding.Time:
var t time.Time
key, t, err = encoding.DecodeTimeAscending(key)
if err == nil {
fmt.Fprintf(&buf, "/%s", t.UTC().Format(time.UnixDate))
}
case encoding.TimeDesc:
var t time.Time
key, t, err = encoding.DecodeTimeDescending(key)
if err == nil {
fmt.Fprintf(&buf, "/%s", t.UTC().Format(time.UnixDate))
}
default:
// This shouldn't ever happen, but if it does let the loop exit.
fmt.Fprintf(&buf, "/%q", []byte(key))
key = nil
}
if err != nil {
fmt.Fprintf(&buf, "/<%v>", err)
continue
}
}
return buf.String()
}
// PrettyPrint prints the key in a human readable format:
//
// Key's Format Key's Value
// /Local/... "\x01"+...
// /Store/... "\x01s"+...
// /RangeID/... "\x01s"+[rangeid]
// /[rangeid]/SequenceCache/[id]/seq:[seq] "\x01s"+[rangeid]+"res-"+[id]+[seq]
// /[rangeid]/RaftLeaderLease "\x01s"+[rangeid]+"rfll"
// /[rangeid]/RaftTombstone "\x01s"+[rangeid]+"rftb"
// /[rangeid]/RaftHardState "\x01s"+[rangeid]+"rfth"
// /[rangeid]/RaftAppliedIndex "\x01s"+[rangeid]+"rfta"
// /[rangeid]/RaftLog/logIndex:[logIndex] "\x01s"+[rangeid]+"rftl"+[logIndex]
// /[rangeid]/RaftTruncatedState "\x01s"+[rangeid]+"rftt"
// /[rangeid]/RaftLastIndex "\x01s"+[rangeid]+"rfti"
// /[rangeid]/RangeLastVerificationTimestamp "\x01s"+[rangeid]+"rlvt"
// /[rangeid]/RangeStats "\x01s"+[rangeid]+"stat"
// /Range/... "\x01k"+...
// /RangeDescriptor/[key] "\x01k"+[key]+"rdsc"
// /RangeTreeNode/[key] "\x01k"+[key]+"rtn-"
// /Transaction/addrKey:[key]/id:[id] "\x01k"+[key]+"txn-"+[id]
// /Local/Max "\x02"
//
// /Meta1/[key] "\x02"+[key]
// /Meta2/[key] "\x03"+[key]
// /System/... "\x04"
// /StatusStore/[key] "\x04status-store-"+[key]
// /StatusNode/[key] "\x04status-node-"+[key]
// /System/Max "\x05"
//
// /Table/[key] [key]
//
// /Min ""
// /Max "\xff\xff"
func PrettyPrint(key roachpb.Key) string {
if bytes.Equal(key, MaxKey) {
return "/Max"
} else if bytes.Equal(key, MinKey) {
return "/Min"
}
var buf bytes.Buffer
for _, k := range keyDict {
if key.Compare(k.start) >= 0 && (k.end == nil || key.Compare(k.end) <= 0) {
fmt.Fprintf(&buf, "%s", k.name)
if k.end != nil && k.end.Compare(key) == 0 {
fmt.Fprintf(&buf, "/Max")
return buf.String()
}
hasPrefix := false
for _, e := range k.entries {
if bytes.HasPrefix(key, e.prefix) {
hasPrefix = true
key = key[len(e.prefix):]
fmt.Fprintf(&buf, "%s%s", e.name, e.ppFunc(key))
break
}
}
if !hasPrefix {
key = key[len(k.start):]
fmt.Fprintf(&buf, "/%q", []byte(key))
}
return buf.String()
}
}
return fmt.Sprintf("%q", []byte(key))
}
func init() {
roachpb.PrettyPrintKey = PrettyPrint
}
// 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++ {
d := -789
fmt.Sscanf(span[i:], "%d", &d)
if (dirs != nil) && (d != -789) {
// 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)
} else {
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
case '<':
// This is an error message, like <util/encoding/encoding.go:256: ....>.
end := strings.Index(span[i:], ">")
if end == -1 {
panic("parse error")
}
errMsg := span[i+1 : i+end+1]
lineIdx := strings.Index(errMsg, ":")
if lineIdx != -1 {
var lineEnd int
for lineEnd = lineIdx + 1; errMsg[lineEnd] >= '0' && errMsg[lineEnd] <= '9'; lineEnd++ {
}
errMsg = errMsg[:lineIdx] + errMsg[lineIdx+(lineEnd-lineIdx):]
}
r += errMsg
i += end
}
}
}
return r
}