/
debug.go
391 lines (356 loc) · 11 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
// Copyright 2020 PingCAP, Inc. Licensed under Apache-2.0.
package main
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"path"
"reflect"
"github.com/pingcap/br/pkg/metautil"
"github.com/gogo/protobuf/proto"
"github.com/pingcap/errors"
backuppb "github.com/pingcap/kvproto/pkg/backup"
"github.com/pingcap/kvproto/pkg/import_sstpb"
"github.com/pingcap/log"
"github.com/pingcap/parser/model"
"github.com/spf13/cobra"
"github.com/tikv/pd/pkg/mock/mockid"
"go.uber.org/zap"
berrors "github.com/pingcap/br/pkg/errors"
"github.com/pingcap/br/pkg/logutil"
"github.com/pingcap/br/pkg/restore"
"github.com/pingcap/br/pkg/rtree"
"github.com/pingcap/br/pkg/task"
"github.com/pingcap/br/pkg/utils"
"github.com/pingcap/br/pkg/version/build"
)
// NewDebugCommand return a debug subcommand.
func NewDebugCommand() *cobra.Command {
meta := &cobra.Command{
Use: "debug <subcommand>",
Short: "commands to check/debug backup data",
SilenceUsage: false,
PersistentPreRunE: func(c *cobra.Command, args []string) error {
if err := Init(c); err != nil {
return errors.Trace(err)
}
build.LogInfo(build.BR)
utils.LogEnvVariables()
task.LogArguments(c)
return nil
},
// To be compatible with older BR.
Aliases: []string{"validate"},
}
meta.AddCommand(newCheckSumCommand())
meta.AddCommand(newBackupMetaCommand())
meta.AddCommand(decodeBackupMetaCommand())
meta.AddCommand(encodeBackupMetaCommand())
meta.AddCommand(setPDConfigCommand())
meta.Hidden = true
return meta
}
func newCheckSumCommand() *cobra.Command {
command := &cobra.Command{
Use: "checksum",
Short: "check the backup data",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error {
ctx, cancel := context.WithCancel(GetDefaultContext())
defer cancel()
var cfg task.Config
if err := cfg.ParseFromFlags(cmd.Flags()); err != nil {
return errors.Trace(err)
}
_, s, backupMeta, err := task.ReadBackupMeta(ctx, metautil.MetaFile, &cfg)
if err != nil {
return errors.Trace(err)
}
reader := metautil.NewMetaReader(backupMeta, s)
dbs, err := utils.LoadBackupTables(ctx, reader)
if err != nil {
return errors.Trace(err)
}
for _, schema := range backupMeta.Schemas {
dbInfo := &model.DBInfo{}
err = json.Unmarshal(schema.Db, dbInfo)
if err != nil {
return errors.Trace(err)
}
tblInfo := &model.TableInfo{}
err = json.Unmarshal(schema.Table, tblInfo)
if err != nil {
return errors.Trace(err)
}
tbl := dbs[dbInfo.Name.String()].GetTable(tblInfo.Name.String())
var calCRC64 uint64
var totalKVs uint64
var totalBytes uint64
for _, file := range tbl.Files {
calCRC64 ^= file.Crc64Xor
totalKVs += file.GetTotalKvs()
totalBytes += file.GetTotalBytes()
log.Info("file info", zap.Stringer("table", tblInfo.Name),
zap.String("file", file.GetName()),
zap.Uint64("crc64xor", file.GetCrc64Xor()),
zap.Uint64("totalKvs", file.GetTotalKvs()),
zap.Uint64("totalBytes", file.GetTotalBytes()),
zap.Uint64("startVersion", file.GetStartVersion()),
zap.Uint64("endVersion", file.GetEndVersion()),
logutil.Key("startKey", file.GetStartKey()),
logutil.Key("endKey", file.GetEndKey()),
)
var data []byte
data, err = s.ReadFile(ctx, file.Name)
if err != nil {
return errors.Trace(err)
}
s := sha256.Sum256(data)
if !bytes.Equal(s[:], file.Sha256) {
return errors.Annotatef(berrors.ErrBackupChecksumMismatch, `
backup data checksum failed: %s may be changed
calculated sha256 is %s,
origin sha256 is %s`,
file.Name, hex.EncodeToString(s[:]), hex.EncodeToString(file.Sha256))
}
}
log.Info("table info", zap.Stringer("table", tblInfo.Name),
zap.Uint64("CRC64", calCRC64),
zap.Uint64("totalKvs", totalKVs),
zap.Uint64("totalBytes", totalBytes),
zap.Uint64("schemaTotalKvs", schema.TotalKvs),
zap.Uint64("schemaTotalBytes", schema.TotalBytes),
zap.Uint64("schemaCRC64", schema.Crc64Xor))
}
cmd.Println("backup data checksum succeed!")
return nil
},
}
command.Hidden = true
return command
}
func newBackupMetaCommand() *cobra.Command {
command := &cobra.Command{
Use: "backupmeta",
Short: "utilities of backupmeta",
SilenceUsage: false,
}
command.AddCommand(newBackupMetaValidateCommand())
return command
}
func newBackupMetaValidateCommand() *cobra.Command {
command := &cobra.Command{
Use: "validate",
Short: "validate key range and rewrite rules of backupmeta",
RunE: func(cmd *cobra.Command, _ []string) error {
ctx, cancel := context.WithCancel(GetDefaultContext())
defer cancel()
tableIDOffset, err := cmd.Flags().GetUint64("offset")
if err != nil {
return errors.Trace(err)
}
var cfg task.Config
if err = cfg.ParseFromFlags(cmd.Flags()); err != nil {
return errors.Trace(err)
}
_, s, backupMeta, err := task.ReadBackupMeta(ctx, metautil.MetaFile, &cfg)
if err != nil {
log.Error("read backupmeta failed", zap.Error(err))
return errors.Trace(err)
}
reader := metautil.NewMetaReader(backupMeta, s)
dbs, err := utils.LoadBackupTables(ctx, reader)
if err != nil {
log.Error("load tables failed", zap.Error(err))
return errors.Trace(err)
}
files := make([]*backuppb.File, 0)
tables := make([]*metautil.Table, 0)
for _, db := range dbs {
for _, table := range db.Tables {
files = append(files, table.Files...)
}
tables = append(tables, db.Tables...)
}
// Check if the ranges of files overlapped
rangeTree := rtree.NewRangeTree()
for _, file := range files {
if out := rangeTree.InsertRange(rtree.Range{
StartKey: file.GetStartKey(),
EndKey: file.GetEndKey(),
}); out != nil {
log.Error(
"file ranges overlapped",
zap.Stringer("out", out),
logutil.File(file),
)
}
}
tableIDAllocator := mockid.NewIDAllocator()
// Advance table ID allocator to the offset.
for offset := uint64(0); offset < tableIDOffset; offset++ {
_, _ = tableIDAllocator.Alloc() // Ignore error
}
rewriteRules := &restore.RewriteRules{
Table: make([]*import_sstpb.RewriteRule, 0),
Data: make([]*import_sstpb.RewriteRule, 0),
}
tableIDMap := make(map[int64]int64)
// Simulate to create table
for _, table := range tables {
indexIDAllocator := mockid.NewIDAllocator()
newTable := new(model.TableInfo)
tableID, _ := tableIDAllocator.Alloc()
newTable.ID = int64(tableID)
newTable.Name = table.Info.Name
newTable.Indices = make([]*model.IndexInfo, len(table.Info.Indices))
for i, indexInfo := range table.Info.Indices {
indexID, _ := indexIDAllocator.Alloc()
newTable.Indices[i] = &model.IndexInfo{
ID: int64(indexID),
Name: indexInfo.Name,
}
}
rules := restore.GetRewriteRules(newTable, table.Info, 0)
rewriteRules.Table = append(rewriteRules.Table, rules.Table...)
rewriteRules.Data = append(rewriteRules.Data, rules.Data...)
tableIDMap[table.Info.ID] = int64(tableID)
}
// Validate rewrite rules
for _, file := range files {
err = restore.ValidateFileRewriteRule(file, rewriteRules)
if err != nil {
return errors.Trace(err)
}
}
cmd.Println("Check backupmeta done")
return nil
},
}
command.Flags().Uint64("offset", 0, "the offset of table id alloctor")
return command
}
func decodeBackupMetaCommand() *cobra.Command {
decodeBackupMetaCmd := &cobra.Command{
Use: "decode",
Short: "decode backupmeta to json",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
ctx, cancel := context.WithCancel(GetDefaultContext())
defer cancel()
var cfg task.Config
if err := cfg.ParseFromFlags(cmd.Flags()); err != nil {
return errors.Trace(err)
}
_, s, backupMeta, err := task.ReadBackupMeta(ctx, metautil.MetaFile, &cfg)
if err != nil {
return errors.Trace(err)
}
fieldName, _ := cmd.Flags().GetString("field")
if fieldName == "" {
// No field flag, write backupmeta to external storage in JSON format.
backupMetaJSON, err := utils.MarshalBackupMeta(backupMeta)
if err != nil {
return errors.Trace(err)
}
err = s.WriteFile(ctx, metautil.MetaJSONFile, backupMetaJSON)
if err != nil {
return errors.Trace(err)
}
cmd.Printf("backupmeta decoded at %s\n", path.Join(cfg.Storage, metautil.MetaJSONFile))
return nil
}
switch fieldName {
// To be compatible with older BR.
case "start-version":
fieldName = "StartVersion"
case "end-version":
fieldName = "EndVersion"
}
_, found := reflect.TypeOf(*backupMeta).FieldByName(fieldName)
if !found {
cmd.Printf("field '%s' not found\n", fieldName)
return nil
}
field := reflect.ValueOf(*backupMeta).FieldByName(fieldName)
if !field.CanInterface() {
cmd.Printf("field '%s' can not print\n", fieldName)
} else {
cmd.Printf("%v\n", field.Interface())
}
return nil
},
}
decodeBackupMetaCmd.Flags().String("field", "", "decode specified field")
return decodeBackupMetaCmd
}
func encodeBackupMetaCommand() *cobra.Command {
encodeBackupMetaCmd := &cobra.Command{
Use: "encode",
Short: "encode backupmeta json file to backupmeta",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
ctx, cancel := context.WithCancel(GetDefaultContext())
defer cancel()
var cfg task.Config
if err := cfg.ParseFromFlags(cmd.Flags()); err != nil {
return errors.Trace(err)
}
_, s, err := task.GetStorage(ctx, &cfg)
if err != nil {
return errors.Trace(err)
}
metaData, err := s.ReadFile(ctx, metautil.MetaJSONFile)
if err != nil {
return errors.Trace(err)
}
backupMetaJSON, err := utils.UnmarshalBackupMeta(metaData)
if err != nil {
return errors.Trace(err)
}
backupMeta, err := proto.Marshal(backupMetaJSON)
if err != nil {
return errors.Trace(err)
}
fileName := metautil.MetaFile
if ok, _ := s.FileExists(ctx, fileName); ok {
// Do not overwrite origin meta file
fileName += "_from_json"
}
err = s.WriteFile(ctx, fileName, backupMeta)
if err != nil {
return errors.Trace(err)
}
return nil
},
}
return encodeBackupMetaCmd
}
func setPDConfigCommand() *cobra.Command {
pdConfigCmd := &cobra.Command{
Use: "reset-pd-config-as-default",
Short: "reset pd config adjusted by BR to default value",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
ctx, cancel := context.WithCancel(GetDefaultContext())
defer cancel()
var cfg task.Config
if err := cfg.ParseFromFlags(cmd.Flags()); err != nil {
return errors.Trace(err)
}
mgr, err := task.NewMgr(ctx, tidbGlue, cfg.PD, cfg.TLS, task.GetKeepalive(&cfg), cfg.CheckRequirements, false)
if err != nil {
return errors.Trace(err)
}
defer mgr.Close()
if err := mgr.UpdatePDScheduleConfig(ctx); err != nil {
return errors.Annotate(err, "fail to update PD merge config")
}
log.Info("add pd configs succeed")
return nil
},
}
return pdConfigCmd
}