-
Notifications
You must be signed in to change notification settings - Fork 5.9k
/
table_import.go
1675 lines (1526 loc) · 53 KB
/
table_import.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 2021 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,
// 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.
package importer
import (
"context"
"database/sql"
"encoding/hex"
"fmt"
"path/filepath"
"strings"
"sync"
"time"
dmysql "github.com/go-sql-driver/mysql"
"github.com/pingcap/errors"
"github.com/pingcap/failpoint"
"github.com/pingcap/tidb/br/pkg/lightning/backend"
"github.com/pingcap/tidb/br/pkg/lightning/backend/encode"
"github.com/pingcap/tidb/br/pkg/lightning/backend/kv"
"github.com/pingcap/tidb/br/pkg/lightning/backend/local"
"github.com/pingcap/tidb/br/pkg/lightning/checkpoints"
"github.com/pingcap/tidb/br/pkg/lightning/common"
"github.com/pingcap/tidb/br/pkg/lightning/config"
"github.com/pingcap/tidb/br/pkg/lightning/log"
"github.com/pingcap/tidb/br/pkg/lightning/metric"
"github.com/pingcap/tidb/br/pkg/lightning/mydump"
verify "github.com/pingcap/tidb/br/pkg/lightning/verification"
"github.com/pingcap/tidb/br/pkg/lightning/web"
"github.com/pingcap/tidb/br/pkg/lightning/worker"
"github.com/pingcap/tidb/br/pkg/version"
"github.com/pingcap/tidb/errno"
tidbkv "github.com/pingcap/tidb/kv"
"github.com/pingcap/tidb/meta/autoid"
"github.com/pingcap/tidb/parser/model"
"github.com/pingcap/tidb/parser/mysql"
"github.com/pingcap/tidb/table"
"github.com/pingcap/tidb/table/tables"
"github.com/pingcap/tidb/util/codec"
"github.com/pingcap/tidb/util/extsort"
"github.com/pingcap/tidb/util/mathutil"
"go.uber.org/multierr"
"go.uber.org/zap"
"golang.org/x/exp/slices"
)
// TableImporter is a helper struct to import a table.
type TableImporter struct {
// The unique table name in the form "`db`.`tbl`".
tableName string
dbInfo *checkpoints.TidbDBInfo
tableInfo *checkpoints.TidbTableInfo
tableMeta *mydump.MDTableMeta
encTable table.Table
alloc autoid.Allocators
logger log.Logger
kvStore tidbkv.Storage
// dupIgnoreRows tracks the rowIDs of rows that are duplicated and should be ignored.
dupIgnoreRows extsort.ExternalSorter
ignoreColumns map[string]struct{}
}
// NewTableImporter creates a new TableImporter.
func NewTableImporter(
tableName string,
tableMeta *mydump.MDTableMeta,
dbInfo *checkpoints.TidbDBInfo,
tableInfo *checkpoints.TidbTableInfo,
cp *checkpoints.TableCheckpoint,
ignoreColumns map[string]struct{},
kvStore tidbkv.Storage,
logger log.Logger,
) (*TableImporter, error) {
idAlloc := kv.NewPanickingAllocators(cp.AllocBase)
tbl, err := tables.TableFromMeta(idAlloc, tableInfo.Core)
if err != nil {
return nil, errors.Annotatef(err, "failed to tables.TableFromMeta %s", tableName)
}
return &TableImporter{
tableName: tableName,
dbInfo: dbInfo,
tableInfo: tableInfo,
tableMeta: tableMeta,
encTable: tbl,
alloc: idAlloc,
kvStore: kvStore,
logger: logger.With(zap.String("table", tableName)),
ignoreColumns: ignoreColumns,
}, nil
}
func (tr *TableImporter) importTable(
ctx context.Context,
rc *Controller,
cp *checkpoints.TableCheckpoint,
) (bool, error) {
// 1. Load the table info.
select {
case <-ctx.Done():
return false, ctx.Err()
default:
}
metaMgr := rc.metaMgrBuilder.TableMetaMgr(tr)
// no need to do anything if the chunks are already populated
if len(cp.Engines) > 0 {
tr.logger.Info("reusing engines and files info from checkpoint",
zap.Int("enginesCnt", len(cp.Engines)),
zap.Int("filesCnt", cp.CountChunks()),
)
err := addExtendDataForCheckpoint(ctx, rc.cfg, cp)
if err != nil {
return false, errors.Trace(err)
}
} else if cp.Status < checkpoints.CheckpointStatusAllWritten {
if err := tr.populateChunks(ctx, rc, cp); err != nil {
return false, errors.Trace(err)
}
// fetch the max chunk row_id max value as the global max row_id
rowIDMax := int64(0)
for _, engine := range cp.Engines {
if len(engine.Chunks) > 0 && engine.Chunks[len(engine.Chunks)-1].Chunk.RowIDMax > rowIDMax {
rowIDMax = engine.Chunks[len(engine.Chunks)-1].Chunk.RowIDMax
}
}
versionStr, err := version.FetchVersion(ctx, rc.db)
if err != nil {
return false, errors.Trace(err)
}
versionInfo := version.ParseServerInfo(versionStr)
// "show table next_row_id" is only available after tidb v4.0.0
if versionInfo.ServerVersion.Major >= 4 && isLocalBackend(rc.cfg) {
// first, insert a new-line into meta table
if err = metaMgr.InitTableMeta(ctx); err != nil {
return false, err
}
checksum, rowIDBase, err := metaMgr.AllocTableRowIDs(ctx, rowIDMax)
if err != nil {
return false, err
}
tr.RebaseChunkRowIDs(cp, rowIDBase)
if checksum != nil {
if cp.Checksum != *checksum {
cp.Checksum = *checksum
rc.saveCpCh <- saveCp{
tableName: tr.tableName,
merger: &checkpoints.TableChecksumMerger{
Checksum: cp.Checksum,
},
}
}
tr.logger.Info("checksum before restore table", zap.Object("checksum", &cp.Checksum))
}
}
if err := rc.checkpointsDB.InsertEngineCheckpoints(ctx, tr.tableName, cp.Engines); err != nil {
return false, errors.Trace(err)
}
web.BroadcastTableCheckpoint(tr.tableName, cp)
// rebase the allocator so it exceeds the number of rows.
if tr.tableInfo.Core.ContainsAutoRandomBits() {
cp.AllocBase = mathutil.Max(cp.AllocBase, tr.tableInfo.Core.AutoRandID)
if err := tr.alloc.Get(autoid.AutoRandomType).Rebase(context.Background(), cp.AllocBase, false); err != nil {
return false, err
}
} else {
cp.AllocBase = mathutil.Max(cp.AllocBase, tr.tableInfo.Core.AutoIncID)
if err := tr.alloc.Get(autoid.RowIDAllocType).Rebase(context.Background(), cp.AllocBase, false); err != nil {
return false, err
}
}
rc.saveCpCh <- saveCp{
tableName: tr.tableName,
merger: &checkpoints.RebaseCheckpointMerger{
AllocBase: cp.AllocBase,
},
}
}
// 2. Do duplicate detection if needed
if isLocalBackend(rc.cfg) && rc.cfg.TikvImporter.OnDuplicate != "" {
_, uuid := backend.MakeUUID(tr.tableName, common.IndexEngineID)
workingDir := filepath.Join(rc.cfg.TikvImporter.SortedKVDir, uuid.String()+local.DupDetectDirSuffix)
resultDir := filepath.Join(rc.cfg.TikvImporter.SortedKVDir, uuid.String()+local.DupResultDirSuffix)
dupIgnoreRows, err := extsort.OpenDiskSorter(resultDir, &extsort.DiskSorterOptions{
Concurrency: rc.cfg.App.RegionConcurrency,
})
if err != nil {
return false, errors.Trace(err)
}
tr.dupIgnoreRows = dupIgnoreRows
if cp.Status < checkpoints.CheckpointStatusDupDetected {
err := tr.preDeduplicate(ctx, rc, cp, workingDir)
saveCpErr := rc.saveStatusCheckpoint(ctx, tr.tableName, checkpoints.WholeTableEngineID, err, checkpoints.CheckpointStatusDupDetected)
if err := firstErr(err, saveCpErr); err != nil {
return false, errors.Trace(err)
}
}
if !dupIgnoreRows.IsSorted() {
if err := dupIgnoreRows.Sort(ctx); err != nil {
return false, errors.Trace(err)
}
}
failpoint.Inject("FailAfterDuplicateDetection", func() {
panic("forcing failure after duplicate detection")
})
}
// 3. Drop indexes if add-index-by-sql is enabled
if cp.Status < checkpoints.CheckpointStatusIndexDropped && isLocalBackend(rc.cfg) && rc.cfg.TikvImporter.AddIndexBySQL {
err := tr.dropIndexes(ctx, rc.db)
saveCpErr := rc.saveStatusCheckpoint(ctx, tr.tableName, checkpoints.WholeTableEngineID, err, checkpoints.CheckpointStatusIndexDropped)
if err := firstErr(err, saveCpErr); err != nil {
return false, errors.Trace(err)
}
}
// 4. Restore engines (if still needed)
err := tr.importEngines(ctx, rc, cp)
if err != nil {
return false, errors.Trace(err)
}
err = metaMgr.UpdateTableStatus(ctx, metaStatusRestoreFinished)
if err != nil {
return false, errors.Trace(err)
}
// 5. Post-process. With the last parameter set to false, we can allow delay analyze execute latter
return tr.postProcess(ctx, rc, cp, false /* force-analyze */, metaMgr)
}
// Close implements the Importer interface.
func (tr *TableImporter) Close() {
tr.encTable = nil
if tr.dupIgnoreRows != nil {
_ = tr.dupIgnoreRows.Close()
}
tr.logger.Info("restore done")
}
func (tr *TableImporter) populateChunks(ctx context.Context, rc *Controller, cp *checkpoints.TableCheckpoint) error {
task := tr.logger.Begin(zap.InfoLevel, "load engines and files")
divideConfig := mydump.NewDataDivideConfig(rc.cfg, len(tr.tableInfo.Core.Columns), rc.ioWorkers, rc.store, tr.tableMeta)
tableRegions, err := mydump.MakeTableRegions(ctx, divideConfig)
if err == nil {
timestamp := time.Now().Unix()
failpoint.Inject("PopulateChunkTimestamp", func(v failpoint.Value) {
timestamp = int64(v.(int))
})
for _, region := range tableRegions {
engine, found := cp.Engines[region.EngineID]
if !found {
engine = &checkpoints.EngineCheckpoint{
Status: checkpoints.CheckpointStatusLoaded,
}
cp.Engines[region.EngineID] = engine
}
ccp := &checkpoints.ChunkCheckpoint{
Key: checkpoints.ChunkCheckpointKey{
Path: region.FileMeta.Path,
Offset: region.Chunk.Offset,
},
FileMeta: region.FileMeta,
ColumnPermutation: nil,
Chunk: region.Chunk,
Timestamp: timestamp,
}
if len(region.Chunk.Columns) > 0 {
perms, err := parseColumnPermutations(
tr.tableInfo.Core,
region.Chunk.Columns,
tr.ignoreColumns,
log.FromContext(ctx))
if err != nil {
return errors.Trace(err)
}
ccp.ColumnPermutation = perms
}
engine.Chunks = append(engine.Chunks, ccp)
}
// Add index engine checkpoint
cp.Engines[common.IndexEngineID] = &checkpoints.EngineCheckpoint{Status: checkpoints.CheckpointStatusLoaded}
}
task.End(zap.ErrorLevel, err,
zap.Int("enginesCnt", len(cp.Engines)),
zap.Int("filesCnt", len(tableRegions)),
)
return err
}
// RebaseChunkRowIDs rebase the row id of the chunks.
func (*TableImporter) RebaseChunkRowIDs(cp *checkpoints.TableCheckpoint, rowIDBase int64) {
if rowIDBase == 0 {
return
}
for _, engine := range cp.Engines {
for _, chunk := range engine.Chunks {
chunk.Chunk.PrevRowIDMax += rowIDBase
chunk.Chunk.RowIDMax += rowIDBase
}
}
}
// initializeColumns computes the "column permutation" for an INSERT INTO
// statement. Suppose a table has columns (a, b, c, d) in canonical order, and
// we execute `INSERT INTO (d, b, a) VALUES ...`, we will need to remap the
// columns as:
//
// - column `a` is at position 2
// - column `b` is at position 1
// - column `c` is missing
// - column `d` is at position 0
//
// The column permutation of (d, b, a) is set to be [2, 1, -1, 0].
//
// The argument `columns` _must_ be in lower case.
func (tr *TableImporter) initializeColumns(columns []string, ccp *checkpoints.ChunkCheckpoint) error {
colPerm, err := createColumnPermutation(columns, tr.ignoreColumns, tr.tableInfo.Core, tr.logger)
if err != nil {
return err
}
ccp.ColumnPermutation = colPerm
return nil
}
func createColumnPermutation(
columns []string,
ignoreColumns map[string]struct{},
tableInfo *model.TableInfo,
logger log.Logger,
) ([]int, error) {
var colPerm []int
if len(columns) == 0 {
colPerm = make([]int, 0, len(tableInfo.Columns)+1)
shouldIncludeRowID := common.TableHasAutoRowID(tableInfo)
// no provided columns, so use identity permutation.
for i, col := range tableInfo.Columns {
idx := i
if _, ok := ignoreColumns[col.Name.L]; ok {
idx = -1
} else if col.IsGenerated() {
idx = -1
}
colPerm = append(colPerm, idx)
}
if shouldIncludeRowID {
colPerm = append(colPerm, -1)
}
} else {
var err error
colPerm, err = parseColumnPermutations(tableInfo, columns, ignoreColumns, logger)
if err != nil {
return nil, errors.Trace(err)
}
}
return colPerm, nil
}
func (tr *TableImporter) importEngines(pCtx context.Context, rc *Controller, cp *checkpoints.TableCheckpoint) error {
indexEngineCp := cp.Engines[common.IndexEngineID]
if indexEngineCp == nil {
tr.logger.Error("fail to importEngines because indexengine is nil")
return common.ErrCheckpointNotFound.GenWithStack("table %v index engine checkpoint not found", tr.tableName)
}
ctx, cancel := context.WithCancel(pCtx)
defer cancel()
// 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 *backend.ClosedEngine
var restoreErr error
// if index-engine checkpoint is lower than `CheckpointStatusClosed`, there must be
// data-engines that need to be restore or import. Otherwise, all data-engines should
// be finished already.
handleDataEngineThisRun := false
idxEngineCfg := &backend.EngineConfig{
TableInfo: tr.tableInfo,
}
if indexEngineCp.Status < checkpoints.CheckpointStatusClosed {
handleDataEngineThisRun = true
indexWorker := rc.indexWorkers.Apply()
defer rc.indexWorkers.Recycle(indexWorker)
if rc.cfg.TikvImporter.Backend == config.BackendLocal {
// for index engine, the estimate factor is non-clustered index count
idxCnt := len(tr.tableInfo.Core.Indices)
if !common.TableHasAutoRowID(tr.tableInfo.Core) {
idxCnt--
}
threshold := local.EstimateCompactionThreshold(tr.tableMeta.DataFiles, cp, int64(idxCnt))
idxEngineCfg.Local = backend.LocalEngineConfig{
Compact: threshold > 0,
CompactConcurrency: 4,
CompactThreshold: threshold,
}
}
// import backend can't reopen engine if engine is closed, so
// only open index engine if any data engines don't finish writing.
var indexEngine *backend.OpenedEngine
var err error
for engineID, engine := range cp.Engines {
if engineID == common.IndexEngineID {
continue
}
if engine.Status < checkpoints.CheckpointStatusAllWritten {
indexEngine, err = rc.engineMgr.OpenEngine(ctx, idxEngineCfg, tr.tableName, common.IndexEngineID)
if err != nil {
return errors.Trace(err)
}
break
}
}
logTask := tr.logger.Begin(zap.InfoLevel, "import whole table")
var wg sync.WaitGroup
var engineErr common.OnceError
setError := func(err error) {
engineErr.Set(err)
// cancel this context to fail fast
cancel()
}
type engineCheckpoint struct {
engineID int32
checkpoint *checkpoints.EngineCheckpoint
}
allEngines := make([]engineCheckpoint, 0, len(cp.Engines))
for engineID, engine := range cp.Engines {
allEngines = append(allEngines, engineCheckpoint{engineID: engineID, checkpoint: engine})
}
slices.SortFunc(allEngines, func(i, j engineCheckpoint) bool { return i.engineID < j.engineID })
for _, ecp := range allEngines {
engineID := ecp.engineID
engine := ecp.checkpoint
select {
case <-ctx.Done():
// Set engineErr and break this for loop to wait all the sub-routines done before return.
// Directly return may cause panic because caller will close the pebble db but some sub routines
// are still reading from or writing to the pebble db.
engineErr.Set(ctx.Err())
default:
}
if engineErr.Get() != nil {
break
}
// Should skip index engine
if engineID < 0 {
continue
}
if engine.Status < checkpoints.CheckpointStatusImported {
wg.Add(1)
// If the number of chunks is small, it means that this engine may be finished in a few times.
// We do not limit it in TableConcurrency
restoreWorker := rc.tableWorkers.Apply()
go func(w *worker.Worker, eid int32, ecp *checkpoints.EngineCheckpoint) {
defer wg.Done()
engineLogTask := tr.logger.With(zap.Int32("engineNumber", eid)).Begin(zap.InfoLevel, "restore engine")
dataClosedEngine, err := tr.preprocessEngine(ctx, rc, indexEngine, eid, ecp)
engineLogTask.End(zap.ErrorLevel, err)
rc.tableWorkers.Recycle(w)
if err == nil {
dataWorker := rc.closedEngineLimit.Apply()
defer rc.closedEngineLimit.Recycle(dataWorker)
err = tr.importEngine(ctx, dataClosedEngine, rc, ecp)
if rc.status != nil && rc.status.backend == config.BackendLocal {
for _, chunk := range ecp.Chunks {
rc.status.FinishedFileSize.Add(chunk.TotalSize())
}
}
}
if err != nil {
setError(err)
}
}(restoreWorker, engineID, engine)
} else {
for _, chunk := range engine.Chunks {
rc.status.FinishedFileSize.Add(chunk.TotalSize())
}
}
}
wg.Wait()
restoreErr = engineErr.Get()
logTask.End(zap.ErrorLevel, restoreErr)
if restoreErr != nil {
return errors.Trace(restoreErr)
}
if indexEngine != nil {
closedIndexEngine, restoreErr = indexEngine.Close(ctx)
} else {
closedIndexEngine, restoreErr = rc.engineMgr.UnsafeCloseEngine(ctx, idxEngineCfg, tr.tableName, common.IndexEngineID)
}
if err = rc.saveStatusCheckpoint(ctx, tr.tableName, common.IndexEngineID, restoreErr, checkpoints.CheckpointStatusClosed); err != nil {
return errors.Trace(firstErr(restoreErr, err))
}
} else if indexEngineCp.Status == checkpoints.CheckpointStatusClosed {
// If index engine file has been closed but not imported only if context cancel occurred
// when `importKV()` execution, so `UnsafeCloseEngine` and continue import it.
closedIndexEngine, restoreErr = rc.engineMgr.UnsafeCloseEngine(ctx, idxEngineCfg, tr.tableName, common.IndexEngineID)
}
if restoreErr != nil {
return errors.Trace(restoreErr)
}
// if data engine is handled in previous run and we continue importing from checkpoint
if !handleDataEngineThisRun {
for _, engine := range cp.Engines {
for _, chunk := range engine.Chunks {
rc.status.FinishedFileSize.Add(chunk.Chunk.EndOffset - chunk.Key.Offset)
}
}
}
if cp.Status < checkpoints.CheckpointStatusIndexImported {
var err error
if indexEngineCp.Status < checkpoints.CheckpointStatusImported {
failpoint.Inject("FailBeforeStartImportingIndexEngine", func() {
errMsg := "fail before importing index KV data"
tr.logger.Warn(errMsg)
failpoint.Return(errors.New(errMsg))
})
err = tr.importKV(ctx, closedIndexEngine, rc)
failpoint.Inject("FailBeforeIndexEngineImported", func() {
finished := rc.status.FinishedFileSize.Load()
total := rc.status.TotalFileSize.Load()
tr.logger.Warn("print lightning status",
zap.Int64("finished", finished),
zap.Int64("total", total),
zap.Bool("equal", finished == total))
panic("forcing failure due to FailBeforeIndexEngineImported")
})
}
saveCpErr := rc.saveStatusCheckpoint(ctx, tr.tableName, checkpoints.WholeTableEngineID, err, checkpoints.CheckpointStatusIndexImported)
if err = firstErr(err, saveCpErr); err != nil {
return errors.Trace(err)
}
}
return nil
}
// preprocessEngine do some preprocess work
// for local backend, it do local sort, for tidb backend it transforms data into sql and execute
// TODO: it's not a correct name for tidb backend, since there's no post-process for it
// TODO: after separate local/tidb backend more clearly, rename it.
func (tr *TableImporter) preprocessEngine(
pCtx context.Context,
rc *Controller,
indexEngine *backend.OpenedEngine,
engineID int32,
cp *checkpoints.EngineCheckpoint,
) (*backend.ClosedEngine, error) {
ctx, cancel := context.WithCancel(pCtx)
defer cancel()
// all data has finished written, we can close the engine directly.
if cp.Status >= checkpoints.CheckpointStatusAllWritten {
engineCfg := &backend.EngineConfig{
TableInfo: tr.tableInfo,
}
closedEngine, err := rc.engineMgr.UnsafeCloseEngine(ctx, engineCfg, tr.tableName, engineID)
// If any error occurred, recycle worker immediately
if err != nil {
return closedEngine, errors.Trace(err)
}
if rc.status != nil && rc.status.backend == config.BackendTiDB {
for _, chunk := range cp.Chunks {
rc.status.FinishedFileSize.Add(chunk.Chunk.EndOffset - chunk.Key.Offset)
}
}
return closedEngine, nil
}
// if the key are ordered, LocalWrite can optimize the writing.
// table has auto-incremented _tidb_rowid must satisfy following restrictions:
// - clustered index disable and primary key is not number
// - no auto random bits (auto random or shard row id)
// - no partition table
// - no explicit _tidb_rowid field (At this time we can't determine if the source file contains _tidb_rowid field,
// so we will do this check in LocalWriter when the first row is received.)
hasAutoIncrementAutoID := common.TableHasAutoRowID(tr.tableInfo.Core) &&
tr.tableInfo.Core.AutoRandomBits == 0 && tr.tableInfo.Core.ShardRowIDBits == 0 &&
tr.tableInfo.Core.Partition == nil
dataWriterCfg := &backend.LocalWriterConfig{
IsKVSorted: hasAutoIncrementAutoID,
TableName: tr.tableName,
}
logTask := tr.logger.With(zap.Int32("engineNumber", engineID)).Begin(zap.InfoLevel, "encode kv data and write")
dataEngineCfg := &backend.EngineConfig{
TableInfo: tr.tableInfo,
}
if !tr.tableMeta.IsRowOrdered {
dataEngineCfg.Local.Compact = true
dataEngineCfg.Local.CompactConcurrency = 4
dataEngineCfg.Local.CompactThreshold = local.CompactionUpperThreshold
}
dataEngine, err := rc.engineMgr.OpenEngine(ctx, dataEngineCfg, tr.tableName, engineID)
if err != nil {
return nil, errors.Trace(err)
}
var wg sync.WaitGroup
var chunkErr common.OnceError
type chunkFlushStatus struct {
dataStatus backend.ChunkFlushStatus
indexStatus backend.ChunkFlushStatus
chunkCp *checkpoints.ChunkCheckpoint
}
// chunks that are finished writing, but checkpoints are not finished due to flush not finished.
var checkFlushLock sync.Mutex
flushPendingChunks := make([]chunkFlushStatus, 0, 16)
chunkCpChan := make(chan *checkpoints.ChunkCheckpoint, 16)
go func() {
for {
select {
case cp, ok := <-chunkCpChan:
if !ok {
return
}
saveCheckpoint(rc, tr, engineID, cp)
case <-ctx.Done():
return
}
}
}()
setError := func(err error) {
chunkErr.Set(err)
cancel()
}
metrics, _ := metric.FromContext(ctx)
// Restore table data
ChunkLoop:
for chunkIndex, chunk := range cp.Chunks {
if rc.status != nil && rc.status.backend == config.BackendTiDB {
rc.status.FinishedFileSize.Add(chunk.Chunk.Offset - chunk.Key.Offset)
}
if chunk.Chunk.Offset >= chunk.Chunk.EndOffset {
continue
}
checkFlushLock.Lock()
finished := 0
for _, c := range flushPendingChunks {
if !(c.indexStatus.Flushed() && c.dataStatus.Flushed()) {
break
}
chunkCpChan <- c.chunkCp
finished++
}
if finished > 0 {
flushPendingChunks = flushPendingChunks[finished:]
}
checkFlushLock.Unlock()
failpoint.Inject("orphanWriterGoRoutine", func() {
if chunkIndex > 0 {
<-pCtx.Done()
}
})
select {
case <-pCtx.Done():
break ChunkLoop
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)
var remainChunkCnt float64
if chunk.Chunk.Offset < chunk.Chunk.EndOffset {
remainChunkCnt = float64(chunk.UnfinishedSize()) / float64(chunk.TotalSize())
if metrics != nil {
metrics.ChunkCounter.WithLabelValues(metric.ChunkStatePending).Add(remainChunkCnt)
}
}
dataWriter, err := dataEngine.LocalWriter(ctx, dataWriterCfg)
if err != nil {
setError(err)
break
}
indexWriter, err := indexEngine.LocalWriter(ctx, &backend.LocalWriterConfig{TableName: tr.tableName})
if err != nil {
_, _ = dataWriter.Close(ctx)
setError(err)
break
}
cr, err := newChunkProcessor(ctx, chunkIndex, rc.cfg, chunk, rc.ioWorkers, rc.store, tr.tableInfo.Core)
if err != nil {
setError(err)
break
}
restoreWorker := rc.regionWorkers.Apply()
wg.Add(1)
go func(w *worker.Worker, cr *chunkProcessor) {
// Restore a chunk.
defer func() {
cr.close()
wg.Done()
rc.regionWorkers.Recycle(w)
}()
if metrics != nil {
metrics.ChunkCounter.WithLabelValues(metric.ChunkStateRunning).Add(remainChunkCnt)
}
err := cr.process(ctx, tr, engineID, dataWriter, indexWriter, rc)
var dataFlushStatus, indexFlushStaus backend.ChunkFlushStatus
if err == nil {
dataFlushStatus, err = dataWriter.Close(ctx)
}
if err == nil {
indexFlushStaus, err = indexWriter.Close(ctx)
}
if err == nil {
if metrics != nil {
metrics.ChunkCounter.WithLabelValues(metric.ChunkStateFinished).Add(remainChunkCnt)
metrics.BytesCounter.WithLabelValues(metric.StateRestoreWritten).Add(float64(cr.chunk.Checksum.SumSize()))
}
if dataFlushStatus != nil && indexFlushStaus != nil {
if dataFlushStatus.Flushed() && indexFlushStaus.Flushed() {
saveCheckpoint(rc, tr, engineID, cr.chunk)
} else {
checkFlushLock.Lock()
flushPendingChunks = append(flushPendingChunks, chunkFlushStatus{
dataStatus: dataFlushStatus,
indexStatus: indexFlushStaus,
chunkCp: cr.chunk,
})
checkFlushLock.Unlock()
}
}
} else {
if metrics != nil {
metrics.ChunkCounter.WithLabelValues(metric.ChunkStateFailed).Add(remainChunkCnt)
}
setError(err)
}
}(restoreWorker, cr)
}
wg.Wait()
select {
case <-pCtx.Done():
return nil, pCtx.Err()
default:
}
// Report some statistics into the log for debugging.
totalKVSize := uint64(0)
totalSQLSize := int64(0)
logKeyName := "read(bytes)"
for _, chunk := range cp.Chunks {
totalKVSize += chunk.Checksum.SumSize()
totalSQLSize += chunk.UnfinishedSize()
if chunk.FileMeta.Type == mydump.SourceTypeParquet {
logKeyName = "read(rows)"
}
}
err = chunkErr.Get()
logTask.End(zap.ErrorLevel, err,
zap.Int64(logKeyName, totalSQLSize),
zap.Uint64("written", totalKVSize),
)
trySavePendingChunks := func(flushCtx context.Context) error {
checkFlushLock.Lock()
cnt := 0
for _, chunk := range flushPendingChunks {
if !(chunk.dataStatus.Flushed() && chunk.indexStatus.Flushed()) {
break
}
saveCheckpoint(rc, tr, engineID, chunk.chunkCp)
cnt++
}
flushPendingChunks = flushPendingChunks[cnt:]
checkFlushLock.Unlock()
return nil
}
// in local mode, this check-point make no sense, because we don't do flush now,
// so there may be data lose if exit at here. So we don't write this checkpoint
// here like other mode.
if !isLocalBackend(rc.cfg) {
if saveCpErr := rc.saveStatusCheckpoint(ctx, tr.tableName, engineID, err, checkpoints.CheckpointStatusAllWritten); saveCpErr != nil {
return nil, errors.Trace(firstErr(err, saveCpErr))
}
}
if err != nil {
// if process is canceled, we should flush all chunk checkpoints for local backend
if isLocalBackend(rc.cfg) && common.IsContextCanceledError(err) {
// ctx is canceled, so to avoid Close engine failed, we use `context.Background()` here
if _, err2 := dataEngine.Close(context.Background()); err2 != nil {
log.FromContext(ctx).Warn("flush all chunk checkpoints failed before manually exits", zap.Error(err2))
return nil, errors.Trace(err)
}
if err2 := trySavePendingChunks(context.Background()); err2 != nil {
log.FromContext(ctx).Warn("flush all chunk checkpoints failed before manually exits", zap.Error(err2))
}
}
return nil, errors.Trace(err)
}
closedDataEngine, err := dataEngine.Close(ctx)
// For local backend, if checkpoint is enabled, we must flush index engine to avoid data loss.
// this flush action impact up to 10% of the performance, so we only do it if necessary.
if err == nil && rc.cfg.Checkpoint.Enable && isLocalBackend(rc.cfg) {
if err = indexEngine.Flush(ctx); err != nil {
return nil, errors.Trace(err)
}
if err = trySavePendingChunks(ctx); err != nil {
return nil, errors.Trace(err)
}
}
saveCpErr := rc.saveStatusCheckpoint(ctx, tr.tableName, engineID, err, checkpoints.CheckpointStatusClosed)
if err = firstErr(err, saveCpErr); err != nil {
// If any error occurred, recycle worker immediately
return nil, errors.Trace(err)
}
return closedDataEngine, nil
}
func (tr *TableImporter) importEngine(
ctx context.Context,
closedEngine *backend.ClosedEngine,
rc *Controller,
cp *checkpoints.EngineCheckpoint,
) error {
if cp.Status >= checkpoints.CheckpointStatusImported {
return nil
}
// 1. calling import
if err := tr.importKV(ctx, closedEngine, rc); err != nil {
return errors.Trace(err)
}
// 2. perform a level-1 compact if idling.
if rc.cfg.PostRestore.Level1Compact && rc.compactState.CompareAndSwap(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.
_ = rc.doCompact(ctx, Level1Compact)
rc.compactState.Store(compactStateIdle)
}()
}
return nil
}
// postProcess execute rebase-auto-id/checksum/analyze according to the task config.
//
// if the parameter forcePostProcess to true, postProcess force run checksum and analyze even if the
// post-process-at-last config is true. And if this two phases are skipped, the first return value will be true.
func (tr *TableImporter) postProcess(
ctx context.Context,
rc *Controller,
cp *checkpoints.TableCheckpoint,
forcePostProcess bool,
metaMgr tableMetaMgr,
) (bool, error) {
if !rc.backend.ShouldPostProcess() {
return false, nil
}
// alter table set auto_increment
if cp.Status < checkpoints.CheckpointStatusAlteredAutoInc {
rc.alterTableLock.Lock()
tblInfo := tr.tableInfo.Core
var err error
if tblInfo.ContainsAutoRandomBits() {
ft := &common.GetAutoRandomColumn(tblInfo).FieldType
shardFmt := autoid.NewShardIDFormat(ft, tblInfo.AutoRandomBits, tblInfo.AutoRandomRangeBits)
maxCap := shardFmt.IncrementalBitsCapacity()
err = AlterAutoRandom(ctx, rc.db, tr.tableName, uint64(tr.alloc.Get(autoid.AutoRandomType).Base())+1, maxCap)
} else if common.TableHasAutoRowID(tblInfo) || tblInfo.GetAutoIncrementColInfo() != nil {
// only alter auto increment id iff table contains auto-increment column or generated handle
err = AlterAutoIncrement(ctx, rc.db, tr.tableName, uint64(tr.alloc.Get(autoid.RowIDAllocType).Base())+1)
}
rc.alterTableLock.Unlock()
saveCpErr := rc.saveStatusCheckpoint(ctx, tr.tableName, checkpoints.WholeTableEngineID, err, checkpoints.CheckpointStatusAlteredAutoInc)
if err = firstErr(err, saveCpErr); err != nil {
return false, err
}
cp.Status = checkpoints.CheckpointStatusAlteredAutoInc
}
// tidb backend don't need checksum & analyze
if rc.cfg.PostRestore.Checksum == config.OpLevelOff && rc.cfg.PostRestore.Analyze == config.OpLevelOff {
tr.logger.Debug("skip checksum & analyze, either because not supported by this backend or manually disabled")
err := rc.saveStatusCheckpoint(ctx, tr.tableName, checkpoints.WholeTableEngineID, nil, checkpoints.CheckpointStatusAnalyzeSkipped)
return false, errors.Trace(err)
}
if !forcePostProcess && rc.cfg.PostRestore.PostProcessAtLast {
return true, nil
}
w := rc.checksumWorks.Apply()
defer rc.checksumWorks.Recycle(w)
shouldSkipAnalyze := false
if cp.Status < checkpoints.CheckpointStatusChecksumSkipped {
// 4. do table checksum
var localChecksum verify.KVChecksum
for _, engine := range cp.Engines {
for _, chunk := range engine.Chunks {
localChecksum.Add(&chunk.Checksum)
}
}
tr.logger.Info("local checksum", zap.Object("checksum", &localChecksum))
// 4.5. do duplicate detection.
// if we came here, it must be a local backend.
// todo: remove this cast after we refactor the backend interface. Physical mode is so different, we shouldn't
// try to abstract it with logical mode.
localBackend := rc.backend.(*local.Backend)
dupeController := localBackend.GetDupeController(rc.cfg.TikvImporter.RangeConcurrency*2, rc.errorMgr)
hasDupe := false
if rc.cfg.TikvImporter.DuplicateResolution != config.DupeResAlgNone {
opts := &encode.SessionOptions{
SQLMode: mysql.ModeStrictAllTables,
SysVars: rc.sysVars,
}
var err error
hasLocalDupe, err := dupeController.CollectLocalDuplicateRows(ctx, tr.encTable, tr.tableName, opts)
if err != nil {
tr.logger.Error("collect local duplicate keys failed", log.ShortError(err))
return false, err
}
hasDupe = hasLocalDupe
}
failpoint.Inject("SlowDownCheckDupe", func(v failpoint.Value) {
sec := v.(int)
tr.logger.Warn("start to sleep several seconds before checking other dupe",
zap.Int("seconds", sec))
time.Sleep(time.Duration(sec) * time.Second)
})
otherHasDupe, needRemoteDupe, baseTotalChecksum, err := metaMgr.CheckAndUpdateLocalChecksum(ctx, &localChecksum, hasDupe)
if err != nil {
return false, err
}
needChecksum := !otherHasDupe && needRemoteDupe
hasDupe = hasDupe || otherHasDupe