forked from pingcap/tidb
/
schema.go
249 lines (224 loc) · 6.89 KB
/
schema.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
// Copyright 2020 PingCAP, Inc. Licensed under Apache-2.0.
package backup
import (
"context"
"encoding/json"
"time"
"github.com/opentracing/opentracing-go"
"github.com/pingcap/errors"
backuppb "github.com/pingcap/kvproto/pkg/brpb"
"github.com/pingcap/log"
"github.com/twotigers93/tidb/br/pkg/checkpoint"
"github.com/twotigers93/tidb/br/pkg/checksum"
"github.com/twotigers93/tidb/br/pkg/glue"
"github.com/twotigers93/tidb/br/pkg/logutil"
"github.com/twotigers93/tidb/br/pkg/metautil"
"github.com/twotigers93/tidb/br/pkg/summary"
"github.com/twotigers93/tidb/br/pkg/utils"
"github.com/twotigers93/tidb/kv"
"github.com/twotigers93/tidb/parser/model"
"github.com/twotigers93/tidb/statistics/handle"
"go.uber.org/zap"
"golang.org/x/sync/errgroup"
)
const (
// DefaultSchemaConcurrency is the default number of the concurrent
// backup schema tasks.
DefaultSchemaConcurrency = 64
)
type schemaInfo struct {
tableInfo *model.TableInfo
dbInfo *model.DBInfo
crc64xor uint64
totalKvs uint64
totalBytes uint64
stats *handle.JSONTable
}
type iterFuncTp func(kv.Storage, func(*model.DBInfo, *model.TableInfo)) error
// Schemas is task for backuping schemas.
type Schemas struct {
iterFunc iterFuncTp
size int
// checkpoint: table id -> checksum
checkpointChecksum map[int64]*checkpoint.ChecksumItem
}
func NewBackupSchemas(iterFunc iterFuncTp, size int) *Schemas {
return &Schemas{
iterFunc: iterFunc,
size: size,
checkpointChecksum: nil,
}
}
func (ss *Schemas) SetCheckpointChecksum(checkpointChecksum map[int64]*checkpoint.ChecksumItem) {
ss.checkpointChecksum = checkpointChecksum
}
// BackupSchemas backups table info, including checksum and stats.
func (ss *Schemas) BackupSchemas(
ctx context.Context,
metaWriter *metautil.MetaWriter,
checkpointRunner *checkpoint.CheckpointRunner[checkpoint.BackupKeyType, checkpoint.BackupValueType],
store kv.Storage,
statsHandle *handle.Handle,
backupTS uint64,
concurrency uint,
copConcurrency uint,
skipChecksum bool,
updateCh glue.Progress,
) error {
if span := opentracing.SpanFromContext(ctx); span != nil && span.Tracer() != nil {
span1 := span.Tracer().StartSpan("Schemas.BackupSchemas", opentracing.ChildOf(span.Context()))
defer span1.Finish()
ctx = opentracing.ContextWithSpan(ctx, span1)
}
workerPool := utils.NewWorkerPool(concurrency, "Schemas")
errg, ectx := errgroup.WithContext(ctx)
startAll := time.Now()
op := metautil.AppendSchema
metaWriter.StartWriteMetasAsync(ctx, op)
err := ss.iterFunc(store, func(dbInfo *model.DBInfo, tableInfo *model.TableInfo) {
// because the field of `dbInfo` would be modified, which affects the later iteration.
// so copy the `dbInfo` for each to `newDBInfo`
newDBInfo := *dbInfo
schema := &schemaInfo{
tableInfo: tableInfo,
dbInfo: &newDBInfo,
}
if utils.IsSysDB(schema.dbInfo.Name.L) {
schema.dbInfo.Name = utils.TemporaryDBName(schema.dbInfo.Name.O)
}
var checksum *checkpoint.ChecksumItem
var exists bool = false
if ss.checkpointChecksum != nil && schema.tableInfo != nil {
checksum, exists = ss.checkpointChecksum[schema.tableInfo.ID]
}
workerPool.ApplyOnErrorGroup(errg, func() error {
if schema.tableInfo != nil {
logger := log.L().With(
zap.String("db", schema.dbInfo.Name.O),
zap.String("table", schema.tableInfo.Name.O),
)
if !skipChecksum {
logger.Info("Calculate table checksum start")
if exists && checksum != nil {
schema.crc64xor = checksum.Crc64xor
schema.totalKvs = checksum.TotalKvs
schema.totalBytes = checksum.TotalBytes
logger.Info("Calculate table checksum completed (from checkpoint)",
zap.Uint64("Crc64Xor", schema.crc64xor),
zap.Uint64("TotalKvs", schema.totalKvs),
zap.Uint64("TotalBytes", schema.totalBytes))
} else {
start := time.Now()
err := schema.calculateChecksum(ectx, store.GetClient(), backupTS, copConcurrency)
if err != nil {
return errors.Trace(err)
}
calculateCost := time.Since(start)
if checkpointRunner != nil {
// if checkpoint runner is running and the checksum is not from checkpoint
// then flush the checksum by the checkpoint runner
if err = checkpointRunner.FlushChecksum(ctx, schema.tableInfo.ID, schema.crc64xor, schema.totalKvs, schema.totalBytes); err != nil {
return errors.Trace(err)
}
}
logger.Info("Calculate table checksum completed",
zap.Uint64("Crc64Xor", schema.crc64xor),
zap.Uint64("TotalKvs", schema.totalKvs),
zap.Uint64("TotalBytes", schema.totalBytes),
zap.Duration("calculate-take", calculateCost))
}
}
if statsHandle != nil {
if err := schema.dumpStatsToJSON(statsHandle); err != nil {
logger.Error("dump table stats failed", logutil.ShortError(err))
}
}
}
// Send schema to metawriter
s, err := schema.encodeToSchema()
if err != nil {
return errors.Trace(err)
}
if err := metaWriter.Send(s, op); err != nil {
return errors.Trace(err)
}
if updateCh != nil {
updateCh.Inc()
}
return nil
})
})
if err != nil {
return errors.Trace(err)
}
if err := errg.Wait(); err != nil {
return errors.Trace(err)
}
log.Info("Backup calculated table checksum into metas", zap.Duration("take", time.Since(startAll)))
summary.CollectDuration("backup checksum", time.Since(startAll))
return metaWriter.FinishWriteMetas(ctx, op)
}
// Len returns the number of schemas.
func (ss *Schemas) Len() int {
return ss.size
}
func (s *schemaInfo) calculateChecksum(
ctx context.Context,
client kv.Client,
backupTS uint64,
concurrency uint,
) error {
exe, err := checksum.NewExecutorBuilder(s.tableInfo, backupTS).
SetConcurrency(concurrency).
Build()
if err != nil {
return errors.Trace(err)
}
checksumResp, err := exe.Execute(ctx, client, func() {
// TODO: update progress here.
})
if err != nil {
return errors.Trace(err)
}
s.crc64xor = checksumResp.Checksum
s.totalKvs = checksumResp.TotalKvs
s.totalBytes = checksumResp.TotalBytes
return nil
}
func (s *schemaInfo) dumpStatsToJSON(statsHandle *handle.Handle) error {
jsonTable, err := statsHandle.DumpStatsToJSON(
s.dbInfo.Name.String(), s.tableInfo, nil, true)
if err != nil {
return errors.Trace(err)
}
s.stats = jsonTable
return nil
}
func (s *schemaInfo) encodeToSchema() (*backuppb.Schema, error) {
dbBytes, err := json.Marshal(s.dbInfo)
if err != nil {
return nil, errors.Trace(err)
}
var tableBytes []byte
if s.tableInfo != nil {
tableBytes, err = json.Marshal(s.tableInfo)
if err != nil {
return nil, errors.Trace(err)
}
}
var statsBytes []byte
if s.stats != nil {
statsBytes, err = json.Marshal(s.stats)
if err != nil {
return nil, errors.Trace(err)
}
}
return &backuppb.Schema{
Db: dbBytes,
Table: tableBytes,
Crc64Xor: s.crc64xor,
TotalKvs: s.totalKvs,
TotalBytes: s.totalBytes,
Stats: statsBytes,
}, nil
}