forked from cockroachdb/cockroach
/
debug.go
623 lines (543 loc) · 15.7 KB
/
debug.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
// Copyright 2016 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. See the AUTHORS file
// for names of contributors.
//
// Author: Ben Darnell
package cli
import (
"bytes"
"errors"
"fmt"
"strconv"
"golang.org/x/net/context"
"github.com/cockroachdb/cockroach/config"
"github.com/cockroachdb/cockroach/keys"
"github.com/cockroachdb/cockroach/roachpb"
"github.com/cockroachdb/cockroach/storage"
"github.com/cockroachdb/cockroach/storage/engine"
"github.com/cockroachdb/cockroach/util/encoding"
"github.com/cockroachdb/cockroach/util/envutil"
"github.com/cockroachdb/cockroach/util/stop"
"github.com/cockroachdb/cockroach/util/timeutil"
"github.com/coreos/etcd/raft/raftpb"
"github.com/gogo/protobuf/proto"
"github.com/kr/pretty"
"github.com/spf13/cobra"
)
var debugKeysCmd = &cobra.Command{
Use: "keys [directory]",
Short: "dump all the keys in a store",
Long: `
Pretty-prints all keys in a store.
`,
RunE: runDebugKeys,
}
func parseRangeID(arg string) (roachpb.RangeID, error) {
rangeIDInt, err := strconv.ParseInt(arg, 10, 64)
if err != nil {
return 0, err
}
if rangeIDInt < 1 {
return 0, fmt.Errorf("illegal RangeID: %d", rangeIDInt)
}
return roachpb.RangeID(rangeIDInt), nil
}
func openStore(cmd *cobra.Command, dir string, stopper *stop.Stopper) (engine.Engine, error) {
setDefaultCacheSize(&cliContext.Context)
db := engine.NewRocksDB(roachpb.Attributes{}, dir,
cliContext.CacheSize, cliContext.MemtableBudget, 0, stopper)
if err := db.Open(); err != nil {
return nil, err
}
return db, nil
}
func printKey(kv engine.MVCCKeyValue) (bool, error) {
fmt.Printf("%q\n", kv.Key)
return false, nil
}
func printKeyValue(kv engine.MVCCKeyValue) (bool, error) {
if kv.Key.Timestamp != roachpb.ZeroTimestamp {
fmt.Printf("%s %q: ", kv.Key.Timestamp, kv.Key.Key)
} else {
fmt.Printf("%q: ", kv.Key.Key)
}
for _, decoder := range []func(kv engine.MVCCKeyValue) (string, error){tryRaftLogEntry, tryRangeDescriptor, tryMeta, tryAbort, tryTxn} {
out, err := decoder(kv)
if err != nil {
continue
}
fmt.Println(out)
return false, nil
}
// No better idea, just print raw bytes and hope that folks use `less -S`.
fmt.Printf("%q\n\n", kv.Value)
return false, nil
}
func runDebugKeys(cmd *cobra.Command, args []string) error {
stopper := stop.NewStopper()
defer stopper.Stop()
if len(args) != 1 {
return errors.New("one argument is required")
}
db, err := openStore(cmd, args[0], stopper)
if err != nil {
return err
}
d := cliContext.debug
from := engine.NilKey
to := engine.MVCCKeyMax
if d.raw {
if len(d.startKey) > 0 {
from = engine.MakeMVCCMetadataKey(roachpb.Key(d.startKey))
}
if len(d.endKey) > 0 {
to = engine.MakeMVCCMetadataKey(roachpb.Key(d.endKey))
}
} else {
if len(d.startKey) > 0 {
startKey, err := keys.UglyPrint(d.startKey)
if err != nil {
return err
}
from = engine.MakeMVCCMetadataKey(startKey)
}
if len(d.endKey) > 0 {
endKey, err := keys.UglyPrint(d.endKey)
if err != nil {
return err
}
to = engine.MakeMVCCMetadataKey(endKey)
}
}
printer := printKey
if d.values {
printer = printKeyValue
}
if err := db.Iterate(from, to, printer); err != nil {
return err
}
return nil
}
var debugSplitKeyCmd = &cobra.Command{
Use: "split-key [directory] [rangeid]",
Short: "Compute a split key for the given key range",
Long: `
Runs MVCCFindSplitKey on the given key range and prints debug information
and the obtained split key.
`,
RunE: runDebugSplitKey,
}
func runDebugSplitKey(cmd *cobra.Command, args []string) error {
stopper := stop.NewStopper()
defer stopper.Stop()
if len(args) != 2 {
return errors.New("store and rangeID must be specified")
}
db, err := openStore(cmd, args[0], stopper)
if err != nil {
return err
}
rangeID, err := parseRangeID(args[1])
if err != nil {
return err
}
snap := db.NewSnapshot()
defer snap.Close()
var desc roachpb.RangeDescriptor
if err := storage.IterateRangeDescriptors(snap, func(descInside roachpb.RangeDescriptor) (bool, error) {
if descInside.RangeID == rangeID {
desc = descInside
return true, nil
}
return false, nil
}); err != nil {
return err
}
if desc.RangeID != rangeID {
return fmt.Errorf("range %d not found", rangeID)
}
if splitKey, err := engine.MVCCFindSplitKey(context.Background(), snap, rangeID,
desc.StartKey, desc.EndKey, func(msg string, args ...interface{}) {
fmt.Printf(msg+"\n", args...)
}); err != nil {
fmt.Println("No SplitKey found:", err)
} else {
fmt.Println("Computed SplitKey:", splitKey)
}
return nil
}
var debugRangeDescriptorsCmd = &cobra.Command{
Use: "range-descriptors [directory]",
Short: "print all range descriptors in a store",
Long: `
Prints all range descriptors in a store with a history of changes.
`,
RunE: runDebugRangeDescriptors,
}
func descStr(desc roachpb.RangeDescriptor) string {
return fmt.Sprintf("[%s, %s)\n\tRaw:%s\n",
desc.StartKey, desc.EndKey, &desc)
}
func tryMeta(kv engine.MVCCKeyValue) (string, error) {
if !bytes.HasPrefix(kv.Key.Key, keys.Meta1Prefix) && !bytes.HasPrefix(kv.Key.Key, keys.Meta2Prefix) {
return "", errors.New("not a meta key")
}
value := roachpb.Value{
Timestamp: kv.Key.Timestamp,
RawBytes: kv.Value,
}
var desc roachpb.RangeDescriptor
if err := value.GetProto(&desc); err != nil {
return "", err
}
return descStr(desc), nil
}
func maybeUnmarshalInline(v []byte, dest proto.Message) error {
var meta engine.MVCCMetadata
if err := meta.Unmarshal(v); err != nil {
return err
}
value := roachpb.Value{
RawBytes: meta.RawBytes,
}
return value.GetProto(dest)
}
func tryTxn(kv engine.MVCCKeyValue) (string, error) {
var txn roachpb.Transaction
if err := maybeUnmarshalInline(kv.Value, &txn); err != nil {
return "", err
}
return txn.String() + "\n", nil
}
func tryAbort(kv engine.MVCCKeyValue) (string, error) {
if kv.Key.Timestamp != roachpb.ZeroTimestamp {
return "", errors.New("not an abort cache key")
}
_, err := keys.DecodeAbortCacheKey(kv.Key.Key, nil)
if err != nil {
return "", err
}
var dest roachpb.AbortCacheEntry
if err := maybeUnmarshalInline(kv.Value, &dest); err != nil {
return "", err
}
return fmt.Sprintf("key=%q, pri=%d\n", dest.Key, dest.Priority), nil
}
func tryRangeDescriptor(kv engine.MVCCKeyValue) (string, error) {
_, suffix, _, err := keys.DecodeRangeKey(kv.Key.Key)
if err != nil {
return "", err
}
if !bytes.Equal(suffix, keys.LocalRangeDescriptorSuffix) {
return "", fmt.Errorf("wrong suffix: %s", suffix)
}
value := roachpb.Value{
RawBytes: kv.Value,
}
var desc roachpb.RangeDescriptor
if err := value.GetProto(&desc); err != nil {
return "", err
}
return descStr(desc), nil
}
func printRangeDescriptor(kv engine.MVCCKeyValue) (bool, error) {
if out, err := tryRangeDescriptor(kv); err == nil {
fmt.Printf("%s %q: %s\n", kv.Key.Timestamp, kv.Key.Key, out)
}
return false, nil
}
func runDebugRangeDescriptors(cmd *cobra.Command, args []string) error {
stopper := stop.NewStopper()
defer stopper.Stop()
if len(args) != 1 {
return errors.New("one argument is required")
}
db, err := openStore(cmd, args[0], stopper)
if err != nil {
return err
}
start := engine.MakeMVCCMetadataKey(keys.LocalRangePrefix)
end := engine.MakeMVCCMetadataKey(keys.LocalRangeMax)
if err := db.Iterate(start, end, printRangeDescriptor); err != nil {
return err
}
return nil
}
var debugRaftLogCmd = &cobra.Command{
Use: "raft-log [directory] [range id]",
Short: "print the raft log for a range",
Long: `
Prints all log entries in a store for the given range.
`,
RunE: runDebugRaftLog,
}
func tryRaftLogEntry(kv engine.MVCCKeyValue) (string, error) {
var ent raftpb.Entry
if err := maybeUnmarshalInline(kv.Value, &ent); err != nil {
return "", err
}
if ent.Type == raftpb.EntryNormal {
if len(ent.Data) > 0 {
_, cmdData := storage.DecodeRaftCommand(ent.Data)
var cmd roachpb.RaftCommand
if err := cmd.Unmarshal(cmdData); err != nil {
return "", err
}
ent.Data = nil
return fmt.Sprintf("%s by %v\n%s\n%s\n", &ent, cmd.OriginReplica, &cmd.Cmd, &cmd), nil
}
return fmt.Sprintf("%s: EMPTY\n", &ent), nil
} else if ent.Type == raftpb.EntryConfChange {
var cc raftpb.ConfChange
if err := cc.Unmarshal(ent.Data); err != nil {
return "", err
}
var ctx storage.ConfChangeContext
if err := ctx.Unmarshal(cc.Context); err != nil {
return "", err
}
var cmd roachpb.RaftCommand
if err := cmd.Unmarshal(ctx.Payload); err != nil {
return "", err
}
ent.Data = nil
return fmt.Sprintf("%s\n%s\n", &ent, &cmd), nil
}
return "", fmt.Errorf("Unknown log entry type: %s\n", &ent)
}
func printRaftLogEntry(kv engine.MVCCKeyValue) (bool, error) {
if out, err := tryRaftLogEntry(kv); err != nil {
fmt.Printf("%q: %v\n\n", kv.Key.Key, err)
} else {
fmt.Printf("%q: %s\n", kv.Key.Key, out)
}
return false, nil
}
func runDebugRaftLog(cmd *cobra.Command, args []string) error {
stopper := stop.NewStopper()
defer stopper.Stop()
if len(args) != 2 {
return errors.New("required arguments: dir range_id")
}
db, err := openStore(cmd, args[0], stopper)
if err != nil {
return err
}
rangeID, err := parseRangeID(args[1])
if err != nil {
return err
}
start := engine.MakeMVCCMetadataKey(keys.RaftLogPrefix(rangeID))
end := engine.MakeMVCCMetadataKey(keys.RaftLogPrefix(rangeID).PrefixEnd())
if err := db.Iterate(start, end, printRaftLogEntry); err != nil {
return err
}
return nil
}
var debugGCCmd = &cobra.Command{
Use: "estimate-gc [directory] [range id]",
Short: "find out what a GC run would do",
Long: `
Sets up (but does not run) a GC collection cycle, giving insight into how much
work would be done (assuming all intent resolution and pushes succeed).
Without a RangeID specified on the command line, runs the analysis for all
ranges individually.
Uses a hard-coded GC policy with a 24 hour TTL for old versions.
`,
RunE: runDebugGCCmd,
}
func runDebugGCCmd(cmd *cobra.Command, args []string) error {
stopper := stop.NewStopper()
defer stopper.Stop()
if len(args) != 1 {
return errors.New("required arguments: dir")
}
var rangeID roachpb.RangeID
if len(args) == 2 {
var err error
if rangeID, err = parseRangeID(args[1]); err != nil {
return err
}
}
db, err := openStore(cmd, args[0], stopper)
if err != nil {
return err
}
start := keys.RangeDescriptorKey(roachpb.RKeyMin)
end := keys.RangeDescriptorKey(roachpb.RKeyMax)
var descs []roachpb.RangeDescriptor
if _, err := engine.MVCCIterate(context.Background(), db, start, end, roachpb.MaxTimestamp,
false /* !consistent */, nil, /* txn */
false /* !reverse */, func(kv roachpb.KeyValue) (bool, error) {
var desc roachpb.RangeDescriptor
_, suffix, _, err := keys.DecodeRangeKey(kv.Key)
if err != nil {
return false, err
}
if !bytes.Equal(suffix, keys.LocalRangeDescriptorSuffix) {
return false, nil
}
if err := kv.Value.GetProto(&desc); err != nil {
return false, err
}
if desc.RangeID == rangeID || rangeID == 0 {
descs = append(descs, desc)
}
return desc.RangeID == rangeID, nil
}); err != nil {
return err
}
if len(descs) == 0 {
return fmt.Errorf("no range matching the criteria found")
}
for _, desc := range descs {
snap := db.NewSnapshot()
defer snap.Close()
_, info, err := storage.RunGC(context.Background(), &desc, snap, roachpb.Timestamp{WallTime: timeutil.Now().UnixNano()},
config.GCPolicy{TTLSeconds: 24 * 60 * 60 /* 1 day */}, func(_ roachpb.Timestamp, _ *roachpb.Transaction, _ roachpb.PushTxnType) {
}, func(_ []roachpb.Intent, _, _ bool) error { return nil })
if err != nil {
return err
}
fmt.Printf("RangeID: %d [%s, %s):\n", desc.RangeID, desc.StartKey, desc.EndKey)
_, _ = pretty.Println(info)
}
return nil
}
var debugCheckStoreCmd = &cobra.Command{
Use: "check-store [directory]",
Short: "consistency check for a single store",
Long: `
Perform local consistency checks of a single store.
Capable of detecting the following errors:
* Raft logs that are inconsistent with their metadata
`,
RunE: runDebugCheckStoreCmd,
}
type replicaCheckInfo struct {
truncatedIndex uint64
appliedIndex uint64
firstIndex uint64
lastIndex uint64
}
func runDebugCheckStoreCmd(cmd *cobra.Command, args []string) error {
stopper := stop.NewStopper()
defer stopper.Stop()
if len(args) != 1 {
return errors.New("required arguments: dir")
}
db, err := openStore(cmd, args[0], stopper)
if err != nil {
return err
}
// Iterate over the entire range-id-local space.
start := roachpb.Key(keys.LocalRangeIDPrefix)
end := start.PrefixEnd()
replicaInfo := map[roachpb.RangeID]*replicaCheckInfo{}
getReplicaInfo := func(rangeID roachpb.RangeID) *replicaCheckInfo {
if info, ok := replicaInfo[rangeID]; ok {
return info
}
replicaInfo[rangeID] = &replicaCheckInfo{}
return replicaInfo[rangeID]
}
if _, err := engine.MVCCIterate(context.Background(), db, start, end, roachpb.MaxTimestamp,
false /* !consistent */, nil, /* txn */
false /* !reverse */, func(kv roachpb.KeyValue) (bool, error) {
rangeID, _, suffix, detail, err := keys.DecodeRangeIDKey(kv.Key)
if err != nil {
return false, err
}
switch {
case bytes.Equal(suffix, keys.LocalRaftTruncatedStateSuffix):
var trunc roachpb.RaftTruncatedState
if err := kv.Value.GetProto(&trunc); err != nil {
return false, err
}
getReplicaInfo(rangeID).truncatedIndex = trunc.Index
case bytes.Equal(suffix, keys.LocalRaftAppliedIndexSuffix):
idx, err := kv.Value.GetInt()
if err != nil {
return false, err
}
getReplicaInfo(rangeID).appliedIndex = uint64(idx)
case bytes.Equal(suffix, keys.LocalRaftLogSuffix):
_, index, err := encoding.DecodeUint64Ascending(detail)
if err != nil {
return false, err
}
ri := getReplicaInfo(rangeID)
if ri.firstIndex == 0 {
ri.firstIndex = index
ri.lastIndex = index
} else {
if index != ri.lastIndex+1 {
fmt.Printf("range %s: log index anomaly: %v followed by %v\n",
rangeID, ri.lastIndex, index)
}
ri.lastIndex = index
}
}
return false, nil
}); err != nil {
return err
}
for rangeID, info := range replicaInfo {
if info.truncatedIndex != info.firstIndex-1 {
fmt.Printf("range %s: truncated index %v should equal first index %v - 1\n",
rangeID, info.truncatedIndex, info.firstIndex)
}
if info.appliedIndex < info.firstIndex || info.appliedIndex > info.lastIndex {
fmt.Printf("range %s: applied index %v should be between first index %v and last index %v\n",
rangeID, info.appliedIndex, info.firstIndex, info.lastIndex)
}
}
return nil
}
var debugEnvCmd = &cobra.Command{
Use: "env",
Short: "output environment settings",
Long: `
Output environment variables that influence configuration.
`,
Run: func(cmd *cobra.Command, args []string) {
env := envutil.GetEnvReport()
fmt.Print(env)
},
}
func init() {
debugCmd.AddCommand(debugCmds...)
}
var debugCmds = []*cobra.Command{
debugKeysCmd,
debugRangeDescriptorsCmd,
debugRaftLogCmd,
debugGCCmd,
debugSplitKeyCmd,
debugCheckStoreCmd,
kvCmd,
rangeCmd,
debugEnvCmd,
}
var debugCmd = &cobra.Command{
Use: "debug [command]",
Short: "debugging commands",
Long: `Various commands for debugging.
These commands are useful for extracting data from the data files of a
process that has failed and cannot restart.
`,
Run: func(cmd *cobra.Command, args []string) {
mustUsage(cmd)
},
}