forked from pingcap/br
-
Notifications
You must be signed in to change notification settings - Fork 0
/
restore.go
439 lines (385 loc) · 12.7 KB
/
restore.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
// Copyright 2020 PingCAP, Inc. Licensed under Apache-2.0.
package task
import (
"context"
"time"
"github.com/pingcap/errors"
"github.com/pingcap/failpoint"
"github.com/pingcap/kvproto/pkg/backup"
"github.com/pingcap/log"
"github.com/pingcap/tidb/config"
"github.com/spf13/pflag"
"go.uber.org/multierr"
"go.uber.org/zap"
"github.com/pingcap/br/pkg/conn"
berrors "github.com/pingcap/br/pkg/errors"
"github.com/pingcap/br/pkg/glue"
"github.com/pingcap/br/pkg/pdutil"
"github.com/pingcap/br/pkg/restore"
"github.com/pingcap/br/pkg/storage"
"github.com/pingcap/br/pkg/summary"
"github.com/pingcap/br/pkg/utils"
)
const (
flagOnline = "online"
flagNoSchema = "no-schema"
defaultRestoreConcurrency = 128
maxRestoreBatchSizeLimit = 10240
defaultDDLConcurrency = 16
)
// RestoreConfig is the configuration specific for restore tasks.
type RestoreConfig struct {
Config
Online bool `json:"online" toml:"online"`
NoSchema bool `json:"no-schema" toml:"no-schema"`
}
// DefineRestoreFlags defines common flags for the restore command.
func DefineRestoreFlags(flags *pflag.FlagSet) {
// TODO remove experimental tag if it's stable
flags.Bool(flagOnline, false, "(experimental) Whether online when restore")
flags.Bool(flagNoSchema, false, "skip creating schemas and tables, reuse existing empty ones")
// Do not expose this flag
_ = flags.MarkHidden(flagNoSchema)
}
// ParseFromFlags parses the restore-related flags from the flag set.
func (cfg *RestoreConfig) ParseFromFlags(flags *pflag.FlagSet) error {
var err error
cfg.Online, err = flags.GetBool(flagOnline)
if err != nil {
return errors.Trace(err)
}
cfg.NoSchema, err = flags.GetBool(flagNoSchema)
if err != nil {
return errors.Trace(err)
}
err = cfg.Config.ParseFromFlags(flags)
if err != nil {
return errors.Trace(err)
}
if cfg.Config.Concurrency == 0 {
cfg.Config.Concurrency = defaultRestoreConcurrency
}
return nil
}
// adjustRestoreConfig is use for BR(binary) and BR in TiDB.
// When new config was add and not included in parser.
// we should set proper value in this function.
// so that both binary and TiDB will use same default value.
func (cfg *RestoreConfig) adjustRestoreConfig() {
cfg.adjust()
if cfg.Config.Concurrency == 0 {
cfg.Config.Concurrency = defaultRestoreConcurrency
}
if cfg.Config.SwitchModeInterval == 0 {
cfg.Config.SwitchModeInterval = defaultSwitchInterval
}
}
// RunRestore starts a restore task inside the current goroutine.
func RunRestore(c context.Context, g glue.Glue, cmdName string, cfg *RestoreConfig) error {
cfg.adjustRestoreConfig()
defer summary.Summary(cmdName)
ctx, cancel := context.WithCancel(c)
defer cancel()
mgr, err := NewMgr(ctx, g, cfg.PD, cfg.TLS, GetKeepalive(&cfg.Config), cfg.CheckRequirements)
if err != nil {
return errors.Trace(err)
}
defer mgr.Close()
keepaliveCfg := GetKeepalive(&cfg.Config)
keepaliveCfg.PermitWithoutStream = true
client, err := restore.NewRestoreClient(g, mgr.GetPDClient(), mgr.GetTiKV(), mgr.GetTLSConfig(), keepaliveCfg)
if err != nil {
return errors.Trace(err)
}
defer client.Close()
u, err := storage.ParseBackend(cfg.Storage, &cfg.BackendOptions)
if err != nil {
return errors.Trace(err)
}
if err = client.SetStorage(ctx, u, cfg.SendCreds); err != nil {
return errors.Trace(err)
}
client.SetRateLimit(cfg.RateLimit)
client.SetConcurrency(uint(cfg.Concurrency))
if cfg.Online {
client.EnableOnline()
}
if cfg.NoSchema {
client.EnableSkipCreateSQL()
}
client.SetSwitchModeInterval(cfg.SwitchModeInterval)
err = client.LoadRestoreStores(ctx)
if err != nil {
return errors.Trace(err)
}
u, _, backupMeta, err := ReadBackupMeta(ctx, utils.MetaFile, &cfg.Config)
if err != nil {
return errors.Trace(err)
}
g.Record("Size", utils.ArchiveSize(backupMeta))
if err = client.InitBackupMeta(backupMeta, u); err != nil {
return errors.Trace(err)
}
if client.IsRawKvMode() {
return errors.Annotate(berrors.ErrRestoreModeMismatch, "cannot do transactional restore from raw kv data")
}
files, tables, dbs := filterRestoreFiles(client, cfg)
if len(dbs) == 0 && len(tables) != 0 {
return errors.Annotate(berrors.ErrRestoreInvalidBackup, "contain tables but no databases")
}
restoreTS, err := client.GetTS(ctx)
if err != nil {
return errors.Trace(err)
}
sp := utils.BRServiceSafePoint{
BackupTS: restoreTS,
TTL: utils.DefaultBRGCSafePointTTL,
ID: utils.MakeSafePointID(),
}
// restore checksum will check safe point with its start ts, see details at
// https://github.com/pingcap/tidb/blob/180c02127105bed73712050594da6ead4d70a85f/store/tikv/kv.go#L186-L190
// so, we should keep the safe point unchangeable. to avoid GC life time is shorter than transaction duration.
utils.StartServiceSafePointKeeper(ctx, mgr.GetPDClient(), sp)
var newTS uint64
if client.IsIncremental() {
newTS = restoreTS
}
ddlJobs := restore.FilterDDLJobs(client.GetDDLJobs(), tables)
// pre-set TiDB config for restore
restoreDBConfig := enableTiDBConfig()
defer restoreDBConfig()
// execute DDL first
err = client.ExecDDLs(ctx, ddlJobs)
if err != nil {
return errors.Trace(err)
}
// nothing to restore, maybe only ddl changes in incremental restore
if len(dbs) == 0 && len(tables) == 0 {
log.Info("nothing to restore, all databases and tables are filtered out")
// even nothing to restore, we show a success message since there is no failure.
summary.SetSuccessStatus(true)
return nil
}
for _, db := range dbs {
err = client.CreateDatabase(ctx, db.Info)
if err != nil {
return errors.Trace(err)
}
}
// We make bigger errCh so we won't block on multi-part failed.
errCh := make(chan error, 32)
// Maybe allow user modify the DDL concurrency isn't necessary,
// because executing DDL is really I/O bound (or, algorithm bound?),
// and we cost most of time at waiting DDL jobs be enqueued.
// So these jobs won't be faster or slower when machine become faster or slower,
// hence make it a fixed value would be fine.
var dbPool []*restore.DB
if g.OwnsStorage() {
// Only in binary we can use multi-thread sessions to create tables.
// so use OwnStorage() to tell whether we are use binary or SQL.
dbPool, err = restore.MakeDBPool(defaultDDLConcurrency, func() (*restore.DB, error) {
return restore.NewDB(g, mgr.GetTiKV())
})
}
if err != nil {
log.Warn("create session pool failed, we will send DDLs only by created sessions",
zap.Error(err),
zap.Int("sessionCount", len(dbPool)),
)
}
tableStream := client.GoCreateTables(ctx, mgr.GetDomain(), tables, newTS, dbPool, errCh)
if len(files) == 0 {
log.Info("no files, empty databases and tables are restored")
summary.SetSuccessStatus(true)
// don't return immediately, wait all pipeline done.
}
tableFileMap := restore.MapTableToFiles(files)
log.Debug("mapped table to files", zap.Any("result map", tableFileMap))
rangeStream := restore.GoValidateFileRanges(ctx, tableStream, tableFileMap, errCh)
rangeSize := restore.EstimateRangeSize(files)
summary.CollectInt("restore ranges", rangeSize)
log.Info("range and file prepared", zap.Int("file count", len(files)), zap.Int("range count", rangeSize))
restoreSchedulers, err := restorePreWork(ctx, client, mgr)
if err != nil {
return errors.Trace(err)
}
// Always run the post-work even on error, so we don't stuck in the import
// mode or emptied schedulers
defer restorePostWork(ctx, client, restoreSchedulers)
// Do not reset timestamp if we are doing incremental restore, because
// we are not allowed to decrease timestamp.
if !client.IsIncremental() {
if err = client.ResetTS(ctx, cfg.PD); err != nil {
log.Error("reset pd TS failed", zap.Error(err))
return errors.Trace(err)
}
}
// Restore sst files in batch.
batchSize := utils.ClampInt(int(cfg.Concurrency), defaultRestoreConcurrency, maxRestoreBatchSizeLimit)
failpoint.Inject("small-batch-size", func(v failpoint.Value) {
log.Info("failpoint small batch size is on", zap.Int("size", v.(int)))
batchSize = v.(int)
})
// Redirect to log if there is no log file to avoid unreadable output.
updateCh := g.StartProgress(
ctx,
cmdName,
// Split/Scatter + Download/Ingest + Checksum
int64(rangeSize+len(files)+len(tables)),
!cfg.LogProgress)
defer updateCh.Close()
sender, err := restore.NewTiKVSender(ctx, client, updateCh)
if err != nil {
return errors.Trace(err)
}
manager := restore.NewBRContextManager(client)
batcher, afterRestoreStream := restore.NewBatcher(ctx, sender, manager, errCh)
batcher.SetThreshold(batchSize)
batcher.EnableAutoCommit(ctx, time.Second)
go restoreTableStream(ctx, rangeStream, batcher, errCh)
var finish <-chan struct{}
// Checksum
if cfg.Checksum {
finish = client.GoValidateChecksum(
ctx, afterRestoreStream, mgr.GetTiKV().GetClient(), errCh, updateCh, cfg.ChecksumConcurrency)
} else {
// when user skip checksum, just collect tables, and drop them.
finish = dropToBlackhole(ctx, afterRestoreStream, errCh, updateCh)
}
select {
case err = <-errCh:
err = multierr.Append(err, multierr.Combine(restore.Exhaust(errCh)...))
case <-finish:
}
// If any error happened, return now.
if err != nil {
return errors.Trace(err)
}
// Set task summary to success status.
summary.SetSuccessStatus(true)
return nil
}
// dropToBlackhole drop all incoming tables into black hole,
// i.e. don't execute checksum, just increase the process anyhow.
func dropToBlackhole(
ctx context.Context,
tableStream <-chan restore.CreatedTable,
errCh chan<- error,
updateCh glue.Progress,
) <-chan struct{} {
outCh := make(chan struct{}, 1)
go func() {
defer func() {
outCh <- struct{}{}
}()
for {
select {
case <-ctx.Done():
errCh <- ctx.Err()
return
case _, ok := <-tableStream:
if !ok {
return
}
updateCh.Inc()
}
}
}()
return outCh
}
func filterRestoreFiles(
client *restore.Client,
cfg *RestoreConfig,
) (files []*backup.File, tables []*utils.Table, dbs []*utils.Database) {
for _, db := range client.GetDatabases() {
createdDatabase := false
for _, table := range db.Tables {
if !cfg.TableFilter.MatchTable(db.Info.Name.O, table.Info.Name.O) {
continue
}
if !createdDatabase {
dbs = append(dbs, db)
createdDatabase = true
}
files = append(files, table.Files...)
tables = append(tables, table)
}
}
return
}
// restorePreWork executes some prepare work before restore.
// TODO make this function returns a restore post work.
func restorePreWork(ctx context.Context, client *restore.Client, mgr *conn.Mgr) (pdutil.UndoFunc, error) {
if client.IsOnline() {
return pdutil.Nop, nil
}
// Switch TiKV cluster to import mode (adjust rocksdb configuration).
client.SwitchToImportMode(ctx)
return mgr.RemoveSchedulers(ctx)
}
// restorePostWork executes some post work after restore.
// TODO: aggregate all lifetime manage methods into batcher's context manager field.
func restorePostWork(
ctx context.Context, client *restore.Client, restoreSchedulers pdutil.UndoFunc,
) {
if ctx.Err() != nil {
log.Warn("context canceled, try shutdown")
ctx = context.Background()
}
if client.IsOnline() {
return
}
if err := client.SwitchToNormalMode(ctx); err != nil {
log.Warn("fail to switch to normal mode", zap.Error(err))
}
if err := restoreSchedulers(ctx); err != nil {
log.Warn("failed to restore PD schedulers", zap.Error(err))
}
}
// enableTiDBConfig tweaks some of configs of TiDB to make the restore progress go well.
// return a function that could restore the config to origin.
func enableTiDBConfig() func() {
restoreConfig := config.RestoreFunc()
config.UpdateGlobal(func(conf *config.Config) {
// set max-index-length before execute DDLs and create tables
// we set this value to max(3072*4), otherwise we might not restore table
// when upstream and downstream both set this value greater than default(3072)
conf.MaxIndexLength = config.DefMaxOfMaxIndexLength
log.Warn("set max-index-length to max(3072*4) to skip check index length in DDL")
// we need set this to true, since all create table DDLs will create with tableInfo
// and we can handle alter drop pk/add pk DDLs with no impact
conf.AlterPrimaryKey = true
})
return restoreConfig
}
// restoreTableStream blocks current goroutine and restore a stream of tables,
// by send tables to batcher.
func restoreTableStream(
ctx context.Context,
inputCh <-chan restore.TableWithRange,
batcher *restore.Batcher,
errCh chan<- error,
) {
// We cache old tables so that we can 'batch' recover TiFlash and tables.
oldTables := []*utils.Table{}
defer func() {
// when things done, we must clean pending requests.
batcher.Close()
log.Info("doing postwork",
zap.Int("table count", len(oldTables)),
)
}()
for {
select {
case <-ctx.Done():
errCh <- ctx.Err()
return
case t, ok := <-inputCh:
if !ok {
return
}
oldTables = append(oldTables, t.OldTable)
batcher.Add(t)
}
}
}