This repository has been archived by the owner on Dec 8, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 66
/
restore.go
1746 lines (1512 loc) · 49.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
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
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2019 PingCAP, Inc.
//
// 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,
// See the License for the specific language governing permissions and
// limitations under the License.
package restore
import (
"context"
"database/sql"
"fmt"
"io"
"net/http"
"os"
"path"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/coreos/go-semver/semver"
"github.com/pingcap/errors"
"github.com/pingcap/failpoint"
sstpb "github.com/pingcap/kvproto/pkg/import_sstpb"
"github.com/pingcap/parser/model"
tidbcfg "github.com/pingcap/tidb/config"
"github.com/pingcap/tidb/meta/autoid"
"github.com/pingcap/tidb/table"
"github.com/pingcap/tidb/table/tables"
"go.uber.org/zap"
"modernc.org/mathutil"
. "github.com/pingcap/tidb-lightning/lightning/checkpoints"
"github.com/pingcap/tidb-lightning/lightning/common"
"github.com/pingcap/tidb-lightning/lightning/config"
kv "github.com/pingcap/tidb-lightning/lightning/backend"
"github.com/pingcap/tidb-lightning/lightning/log"
"github.com/pingcap/tidb-lightning/lightning/metric"
"github.com/pingcap/tidb-lightning/lightning/mydump"
verify "github.com/pingcap/tidb-lightning/lightning/verification"
"github.com/pingcap/tidb-lightning/lightning/web"
"github.com/pingcap/tidb-lightning/lightning/worker"
)
const (
FullLevelCompact = -1
Level1Compact = 1
)
const (
defaultGCLifeTime = 100 * time.Hour
)
const (
indexEngineID = -1
)
const (
compactStateIdle int32 = iota
compactStateDoing
)
var (
requiredTiDBVersion = *semver.New("2.1.0")
requiredPDVersion = *semver.New("2.1.0")
requiredTiKVVersion = *semver.New("2.1.0")
)
// DeliverPauser is a shared pauser to pause progress to (*chunkRestore).encodeLoop
var DeliverPauser = common.NewPauser()
func init() {
cfg := tidbcfg.GetGlobalConfig()
cfg.Log.SlowThreshold = 3000
}
type saveCp struct {
tableName string
merger TableCheckpointMerger
}
type errorSummary struct {
status CheckpointStatus
err error
}
type errorSummaries struct {
sync.Mutex
logger log.Logger
summary map[string]errorSummary
}
// makeErrorSummaries returns an initialized errorSummaries instance
func makeErrorSummaries(logger log.Logger) errorSummaries {
return errorSummaries{
logger: logger,
summary: make(map[string]errorSummary),
}
}
func (es *errorSummaries) emitLog() {
es.Lock()
defer es.Unlock()
if errorCount := len(es.summary); errorCount > 0 {
logger := es.logger
logger.Error("tables failed to be imported", zap.Int("count", errorCount))
for tableName, errorSummary := range es.summary {
logger.Error("-",
zap.String("table", tableName),
zap.String("status", errorSummary.status.MetricName()),
log.ShortError(errorSummary.err),
)
}
}
}
func (es *errorSummaries) record(tableName string, err error, status CheckpointStatus) {
es.Lock()
defer es.Unlock()
es.summary[tableName] = errorSummary{status: status, err: err}
}
type RestoreController struct {
cfg *config.Config
dbMetas []*mydump.MDDatabaseMeta
dbInfos map[string]*TidbDBInfo
tableWorkers *worker.Pool
indexWorkers *worker.Pool
regionWorkers *worker.Pool
ioWorkers *worker.Pool
backend kv.Backend
tidbMgr *TiDBManager
postProcessLock sync.Mutex // a simple way to ensure post-processing is not concurrent without using complicated goroutines
alterTableLock sync.Mutex
compactState int32
errorSummaries errorSummaries
checkpointsDB CheckpointsDB
saveCpCh chan saveCp
checkpointsWg sync.WaitGroup
closedEngineLimit *worker.Pool
}
func NewRestoreController(ctx context.Context, dbMetas []*mydump.MDDatabaseMeta, cfg *config.Config) (*RestoreController, error) {
cpdb, err := OpenCheckpointsDB(ctx, cfg)
if err != nil {
return nil, errors.Trace(err)
}
tidbMgr, err := NewTiDBManager(cfg.TiDB)
if err != nil {
return nil, errors.Trace(err)
}
var backend kv.Backend
switch cfg.TikvImporter.Backend {
case config.BackendImporter:
var err error
backend, err = kv.NewImporter(ctx, cfg.TikvImporter.Addr, cfg.TiDB.PdAddr)
if err != nil {
return nil, err
}
case config.BackendMySQL:
backend = kv.NewMySQLBackend(tidbMgr.db)
default:
return nil, errors.New("unknown backend: " + cfg.TikvImporter.Backend)
}
rc := &RestoreController{
cfg: cfg,
dbMetas: dbMetas,
tableWorkers: worker.NewPool(ctx, cfg.App.TableConcurrency, "table"),
indexWorkers: worker.NewPool(ctx, cfg.App.IndexConcurrency, "index"),
regionWorkers: worker.NewPool(ctx, cfg.App.RegionConcurrency, "region"),
ioWorkers: worker.NewPool(ctx, cfg.App.IOConcurrency, "io"),
backend: backend,
tidbMgr: tidbMgr,
errorSummaries: makeErrorSummaries(log.L()),
checkpointsDB: cpdb,
saveCpCh: make(chan saveCp),
closedEngineLimit: worker.NewPool(ctx, cfg.App.TableConcurrency*2, "closed-engine"),
}
return rc, nil
}
func OpenCheckpointsDB(ctx context.Context, cfg *config.Config) (CheckpointsDB, error) {
if !cfg.Checkpoint.Enable {
return NewNullCheckpointsDB(), nil
}
switch cfg.Checkpoint.Driver {
case config.CheckpointDriverMySQL:
db, err := sql.Open("mysql", cfg.Checkpoint.DSN)
if err != nil {
return nil, errors.Trace(err)
}
cpdb, err := NewMySQLCheckpointsDB(ctx, db, cfg.Checkpoint.Schema, cfg.TaskID)
if err != nil {
db.Close()
return nil, errors.Trace(err)
}
return cpdb, nil
case config.CheckpointDriverFile:
return NewFileCheckpointsDB(cfg.Checkpoint.DSN), nil
default:
return nil, errors.Errorf("Unknown checkpoint driver %s", cfg.Checkpoint.Driver)
}
}
func (rc *RestoreController) Wait() {
close(rc.saveCpCh)
rc.checkpointsWg.Wait()
}
func (rc *RestoreController) Close() {
rc.backend.Close()
rc.tidbMgr.Close()
}
func (rc *RestoreController) Run(ctx context.Context) error {
opts := []func(context.Context) error{
rc.checkRequirements,
rc.restoreSchema,
rc.restoreTables,
rc.fullCompact,
rc.switchToNormalMode,
rc.cleanCheckpoints,
}
task := log.L().Begin(zap.InfoLevel, "the whole procedure")
var err error
outside:
for i, process := range opts {
err = process(ctx)
logger := task.With(zap.Int("step", i), log.ShortError(err))
switch {
case err == nil:
case log.IsContextCanceledError(err):
logger.Info("user terminated")
err = nil
break outside
default:
logger.Error("run failed")
fmt.Fprintf(os.Stderr, "Error: %s\n", err)
break outside // ps : not continue
}
}
task.End(zap.ErrorLevel, err)
rc.errorSummaries.emitLog()
return errors.Trace(err)
}
func (rc *RestoreController) restoreSchema(ctx context.Context) error {
tidbMgr, err := NewTiDBManager(rc.cfg.TiDB)
if err != nil {
return errors.Trace(err)
}
defer tidbMgr.Close()
if !rc.cfg.Mydumper.NoSchema {
tidbMgr.db.ExecContext(ctx, "SET SQL_MODE = ?", rc.cfg.TiDB.StrSQLMode)
for _, dbMeta := range rc.dbMetas {
task := log.With(zap.String("db", dbMeta.Name)).Begin(zap.InfoLevel, "restore table schema")
tablesSchema := make(map[string]string)
for _, tblMeta := range dbMeta.Tables {
tablesSchema[tblMeta.Name] = tblMeta.GetSchema()
}
err = tidbMgr.InitSchema(ctx, dbMeta.Name, tablesSchema)
task.End(zap.ErrorLevel, err)
if err != nil {
return errors.Annotatef(err, "restore table schema %s failed", dbMeta.Name)
}
}
}
dbInfos, err := tidbMgr.LoadSchemaInfo(ctx, rc.dbMetas)
if err != nil {
return errors.Trace(err)
}
rc.dbInfos = dbInfos
// Load new checkpoints
err = rc.checkpointsDB.Initialize(ctx, dbInfos)
if err != nil {
return errors.Trace(err)
}
go rc.listenCheckpointUpdates()
// Estimate the number of chunks for progress reporting
rc.estimateChunkCountIntoMetrics()
return nil
}
func (rc *RestoreController) estimateChunkCountIntoMetrics() {
estimatedChunkCount := 0
for _, dbMeta := range rc.dbMetas {
for _, tableMeta := range dbMeta.Tables {
estimatedChunkCount += len(tableMeta.DataFiles)
}
}
metric.ChunkCounter.WithLabelValues(metric.ChunkStateEstimated).Add(float64(estimatedChunkCount))
}
func (rc *RestoreController) saveStatusCheckpoint(tableName string, engineID int32, err error, statusIfSucceed CheckpointStatus) {
merger := &StatusCheckpointMerger{Status: statusIfSucceed, EngineID: engineID}
switch {
case err == nil:
break
case !common.IsContextCanceledError(err):
merger.SetInvalid()
rc.errorSummaries.record(tableName, err, statusIfSucceed)
default:
return
}
if engineID == WholeTableEngineID {
metric.RecordTableCount(statusIfSucceed.MetricName(), err)
} else {
metric.RecordEngineCount(statusIfSucceed.MetricName(), err)
}
rc.saveCpCh <- saveCp{tableName: tableName, merger: merger}
}
// listenCheckpointUpdates will combine several checkpoints together to reduce database load.
func (rc *RestoreController) listenCheckpointUpdates() {
rc.checkpointsWg.Add(1)
var lock sync.Mutex
coalesed := make(map[string]*TableCheckpointDiff)
hasCheckpoint := make(chan struct{}, 1)
defer close(hasCheckpoint)
go func() {
for range hasCheckpoint {
lock.Lock()
cpd := coalesed
coalesed = make(map[string]*TableCheckpointDiff)
lock.Unlock()
if len(cpd) > 0 {
rc.checkpointsDB.Update(cpd)
web.BroadcastCheckpointDiff(cpd)
}
rc.checkpointsWg.Done()
}
}()
for scp := range rc.saveCpCh {
lock.Lock()
cpd, ok := coalesed[scp.tableName]
if !ok {
cpd = NewTableCheckpointDiff()
coalesed[scp.tableName] = cpd
}
scp.merger.MergeInto(cpd)
if len(hasCheckpoint) == 0 {
rc.checkpointsWg.Add(1)
hasCheckpoint <- struct{}{}
}
lock.Unlock()
failpoint.Inject("FailIfImportedChunk", func(val failpoint.Value) {
if merger, ok := scp.merger.(*ChunkCheckpointMerger); ok && merger.Checksum.SumKVS() >= uint64(val.(int)) {
rc.checkpointsWg.Done()
rc.checkpointsWg.Wait()
panic("forcing failure due to FailIfImportedChunk")
}
})
failpoint.Inject("FailIfStatusBecomes", func(val failpoint.Value) {
if merger, ok := scp.merger.(*StatusCheckpointMerger); ok && merger.EngineID >= 0 && int(merger.Status) == val.(int) {
rc.checkpointsWg.Done()
rc.checkpointsWg.Wait()
panic("forcing failure due to FailIfStatusBecomes")
}
})
failpoint.Inject("FailIfIndexEngineImported", func(val failpoint.Value) {
if merger, ok := scp.merger.(*StatusCheckpointMerger); ok &&
merger.EngineID == WholeTableEngineID &&
merger.Status == CheckpointStatusIndexImported && val.(int) > 0 {
rc.checkpointsWg.Done()
rc.checkpointsWg.Wait()
panic("forcing failure due to FailIfIndexEngineImported")
}
})
failpoint.Inject("KillIfImportedChunk", func(val failpoint.Value) {
if merger, ok := scp.merger.(*ChunkCheckpointMerger); ok && merger.Checksum.SumKVS() >= uint64(val.(int)) {
common.KillMySelf()
}
})
}
rc.checkpointsWg.Done()
}
func (rc *RestoreController) runPeriodicActions(ctx context.Context, stop <-chan struct{}) {
switchModeTicker := time.NewTicker(rc.cfg.Cron.SwitchMode.Duration)
logProgressTicker := time.NewTicker(rc.cfg.Cron.LogProgress.Duration)
defer func() {
switchModeTicker.Stop()
logProgressTicker.Stop()
}()
rc.switchToImportMode(ctx)
start := time.Now()
for {
select {
case <-ctx.Done():
log.L().Warn("stopping periodic actions", log.ShortError(ctx.Err()))
return
case <-stop:
log.L().Info("everything imported, stopping periodic actions")
return
case <-switchModeTicker.C:
// periodically switch to import mode, as requested by TiKV 3.0
rc.switchToImportMode(ctx)
case <-logProgressTicker.C:
// log the current progress periodically, so OPS will know that we're still working
nanoseconds := float64(time.Since(start).Nanoseconds())
estimated := metric.ReadCounter(metric.ChunkCounter.WithLabelValues(metric.ChunkStateEstimated))
finished := metric.ReadCounter(metric.ChunkCounter.WithLabelValues(metric.ChunkStateFinished))
totalTables := metric.ReadCounter(metric.TableCounter.WithLabelValues(metric.TableStatePending, metric.TableResultSuccess))
completedTables := metric.ReadCounter(metric.TableCounter.WithLabelValues(metric.TableStateCompleted, metric.TableResultSuccess))
bytesRead := metric.ReadHistogramSum(metric.RowReadBytesHistogram)
var state string
var remaining zap.Field
if finished >= estimated {
state = "post-processing"
remaining = zap.Skip()
} else if finished > 0 {
remainNanoseconds := (estimated/finished - 1) * nanoseconds
state = "writing"
remaining = zap.Duration("remaining", time.Duration(remainNanoseconds).Round(time.Second))
} else {
state = "writing"
remaining = zap.Skip()
}
// Note: a speed of 28 MiB/s roughly corresponds to 100 GiB/hour.
log.L().Info("progress",
zap.String("files", fmt.Sprintf("%.0f/%.0f (%.1f%%)", finished, estimated, finished/estimated*100)),
zap.String("tables", fmt.Sprintf("%.0f/%.0f (%.1f%%)", completedTables, totalTables, completedTables/totalTables*100)),
zap.Float64("speed(MiB/s)", bytesRead/(1048576e-9*nanoseconds)),
zap.String("state", state),
remaining,
)
}
}
}
type gcLifeTimeManager struct {
runningJobsLock sync.Mutex
runningJobs int
oriGCLifeTime string
}
func newGCLifeTimeManager() *gcLifeTimeManager {
// Default values of three member are enough to initialize this struct
return &gcLifeTimeManager{}
}
// Pre- and post-condition:
// if m.runningJobs == 0, GC life time has not been increased.
// if m.runningJobs > 0, GC life time has been increased.
// m.runningJobs won't be negative(overflow) since index concurrency is relatively small
func (m *gcLifeTimeManager) addOneJob(ctx context.Context, db *sql.DB) error {
m.runningJobsLock.Lock()
defer m.runningJobsLock.Unlock()
if m.runningJobs == 0 {
oriGCLifeTime, err := ObtainGCLifeTime(ctx, db)
if err != nil {
return err
}
m.oriGCLifeTime = oriGCLifeTime
err = increaseGCLifeTime(ctx, db)
if err != nil {
return err
}
}
m.runningJobs += 1
return nil
}
// Pre- and post-condition:
// if m.runningJobs == 0, GC life time has been tried to recovered. If this try fails, a warning will be printed.
// if m.runningJobs > 0, GC life time has not been recovered.
// m.runningJobs won't minus to negative since removeOneJob follows a successful addOneJob.
func (m *gcLifeTimeManager) removeOneJob(ctx context.Context, db *sql.DB) {
m.runningJobsLock.Lock()
defer m.runningJobsLock.Unlock()
m.runningJobs -= 1
if m.runningJobs == 0 {
err := UpdateGCLifeTime(ctx, db, m.oriGCLifeTime)
if err != nil {
query := fmt.Sprintf(
"UPDATE mysql.tidb SET VARIABLE_VALUE = '%s' WHERE VARIABLE_NAME = 'tikv_gc_life_time'",
m.oriGCLifeTime,
)
log.L().Warn("revert GC lifetime failed, please reset the GC lifetime manually after Lightning completed",
zap.String("query", query),
log.ShortError(err),
)
}
}
}
var gcLifeTimeKey struct{}
func (rc *RestoreController) restoreTables(ctx context.Context) error {
logTask := log.L().Begin(zap.InfoLevel, "restore all tables data")
var wg sync.WaitGroup
var restoreErr common.OnceError
stopPeriodicActions := make(chan struct{}, 1)
go rc.runPeriodicActions(ctx, stopPeriodicActions)
type task struct {
tr *TableRestore
cp *TableCheckpoint
}
taskCh := make(chan task, rc.cfg.App.IndexConcurrency)
defer close(taskCh)
manager := newGCLifeTimeManager()
ctx2 := context.WithValue(ctx, &gcLifeTimeKey, manager)
for i := 0; i < rc.cfg.App.IndexConcurrency; i++ {
go func() {
for task := range taskCh {
tableLogTask := task.tr.logger.Begin(zap.InfoLevel, "restore table")
web.BroadcastTableCheckpoint(task.tr.tableName, task.cp)
err := task.tr.restoreTable(ctx2, rc, task.cp)
tableLogTask.End(zap.ErrorLevel, err)
web.BroadcastError(task.tr.tableName, err)
metric.RecordTableCount("completed", err)
restoreErr.Set(err)
wg.Done()
}
}()
}
for _, dbMeta := range rc.dbMetas {
dbInfo, ok := rc.dbInfos[dbMeta.Name]
if !ok {
return errors.Errorf("database %s not found in rc.dbInfos", dbMeta.Name)
}
for _, tableMeta := range dbMeta.Tables {
tableInfo, ok := dbInfo.Tables[tableMeta.Name]
if !ok {
return errors.Errorf("table info %s.%s not found", dbMeta.Name, tableMeta.Name)
}
tableName := common.UniqueTable(dbInfo.Name, tableInfo.Name)
cp, err := rc.checkpointsDB.Get(ctx, tableName)
if cp.Status <= CheckpointStatusMaxInvalid {
return errors.Errorf("Checkpoint for %s has invalid status: %d", tableName, cp.Status)
}
if err != nil {
return errors.Trace(err)
}
tr, err := NewTableRestore(tableName, tableMeta, dbInfo, tableInfo, cp)
if err != nil {
return errors.Trace(err)
}
wg.Add(1)
select {
case taskCh <- task{tr: tr, cp: cp}:
case <-ctx.Done():
return ctx.Err()
}
}
}
wg.Wait()
stopPeriodicActions <- struct{}{}
err := restoreErr.Get()
logTask.End(zap.ErrorLevel, err)
return err
}
func (t *TableRestore) restoreTable(
ctx context.Context,
rc *RestoreController,
cp *TableCheckpoint,
) error {
// 1. Load the table info.
select {
case <-ctx.Done():
return ctx.Err()
default:
}
// no need to do anything if the chunks are already populated
if len(cp.Engines) > 0 {
t.logger.Info("reusing engines and files info from checkpoint",
zap.Int("enginesCnt", len(cp.Engines)),
zap.Int("filesCnt", cp.CountChunks()),
)
} else if cp.Status < CheckpointStatusAllWritten {
if err := t.populateChunks(rc.cfg, cp); err != nil {
return errors.Trace(err)
}
if err := rc.checkpointsDB.InsertEngineCheckpoints(ctx, t.tableName, cp.Engines); err != nil {
return errors.Trace(err)
}
web.BroadcastTableCheckpoint(t.tableName, cp)
// rebase the allocator so it exceeds the number of rows.
cp.AllocBase = mathutil.MaxInt64(cp.AllocBase, t.tableInfo.Core.AutoIncID)
for _, engine := range cp.Engines {
for _, chunk := range engine.Chunks {
cp.AllocBase = mathutil.MaxInt64(cp.AllocBase, chunk.Chunk.RowIDMax)
}
}
t.alloc.Rebase(t.tableInfo.ID, cp.AllocBase, false)
rc.saveCpCh <- saveCp{
tableName: t.tableName,
merger: &RebaseCheckpointMerger{
AllocBase: cp.AllocBase,
},
}
}
// 2. Restore engines (if still needed)
err := t.restoreEngines(ctx, rc, cp)
if err != nil {
return errors.Trace(err)
}
// 3. Post-process
return errors.Trace(t.postProcess(ctx, rc, cp))
}
func (t *TableRestore) restoreEngines(ctx context.Context, rc *RestoreController, cp *TableCheckpoint) error {
indexEngineCp := cp.Engines[indexEngineID]
if indexEngineCp == nil {
return errors.Errorf("table %v index engine checkpoint not found", t.tableName)
}
// The table checkpoint status set to `CheckpointStatusIndexImported` only if
// both all data engines and the index engine had been imported to TiKV.
// But persist index engine checkpoint status and table checkpoint status are
// not an atomic operation, so `cp.Status < CheckpointStatusIndexImported`
// but `indexEngineCp.Status == CheckpointStatusImported` could happen
// when kill lightning after saving index engine checkpoint status before saving
// table checkpoint status.
var closedIndexEngine *kv.ClosedEngine
if indexEngineCp.Status < CheckpointStatusImported && cp.Status < CheckpointStatusIndexImported {
indexWorker := rc.indexWorkers.Apply()
defer rc.indexWorkers.Recycle(indexWorker)
indexEngine, err := rc.backend.OpenEngine(ctx, t.tableName, indexEngineID)
if err != nil {
return errors.Trace(err)
}
// The table checkpoint status less than `CheckpointStatusIndexImported` implies
// that index engine checkpoint status less than `CheckpointStatusImported`.
// So the index engine must be found in above process
if indexEngine == nil {
return errors.Errorf("table checkpoint status %v incompitable with index engine checkpoint status %v",
cp.Status, indexEngineCp.Status)
}
logTask := t.logger.Begin(zap.InfoLevel, "import whole table")
var wg sync.WaitGroup
var engineErr common.OnceError
for engineID, engine := range cp.Engines {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
if engineErr.Get() != nil {
break
}
// Should skip index engine
if engineID < 0 {
continue
}
wg.Add(1)
// Note: We still need tableWorkers to control the concurrency of tables.
// In the future, we will investigate more about
// the difference between restoring tables concurrently and restoring tables one by one.
restoreWorker := rc.tableWorkers.Apply()
go func(w *worker.Worker, eid int32, ecp *EngineCheckpoint) {
defer wg.Done()
engineLogTask := t.logger.With(zap.Int32("engineNumber", eid)).Begin(zap.InfoLevel, "restore engine")
dataClosedEngine, dataWorker, err := t.restoreEngine(ctx, rc, indexEngine, eid, ecp)
engineLogTask.End(zap.ErrorLevel, err)
rc.tableWorkers.Recycle(w)
if err != nil {
engineErr.Set(err)
return
}
defer rc.closedEngineLimit.Recycle(dataWorker)
if err := t.importEngine(ctx, dataClosedEngine, rc, eid, ecp); err != nil {
engineErr.Set(err)
}
}(restoreWorker, engineID, engine)
}
wg.Wait()
err = engineErr.Get()
logTask.End(zap.ErrorLevel, err)
if err != nil {
return errors.Trace(err)
}
// If index engine file has been closed but not imported only if context cancel occurred
// when `importKV()` execution, so `UnsafeCloseEngine` and continue import it.
if indexEngineCp.Status == CheckpointStatusClosed {
closedIndexEngine, err = rc.backend.UnsafeCloseEngine(ctx, t.tableName, indexEngineID)
} else {
closedIndexEngine, err = indexEngine.Close(ctx)
rc.saveStatusCheckpoint(t.tableName, indexEngineID, err, CheckpointStatusClosed)
}
if err != nil {
return errors.Trace(err)
}
}
if cp.Status < CheckpointStatusIndexImported {
var err error
if indexEngineCp.Status < CheckpointStatusImported {
// the lock ensures the import() step will not be concurrent.
rc.postProcessLock.Lock()
err = t.importKV(ctx, closedIndexEngine)
rc.postProcessLock.Unlock()
rc.saveStatusCheckpoint(t.tableName, indexEngineID, err, CheckpointStatusImported)
}
failpoint.Inject("FailBeforeIndexEngineImported", func() {
panic("forcing failure due to FailBeforeIndexEngineImported")
})
rc.saveStatusCheckpoint(t.tableName, WholeTableEngineID, err, CheckpointStatusIndexImported)
if err != nil {
return errors.Trace(err)
}
}
return nil
}
func (t *TableRestore) restoreEngine(
ctx context.Context,
rc *RestoreController,
indexEngine *kv.OpenedEngine,
engineID int32,
cp *EngineCheckpoint,
) (*kv.ClosedEngine, *worker.Worker, error) {
if cp.Status >= CheckpointStatusClosed {
w := rc.closedEngineLimit.Apply()
closedEngine, err := rc.backend.UnsafeCloseEngine(ctx, t.tableName, engineID)
// If any error occurred, recycle worker immediately
if err != nil {
rc.closedEngineLimit.Recycle(w)
return closedEngine, nil, errors.Trace(err)
}
return closedEngine, w, nil
}
logTask := t.logger.With(zap.Int32("engineNumber", engineID)).Begin(zap.InfoLevel, "encode kv data and write")
dataEngine, err := rc.backend.OpenEngine(ctx, t.tableName, engineID)
if err != nil {
return nil, nil, errors.Trace(err)
}
var wg sync.WaitGroup
var chunkErr common.OnceError
// Restore table data
for chunkIndex, chunk := range cp.Chunks {
if chunk.Chunk.Offset >= chunk.Chunk.EndOffset {
continue
}
select {
case <-ctx.Done():
return nil, nil, ctx.Err()
default:
}
if chunkErr.Get() != nil {
break
}
// Flows :
// 1. read mydump file
// 2. sql -> kvs
// 3. load kvs data (into kv deliver server)
// 4. flush kvs data (into tikv node)
cr, err := newChunkRestore(chunkIndex, rc.cfg, chunk, rc.ioWorkers)
if err != nil {
return nil, nil, errors.Trace(err)
}
metric.ChunkCounter.WithLabelValues(metric.ChunkStatePending).Inc()
restoreWorker := rc.regionWorkers.Apply()
wg.Add(1)
go func(w *worker.Worker, cr *chunkRestore) {
// Restore a chunk.
defer func() {
cr.close()
wg.Done()
rc.regionWorkers.Recycle(w)
}()
metric.ChunkCounter.WithLabelValues(metric.ChunkStateRunning).Inc()
err := cr.restore(ctx, t, engineID, dataEngine, indexEngine, rc)
if err == nil {
metric.ChunkCounter.WithLabelValues(metric.ChunkStateFinished).Inc()
return
}
metric.ChunkCounter.WithLabelValues(metric.ChunkStateFailed).Inc()
chunkErr.Set(err)
}(restoreWorker, cr)
}
wg.Wait()
// Report some statistics into the log for debugging.
totalKVSize := uint64(0)
totalSQLSize := int64(0)
for _, chunk := range cp.Chunks {
totalKVSize += chunk.Checksum.SumSize()
totalSQLSize += chunk.Chunk.EndOffset
}
err = chunkErr.Get()
logTask.End(zap.ErrorLevel, err,
zap.Int64("read", totalSQLSize),
zap.Uint64("written", totalKVSize),
)
rc.saveStatusCheckpoint(t.tableName, engineID, err, CheckpointStatusAllWritten)
if err != nil {
return nil, nil, errors.Trace(err)
}
dataWorker := rc.closedEngineLimit.Apply()
closedDataEngine, err := dataEngine.Close(ctx)
rc.saveStatusCheckpoint(t.tableName, engineID, err, CheckpointStatusClosed)
if err != nil {
// If any error occurred, recycle worker immediately
rc.closedEngineLimit.Recycle(dataWorker)
return nil, nil, errors.Trace(err)
}
return closedDataEngine, dataWorker, nil
}
func (t *TableRestore) importEngine(
ctx context.Context,
closedEngine *kv.ClosedEngine,
rc *RestoreController,
engineID int32,
cp *EngineCheckpoint,
) error {
if cp.Status >= CheckpointStatusImported {
return nil
}
// 1. close engine, then calling import
// FIXME: flush is an asynchronous operation, what if flush failed?
// the lock ensures the import() step will not be concurrent.
rc.postProcessLock.Lock()
err := t.importKV(ctx, closedEngine)
rc.postProcessLock.Unlock()
rc.saveStatusCheckpoint(t.tableName, engineID, err, CheckpointStatusImported)
if err != nil {
return errors.Trace(err)
}
// 2. perform a level-1 compact if idling.
if rc.cfg.PostRestore.Level1Compact &&
atomic.CompareAndSwapInt32(&rc.compactState, compactStateIdle, compactStateDoing) {
go func() {
// we ignore level-1 compact failure since it is not fatal.
// no need log the error, it is done in (*Importer).Compact already.
var _ = rc.doCompact(ctx, Level1Compact)
atomic.StoreInt32(&rc.compactState, compactStateIdle)
}()
}
return nil
}
func (t *TableRestore) postProcess(ctx context.Context, rc *RestoreController, cp *TableCheckpoint) error {
if !rc.backend.ShouldPostProcess() {
t.logger.Debug("skip post-processing, not supported by backend")
rc.saveStatusCheckpoint(t.tableName, WholeTableEngineID, nil, CheckpointStatusAnalyzeSkipped)
return nil
}
setSessionConcurrencyVars(ctx, rc.tidbMgr.db, rc.cfg.TiDB)
// 3. alter table set auto_increment
if cp.Status < CheckpointStatusAlteredAutoInc {
rc.alterTableLock.Lock()
err := AlterAutoIncrement(ctx, rc.tidbMgr.db, t.tableName, t.alloc.Base()+1)
rc.alterTableLock.Unlock()
rc.saveStatusCheckpoint(t.tableName, WholeTableEngineID, err, CheckpointStatusAlteredAutoInc)
if err != nil {
return err
}
}
// 4. do table checksum
var localChecksum verify.KVChecksum
for _, engine := range cp.Engines {
for _, chunk := range engine.Chunks {
localChecksum.Add(&chunk.Checksum)
}
}
t.logger.Info("local checksum", zap.Object("checksum", &localChecksum))
if cp.Status < CheckpointStatusChecksummed {
if !rc.cfg.PostRestore.Checksum {
t.logger.Info("skip checksum")
rc.saveStatusCheckpoint(t.tableName, WholeTableEngineID, nil, CheckpointStatusChecksumSkipped)
} else {
err := t.compareChecksum(ctx, rc.tidbMgr.db, localChecksum)
rc.saveStatusCheckpoint(t.tableName, WholeTableEngineID, err, CheckpointStatusChecksummed)
if err != nil {
return errors.Trace(err)
}
}
}
// 5. do table analyze
if cp.Status < CheckpointStatusAnalyzed {
if !rc.cfg.PostRestore.Analyze {
t.logger.Info("skip analyze")
rc.saveStatusCheckpoint(t.tableName, WholeTableEngineID, nil, CheckpointStatusAnalyzeSkipped)
} else {
err := t.analyzeTable(ctx, rc.tidbMgr.db)
rc.saveStatusCheckpoint(t.tableName, WholeTableEngineID, err, CheckpointStatusAnalyzed)
if err != nil {
return errors.Trace(err)
}
}
}
return nil
}
// do full compaction for the whole data.
func (rc *RestoreController) fullCompact(ctx context.Context) error {
if !rc.cfg.PostRestore.Compact {
log.L().Info("skip full compaction")
return nil
}