-
Notifications
You must be signed in to change notification settings - Fork 5.9k
/
dump.go
1618 lines (1493 loc) · 52.5 KB
/
dump.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 2020 PingCAP, Inc. Licensed under Apache-2.0.
package export
import (
"bytes"
"context"
"database/sql"
"encoding/hex"
"fmt"
"math/big"
"strconv"
"strings"
"sync/atomic"
"time"
// import mysql driver
"github.com/go-sql-driver/mysql"
"github.com/pingcap/errors"
"github.com/pingcap/failpoint"
pclog "github.com/pingcap/log"
"github.com/pingcap/tidb/br/pkg/storage"
"github.com/pingcap/tidb/br/pkg/summary"
"github.com/pingcap/tidb/br/pkg/version"
"github.com/pingcap/tidb/dumpling/cli"
tcontext "github.com/pingcap/tidb/dumpling/context"
"github.com/pingcap/tidb/dumpling/log"
"github.com/pingcap/tidb/parser"
"github.com/pingcap/tidb/parser/ast"
"github.com/pingcap/tidb/parser/format"
"github.com/pingcap/tidb/store/helper"
"github.com/pingcap/tidb/tablecodec"
"github.com/pingcap/tidb/util/codec"
pd "github.com/tikv/pd/client"
"go.uber.org/zap"
"golang.org/x/exp/slices"
"golang.org/x/sync/errgroup"
)
var openDBFunc = sql.Open
var errEmptyHandleVals = errors.New("empty handleVals for TiDB table")
// Dumper is the dump progress structure
type Dumper struct {
tctx *tcontext.Context
cancelCtx context.CancelFunc
conf *Config
metrics *metrics
extStore storage.ExternalStorage
dbHandle *sql.DB
tidbPDClientForGC pd.Client
selectTiDBTableRegionFunc func(tctx *tcontext.Context, conn *BaseConn, meta TableMeta) (pkFields []string, pkVals [][]string, err error)
totalTables int64
charsetAndDefaultCollationMap map[string]string
speedRecorder *SpeedRecorder
}
// NewDumper returns a new Dumper
func NewDumper(ctx context.Context, conf *Config) (*Dumper, error) {
failpoint.Inject("setExtStorage", func(val failpoint.Value) {
path := val.(string)
b, err := storage.ParseBackend(path, nil)
if err != nil {
panic(err)
}
s, err := storage.New(context.Background(), b, &storage.ExternalStorageOptions{})
if err != nil {
panic(err)
}
conf.ExtStorage = s
})
tctx, cancelFn := tcontext.Background().WithContext(ctx).WithCancel()
d := &Dumper{
tctx: tctx,
conf: conf,
cancelCtx: cancelFn,
selectTiDBTableRegionFunc: selectTiDBTableRegion,
speedRecorder: NewSpeedRecorder(),
}
var err error
d.metrics = newMetrics(conf.PromFactory, conf.Labels)
d.metrics.registerTo(conf.PromRegistry)
defer func() {
if err != nil {
d.metrics.unregisterFrom(conf.PromRegistry)
}
}()
err = adjustConfig(conf,
registerTLSConfig,
validateSpecifiedSQL,
adjustFileFormat)
if err != nil {
return nil, err
}
err = runSteps(d,
initLogger,
createExternalStore,
startHTTPService,
openSQLDB,
detectServerInfo,
resolveAutoConsistency,
validateResolveAutoConsistency,
tidbSetPDClientForGC,
tidbGetSnapshot,
tidbStartGCSavepointUpdateService,
setSessionParam)
return d, err
}
// Dump dumps table from database
// nolint: gocyclo
func (d *Dumper) Dump() (dumpErr error) {
initColTypeRowReceiverMap()
var (
conn *sql.Conn
err error
conCtrl ConsistencyController
)
tctx, conf, pool := d.tctx, d.conf, d.dbHandle
tctx.L().Info("begin to run Dump", zap.Stringer("conf", conf))
m := newGlobalMetadata(tctx, d.extStore, conf.Snapshot)
repeatableRead := needRepeatableRead(conf.ServerInfo.ServerType, conf.Consistency)
defer func() {
if dumpErr == nil {
_ = m.writeGlobalMetaData()
}
}()
// for consistency lock, we should get table list at first to generate the lock tables SQL
if conf.Consistency == ConsistencyTypeLock {
conn, err = createConnWithConsistency(tctx, pool, repeatableRead)
if err != nil {
return errors.Trace(err)
}
if err = prepareTableListToDump(tctx, conf, conn); err != nil {
_ = conn.Close()
return err
}
_ = conn.Close()
}
conCtrl, err = NewConsistencyController(tctx, conf, pool)
if err != nil {
return err
}
if err = conCtrl.Setup(tctx); err != nil {
return errors.Trace(err)
}
// To avoid lock is not released
defer func() {
err = conCtrl.TearDown(tctx)
if err != nil {
tctx.L().Warn("fail to tear down consistency controller", zap.Error(err))
}
}()
metaConn, err := createConnWithConsistency(tctx, pool, repeatableRead)
if err != nil {
return err
}
defer func() {
_ = metaConn.Close()
}()
m.recordStartTime(time.Now())
// for consistency lock, we can write snapshot info after all tables are locked.
// the binlog pos may changed because there is still possible write between we lock tables and write master status.
// but for the locked tables doing replication that starts from metadata is safe.
// for consistency flush, record snapshot after whole tables are locked. The recorded meta info is exactly the locked snapshot.
// for consistency snapshot, we should use the snapshot that we get/set at first in metadata. TiDB will assure the snapshot of TSO.
// for consistency none, the binlog pos in metadata might be earlier than dumped data. We need to enable safe-mode to assure data safety.
err = m.recordGlobalMetaData(metaConn, conf.ServerInfo.ServerType, false)
if err != nil {
tctx.L().Info("get global metadata failed", log.ShortError(err))
}
if d.conf.CollationCompatible == StrictCollationCompatible {
//init charset and default collation map
d.charsetAndDefaultCollationMap, err = GetCharsetAndDefaultCollation(tctx.Context, metaConn)
if err != nil {
return err
}
}
// for other consistencies, we should get table list after consistency is set up and GlobalMetaData is cached
if conf.Consistency != ConsistencyTypeLock {
if err = prepareTableListToDump(tctx, conf, metaConn); err != nil {
return err
}
}
if err = d.renewSelectTableRegionFuncForLowerTiDB(tctx); err != nil {
tctx.L().Info("cannot update select table region info for TiDB", log.ShortError(err))
}
atomic.StoreInt64(&d.totalTables, int64(calculateTableCount(conf.Tables)))
rebuildConn := func(conn *sql.Conn, updateMeta bool) (*sql.Conn, error) {
// make sure that the lock connection is still alive
err1 := conCtrl.PingContext(tctx)
if err1 != nil {
return conn, errors.Trace(err1)
}
// give up the last broken connection
_ = conn.Close()
newConn, err1 := createConnWithConsistency(tctx, pool, repeatableRead)
if err1 != nil {
return conn, errors.Trace(err1)
}
conn = newConn
// renew the master status after connection. dm can't close safe-mode until dm reaches current pos
if updateMeta && conf.PosAfterConnect {
err1 = m.recordGlobalMetaData(conn, conf.ServerInfo.ServerType, true)
if err1 != nil {
return conn, errors.Trace(err1)
}
}
return conn, nil
}
taskChan := make(chan Task, defaultDumpThreads)
AddGauge(d.metrics.taskChannelCapacity, defaultDumpThreads)
wg, writingCtx := errgroup.WithContext(tctx)
writerCtx := tctx.WithContext(writingCtx)
writers, tearDownWriters, err := d.startWriters(writerCtx, wg, taskChan, rebuildConn)
if err != nil {
return err
}
defer tearDownWriters()
if conf.TransactionalConsistency {
if conf.Consistency == ConsistencyTypeFlush || conf.Consistency == ConsistencyTypeLock {
tctx.L().Info("All the dumping transactions have started. Start to unlock tables")
}
if err = conCtrl.TearDown(tctx); err != nil {
return errors.Trace(err)
}
}
// Inject consistency failpoint test after we release the table lock
failpoint.Inject("ConsistencyCheck", nil)
if conf.PosAfterConnect {
// record again, to provide a location to exit safe mode for DM
err = m.recordGlobalMetaData(metaConn, conf.ServerInfo.ServerType, true)
if err != nil {
tctx.L().Info("get global metadata (after connection pool established) failed", log.ShortError(err))
}
}
summary.SetLogCollector(summary.NewLogCollector(tctx.L().Info))
summary.SetUnit(summary.BackupUnit)
defer summary.Summary(summary.BackupUnit)
logProgressCtx, logProgressCancel := tctx.WithCancel()
go d.runLogProgress(logProgressCtx)
defer logProgressCancel()
tableDataStartTime := time.Now()
failpoint.Inject("PrintTiDBMemQuotaQuery", func(_ failpoint.Value) {
row := d.dbHandle.QueryRowContext(tctx, "select @@tidb_mem_quota_query;")
var s string
err = row.Scan(&s)
if err != nil {
fmt.Println(errors.Trace(err))
} else {
fmt.Printf("tidb_mem_quota_query == %s\n", s)
}
})
baseConn := newBaseConn(metaConn, canRebuildConn(conf.Consistency, conf.TransactionalConsistency), rebuildConn)
if conf.SQL == "" {
if err = d.dumpDatabases(writerCtx, baseConn, taskChan); err != nil && !errors.ErrorEqual(err, context.Canceled) {
return err
}
} else {
d.dumpSQL(writerCtx, baseConn, taskChan)
}
close(taskChan)
_ = baseConn.DBConn.Close()
if err := wg.Wait(); err != nil {
summary.CollectFailureUnit("dump table data", err)
return errors.Trace(err)
}
summary.CollectSuccessUnit("dump cost", countTotalTask(writers), time.Since(tableDataStartTime))
summary.SetSuccessStatus(true)
m.recordFinishTime(time.Now())
return nil
}
func (d *Dumper) startWriters(tctx *tcontext.Context, wg *errgroup.Group, taskChan <-chan Task,
rebuildConnFn func(*sql.Conn, bool) (*sql.Conn, error)) ([]*Writer, func(), error) {
conf, pool := d.conf, d.dbHandle
writers := make([]*Writer, conf.Threads)
for i := 0; i < conf.Threads; i++ {
conn, err := createConnWithConsistency(tctx, pool, needRepeatableRead(conf.ServerInfo.ServerType, conf.Consistency))
if err != nil {
return nil, func() {}, err
}
writer := NewWriter(tctx, int64(i), conf, conn, d.extStore, d.metrics)
writer.rebuildConnFn = rebuildConnFn
writer.setFinishTableCallBack(func(task Task) {
if _, ok := task.(*TaskTableData); ok {
IncCounter(d.metrics.finishedTablesCounter)
// FIXME: actually finishing the last chunk doesn't means this table is 'finished'.
// We can call this table is 'finished' if all its chunks are finished.
// Comment this log now to avoid ambiguity.
// tctx.L().Debug("finished dumping table data",
// zap.String("database", td.Meta.DatabaseName()),
// zap.String("table", td.Meta.TableName()))
}
})
writer.setFinishTaskCallBack(func(task Task) {
IncGauge(d.metrics.taskChannelCapacity)
if td, ok := task.(*TaskTableData); ok {
tctx.L().Debug("finish dumping table data task",
zap.String("database", td.Meta.DatabaseName()),
zap.String("table", td.Meta.TableName()),
zap.Int("chunkIdx", td.ChunkIndex))
}
})
wg.Go(func() error {
return writer.run(taskChan)
})
writers[i] = writer
}
tearDown := func() {
for _, w := range writers {
_ = w.conn.Close()
}
}
return writers, tearDown, nil
}
func (d *Dumper) dumpDatabases(tctx *tcontext.Context, metaConn *BaseConn, taskChan chan<- Task) error {
conf := d.conf
allTables := conf.Tables
// policy should be created before database
// placement policy in other server type can be different, so we only handle the tidb server
if conf.ServerInfo.ServerType == version.ServerTypeTiDB {
policyNames, err := ListAllPlacementPolicyNames(tctx, metaConn)
if err != nil {
errCause := errors.Cause(err)
if mysqlErr, ok := errCause.(*mysql.MySQLError); ok && mysqlErr.Number == ErrNoSuchTable {
// some old tidb version and other server type doesn't support placement rules, we can skip it.
tctx.L().Debug("cannot dump placement policy, maybe the server doesn't support it", log.ShortError(err))
} else {
tctx.L().Warn("fail to dump placement policy: ", log.ShortError(err))
}
}
for _, policy := range policyNames {
createPolicySQL, err := ShowCreatePlacementPolicy(tctx, metaConn, policy)
if err != nil {
return errors.Trace(err)
}
wrappedCreatePolicySQL := fmt.Sprintf("/*T![placement] %s */", createPolicySQL)
task := NewTaskPolicyMeta(policy, wrappedCreatePolicySQL)
ctxDone := d.sendTaskToChan(tctx, task, taskChan)
if ctxDone {
return tctx.Err()
}
}
}
parser1 := parser.New()
for dbName, tables := range allTables {
if !conf.NoSchemas {
createDatabaseSQL, err := ShowCreateDatabase(tctx, metaConn, dbName)
if err != nil {
return errors.Trace(err)
}
// adjust db collation
createDatabaseSQL, err = adjustDatabaseCollation(tctx, d.conf.CollationCompatible, parser1, createDatabaseSQL, d.charsetAndDefaultCollationMap)
if err != nil {
return errors.Trace(err)
}
task := NewTaskDatabaseMeta(dbName, createDatabaseSQL)
ctxDone := d.sendTaskToChan(tctx, task, taskChan)
if ctxDone {
return tctx.Err()
}
}
for _, table := range tables {
tctx.L().Debug("start dumping table...", zap.String("database", dbName),
zap.String("table", table.Name))
meta, err := dumpTableMeta(tctx, conf, metaConn, dbName, table)
if err != nil {
return errors.Trace(err)
}
if !conf.NoSchemas {
switch table.Type {
case TableTypeView:
task := NewTaskViewMeta(dbName, table.Name, meta.ShowCreateTable(), meta.ShowCreateView())
ctxDone := d.sendTaskToChan(tctx, task, taskChan)
if ctxDone {
return tctx.Err()
}
case TableTypeSequence:
task := NewTaskSequenceMeta(dbName, table.Name, meta.ShowCreateTable())
ctxDone := d.sendTaskToChan(tctx, task, taskChan)
if ctxDone {
return tctx.Err()
}
default:
// adjust table collation
newCreateSQL, err := adjustTableCollation(tctx, d.conf.CollationCompatible, parser1, meta.ShowCreateTable(), d.charsetAndDefaultCollationMap)
if err != nil {
return errors.Trace(err)
}
meta.(*tableMeta).showCreateTable = newCreateSQL
task := NewTaskTableMeta(dbName, table.Name, meta.ShowCreateTable())
ctxDone := d.sendTaskToChan(tctx, task, taskChan)
if ctxDone {
return tctx.Err()
}
}
}
if table.Type == TableTypeBase {
err = d.dumpTableData(tctx, metaConn, meta, taskChan)
if err != nil {
return errors.Trace(err)
}
}
}
}
return nil
}
// adjustDatabaseCollation adjusts db collation and return new create sql and collation
func adjustDatabaseCollation(tctx *tcontext.Context, collationCompatible string, parser *parser.Parser, originSQL string, charsetAndDefaultCollationMap map[string]string) (string, error) {
if collationCompatible != StrictCollationCompatible {
return originSQL, nil
}
stmt, err := parser.ParseOneStmt(originSQL, "", "")
if err != nil {
tctx.L().Warn("parse create database error, maybe tidb parser doesn't support it", zap.String("originSQL", originSQL), log.ShortError(err))
return originSQL, nil
}
createStmt, ok := stmt.(*ast.CreateDatabaseStmt)
if !ok {
return originSQL, nil
}
var charset string
for _, createOption := range createStmt.Options {
// already have 'Collation'
if createOption.Tp == ast.DatabaseOptionCollate {
return originSQL, nil
}
if createOption.Tp == ast.DatabaseOptionCharset {
charset = createOption.Value
}
}
// get db collation
collation, ok := charsetAndDefaultCollationMap[strings.ToLower(charset)]
if !ok {
tctx.L().Warn("not found database charset default collation.", zap.String("originSQL", originSQL), zap.String("charset", strings.ToLower(charset)))
return originSQL, nil
}
// add collation
createStmt.Options = append(createStmt.Options, &ast.DatabaseOption{Tp: ast.DatabaseOptionCollate, Value: collation})
// rewrite sql
var b []byte
bf := bytes.NewBuffer(b)
err = createStmt.Restore(&format.RestoreCtx{
Flags: format.DefaultRestoreFlags | format.RestoreTiDBSpecialComment,
In: bf,
})
if err != nil {
return "", errors.Trace(err)
}
return bf.String(), nil
}
// adjustTableCollation adjusts table collation
func adjustTableCollation(tctx *tcontext.Context, collationCompatible string, parser *parser.Parser, originSQL string, charsetAndDefaultCollationMap map[string]string) (string, error) {
if collationCompatible != StrictCollationCompatible {
return originSQL, nil
}
stmt, err := parser.ParseOneStmt(originSQL, "", "")
if err != nil {
tctx.L().Warn("parse create table error, maybe tidb parser doesn't support it", zap.String("originSQL", originSQL), log.ShortError(err))
return originSQL, nil
}
createStmt, ok := stmt.(*ast.CreateTableStmt)
if !ok {
return originSQL, nil
}
var charset string
var collation string
for _, createOption := range createStmt.Options {
// already have 'Collation'
if createOption.Tp == ast.TableOptionCollate {
collation = createOption.StrValue
break
}
if createOption.Tp == ast.TableOptionCharset {
charset = createOption.StrValue
}
}
if collation == "" && charset != "" {
collation, ok := charsetAndDefaultCollationMap[strings.ToLower(charset)]
if !ok {
tctx.L().Warn("not found table charset default collation.", zap.String("originSQL", originSQL), zap.String("charset", strings.ToLower(charset)))
return originSQL, nil
}
// add collation
createStmt.Options = append(createStmt.Options, &ast.TableOption{Tp: ast.TableOptionCollate, StrValue: collation})
}
// adjust columns collation
adjustColumnsCollation(tctx, createStmt, charsetAndDefaultCollationMap)
// rewrite sql
var b []byte
bf := bytes.NewBuffer(b)
err = createStmt.Restore(&format.RestoreCtx{
Flags: format.DefaultRestoreFlags | format.RestoreTiDBSpecialComment,
In: bf,
})
if err != nil {
return "", errors.Trace(err)
}
return bf.String(), nil
}
// adjustColumnsCollation adds column's collation.
func adjustColumnsCollation(tctx *tcontext.Context, createStmt *ast.CreateTableStmt, charsetAndDefaultCollationMap map[string]string) {
ColumnLoop:
for _, col := range createStmt.Cols {
for _, options := range col.Options {
// already have 'Collation'
if options.Tp == ast.ColumnOptionCollate {
continue ColumnLoop
}
}
fieldType := col.Tp
if fieldType.GetCollate() != "" {
continue
}
if fieldType.GetCharset() != "" {
// just have charset
collation, ok := charsetAndDefaultCollationMap[strings.ToLower(fieldType.GetCharset())]
if !ok {
tctx.L().Warn("not found charset default collation for column.", zap.String("table", createStmt.Table.Name.String()), zap.String("column", col.Name.String()), zap.String("charset", strings.ToLower(fieldType.GetCharset())))
continue
}
fieldType.SetCollate(collation)
}
}
}
func (d *Dumper) dumpTableData(tctx *tcontext.Context, conn *BaseConn, meta TableMeta, taskChan chan<- Task) error {
conf := d.conf
if conf.NoData {
return nil
}
// Update total rows
fieldName, _ := pickupPossibleField(tctx, meta, conn)
c := estimateCount(tctx, meta.DatabaseName(), meta.TableName(), conn, fieldName, conf)
AddCounter(d.metrics.estimateTotalRowsCounter, float64(c))
if conf.Rows == UnspecifiedSize {
return d.sequentialDumpTable(tctx, conn, meta, taskChan)
}
return d.concurrentDumpTable(tctx, conn, meta, taskChan)
}
func (d *Dumper) buildConcatTask(tctx *tcontext.Context, conn *BaseConn, meta TableMeta) (*TaskTableData, error) {
tableChan := make(chan Task, 128)
errCh := make(chan error, 1)
go func() {
// adjust rows to suitable rows for this table
d.conf.Rows = GetSuitableRows(meta.AvgRowLength())
err := d.concurrentDumpTable(tctx, conn, meta, tableChan)
d.conf.Rows = UnspecifiedSize
if err != nil {
errCh <- err
} else {
close(errCh)
}
}()
tableDataArr := make([]*tableData, 0)
handleSubTask := func(task Task) {
tableTask, ok := task.(*TaskTableData)
if !ok {
tctx.L().Warn("unexpected task when splitting table chunks", zap.String("task", tableTask.Brief()))
return
}
tableDataInst, ok := tableTask.Data.(*tableData)
if !ok {
tctx.L().Warn("unexpected task.Data when splitting table chunks", zap.String("task", tableTask.Brief()))
return
}
tableDataArr = append(tableDataArr, tableDataInst)
}
for {
select {
case err, ok := <-errCh:
if !ok {
// make sure all the subtasks in tableChan are handled
for len(tableChan) > 0 {
task := <-tableChan
handleSubTask(task)
}
if len(tableDataArr) <= 1 {
return nil, nil
}
queries := make([]string, 0, len(tableDataArr))
colLen := tableDataArr[0].colLen
for _, tableDataInst := range tableDataArr {
queries = append(queries, tableDataInst.query)
if colLen != tableDataInst.colLen {
tctx.L().Warn("colLen varies for same table",
zap.Int("oldColLen", colLen),
zap.String("oldQuery", queries[0]),
zap.Int("newColLen", tableDataInst.colLen),
zap.String("newQuery", tableDataInst.query))
return nil, nil
}
}
return NewTaskTableData(meta, newMultiQueriesChunk(queries, colLen), 0, 1), nil
}
return nil, err
case task := <-tableChan:
handleSubTask(task)
}
}
}
func (d *Dumper) dumpWholeTableDirectly(tctx *tcontext.Context, meta TableMeta, taskChan chan<- Task, partition, orderByClause string, currentChunk, totalChunks int) error {
conf := d.conf
tableIR := SelectAllFromTable(conf, meta, partition, orderByClause)
task := NewTaskTableData(meta, tableIR, currentChunk, totalChunks)
ctxDone := d.sendTaskToChan(tctx, task, taskChan)
if ctxDone {
return tctx.Err()
}
return nil
}
func (d *Dumper) sequentialDumpTable(tctx *tcontext.Context, conn *BaseConn, meta TableMeta, taskChan chan<- Task) error {
conf := d.conf
if conf.ServerInfo.ServerType == version.ServerTypeTiDB {
task, err := d.buildConcatTask(tctx, conn, meta)
if err != nil {
return errors.Trace(err)
}
if task != nil {
ctxDone := d.sendTaskToChan(tctx, task, taskChan)
if ctxDone {
return tctx.Err()
}
return nil
}
tctx.L().Info("didn't build tidb concat sqls, will select all from table now",
zap.String("database", meta.DatabaseName()),
zap.String("table", meta.TableName()))
}
orderByClause, err := buildOrderByClause(tctx, conf, conn, meta.DatabaseName(), meta.TableName(), meta.HasImplicitRowID())
if err != nil {
return err
}
return d.dumpWholeTableDirectly(tctx, meta, taskChan, "", orderByClause, 0, 1)
}
// concurrentDumpTable tries to split table into several chunks to dump
func (d *Dumper) concurrentDumpTable(tctx *tcontext.Context, conn *BaseConn, meta TableMeta, taskChan chan<- Task) error {
conf := d.conf
db, tbl := meta.DatabaseName(), meta.TableName()
if conf.ServerInfo.ServerType == version.ServerTypeTiDB &&
conf.ServerInfo.ServerVersion != nil &&
(conf.ServerInfo.ServerVersion.Compare(*tableSampleVersion) >= 0 ||
(conf.ServerInfo.HasTiKV && conf.ServerInfo.ServerVersion.Compare(*decodeRegionVersion) >= 0)) {
err := d.concurrentDumpTiDBTables(tctx, conn, meta, taskChan)
// don't retry on context error and successful tasks
if err2 := errors.Cause(err); err2 == nil || err2 == context.DeadlineExceeded || err2 == context.Canceled {
return err
} else if err2 != errEmptyHandleVals {
tctx.L().Info("fallback to concurrent dump tables using rows due to some problem. This won't influence the whole dump process",
zap.String("database", db), zap.String("table", tbl), log.ShortError(err))
}
}
orderByClause, err := buildOrderByClause(tctx, conf, conn, db, tbl, meta.HasImplicitRowID())
if err != nil {
return err
}
field, err := pickupPossibleField(tctx, meta, conn)
if err != nil || field == "" {
// skip split chunk logic if not found proper field
tctx.L().Info("fallback to sequential dump due to no proper field. This won't influence the whole dump process",
zap.String("database", db), zap.String("table", tbl), log.ShortError(err))
return d.dumpWholeTableDirectly(tctx, meta, taskChan, "", orderByClause, 0, 1)
}
count := estimateCount(d.tctx, db, tbl, conn, field, conf)
tctx.L().Info("get estimated rows count",
zap.String("database", db),
zap.String("table", tbl),
zap.Uint64("estimateCount", count))
if count < conf.Rows {
// skip chunk logic if estimates are low
tctx.L().Info("fallback to sequential dump due to estimate count < rows. This won't influence the whole dump process",
zap.Uint64("estimate count", count),
zap.Uint64("conf.rows", conf.Rows),
zap.String("database", db),
zap.String("table", tbl))
return d.dumpWholeTableDirectly(tctx, meta, taskChan, "", orderByClause, 0, 1)
}
min, max, err := d.selectMinAndMaxIntValue(tctx, conn, db, tbl, field)
if err != nil {
tctx.L().Info("fallback to sequential dump due to cannot get bounding values. This won't influence the whole dump process",
log.ShortError(err))
return d.dumpWholeTableDirectly(tctx, meta, taskChan, "", orderByClause, 0, 1)
}
tctx.L().Debug("get int bounding values",
zap.String("lower", min.String()),
zap.String("upper", max.String()))
// every chunk would have eventual adjustments
estimatedChunks := count / conf.Rows
estimatedStep := new(big.Int).Sub(max, min).Uint64()/estimatedChunks + 1
bigEstimatedStep := new(big.Int).SetUint64(estimatedStep)
cutoff := new(big.Int).Set(min)
totalChunks := estimatedChunks
if estimatedStep == 1 {
totalChunks = new(big.Int).Sub(max, min).Uint64() + 1
}
selectField, selectLen := meta.SelectedField(), meta.SelectedLen()
chunkIndex := 0
nullValueCondition := ""
if conf.Where == "" {
nullValueCondition = fmt.Sprintf("`%s` IS NULL OR ", escapeString(field))
}
for max.Cmp(cutoff) >= 0 {
nextCutOff := new(big.Int).Add(cutoff, bigEstimatedStep)
where := fmt.Sprintf("%s(`%s` >= %d AND `%s` < %d)", nullValueCondition, escapeString(field), cutoff, escapeString(field), nextCutOff)
query := buildSelectQuery(db, tbl, selectField, "", buildWhereCondition(conf, where), orderByClause)
if len(nullValueCondition) > 0 {
nullValueCondition = ""
}
task := NewTaskTableData(meta, newTableData(query, selectLen, false), chunkIndex, int(totalChunks))
ctxDone := d.sendTaskToChan(tctx, task, taskChan)
if ctxDone {
return tctx.Err()
}
cutoff = nextCutOff
chunkIndex++
}
return nil
}
func (d *Dumper) sendTaskToChan(tctx *tcontext.Context, task Task, taskChan chan<- Task) (ctxDone bool) {
select {
case <-tctx.Done():
return true
case taskChan <- task:
tctx.L().Debug("send task to writer",
zap.String("task", task.Brief()))
DecGauge(d.metrics.taskChannelCapacity)
return false
}
}
func (d *Dumper) selectMinAndMaxIntValue(tctx *tcontext.Context, conn *BaseConn, db, tbl, field string) (*big.Int, *big.Int, error) {
conf, zero := d.conf, &big.Int{}
query := fmt.Sprintf("SELECT MIN(`%s`),MAX(`%s`) FROM `%s`.`%s`",
escapeString(field), escapeString(field), escapeString(db), escapeString(tbl))
if conf.Where != "" {
query = fmt.Sprintf("%s WHERE %s", query, conf.Where)
}
tctx.L().Debug("split chunks", zap.String("query", query))
var smin sql.NullString
var smax sql.NullString
err := conn.QuerySQL(tctx, func(rows *sql.Rows) error {
err := rows.Scan(&smin, &smax)
rows.Close()
return err
}, func() {}, query)
if err != nil {
return zero, zero, errors.Annotatef(err, "can't get min/max values to split chunks, query: %s", query)
}
if !smax.Valid || !smin.Valid {
// found no data
return zero, zero, errors.Errorf("no invalid min/max value found in query %s", query)
}
max := new(big.Int)
min := new(big.Int)
var ok bool
if max, ok = max.SetString(smax.String, 10); !ok {
return zero, zero, errors.Errorf("fail to convert max value %s in query %s", smax.String, query)
}
if min, ok = min.SetString(smin.String, 10); !ok {
return zero, zero, errors.Errorf("fail to convert min value %s in query %s", smin.String, query)
}
return min, max, nil
}
func (d *Dumper) concurrentDumpTiDBTables(tctx *tcontext.Context, conn *BaseConn, meta TableMeta, taskChan chan<- Task) error {
db, tbl := meta.DatabaseName(), meta.TableName()
var (
handleColNames []string
handleVals [][]string
err error
)
// for TiDB v5.0+, we can use table sample directly
if d.conf.ServerInfo.ServerVersion.Compare(*tableSampleVersion) >= 0 {
tctx.L().Debug("dumping TiDB tables with TABLESAMPLE",
zap.String("database", db), zap.String("table", tbl))
handleColNames, handleVals, err = selectTiDBTableSample(tctx, conn, meta)
} else {
// for TiDB v3.0+, we can use table region decode in TiDB directly
tctx.L().Debug("dumping TiDB tables with TABLE REGIONS",
zap.String("database", db), zap.String("table", tbl))
var partitions []string
if d.conf.ServerInfo.ServerVersion.Compare(*gcSafePointVersion) >= 0 {
partitions, err = GetPartitionNames(tctx, conn, db, tbl)
}
if err == nil {
if len(partitions) == 0 {
handleColNames, handleVals, err = d.selectTiDBTableRegionFunc(tctx, conn, meta)
} else {
return d.concurrentDumpTiDBPartitionTables(tctx, conn, meta, taskChan, partitions)
}
}
}
if err != nil {
return err
}
return d.sendConcurrentDumpTiDBTasks(tctx, meta, taskChan, handleColNames, handleVals, "", 0, len(handleVals)+1)
}
func (d *Dumper) concurrentDumpTiDBPartitionTables(tctx *tcontext.Context, conn *BaseConn, meta TableMeta, taskChan chan<- Task, partitions []string) error {
db, tbl := meta.DatabaseName(), meta.TableName()
tctx.L().Debug("dumping TiDB tables with TABLE REGIONS for partition table",
zap.String("database", db), zap.String("table", tbl), zap.Strings("partitions", partitions))
startChunkIdx := 0
totalChunk := 0
cachedHandleVals := make([][][]string, len(partitions))
handleColNames, _, err := selectTiDBRowKeyFields(tctx, conn, meta, checkTiDBTableRegionPkFields)
if err != nil {
return err
}
// cache handleVals here to calculate the total chunks
for i, partition := range partitions {
handleVals, err := selectTiDBPartitionRegion(tctx, conn, db, tbl, partition)
if err != nil {
return err
}
totalChunk += len(handleVals) + 1
cachedHandleVals[i] = handleVals
}
for i, partition := range partitions {
err := d.sendConcurrentDumpTiDBTasks(tctx, meta, taskChan, handleColNames, cachedHandleVals[i], partition, startChunkIdx, totalChunk)
if err != nil {
return err
}
startChunkIdx += len(cachedHandleVals[i]) + 1
}
return nil
}
func (d *Dumper) sendConcurrentDumpTiDBTasks(tctx *tcontext.Context,
meta TableMeta, taskChan chan<- Task,
handleColNames []string, handleVals [][]string, partition string, startChunkIdx, totalChunk int) error {
db, tbl := meta.DatabaseName(), meta.TableName()
if len(handleVals) == 0 {
if partition == "" {
// return error to make outside function try using rows method to dump data
return errors.Annotatef(errEmptyHandleVals, "table: `%s`.`%s`", escapeString(db), escapeString(tbl))
}
return d.dumpWholeTableDirectly(tctx, meta, taskChan, partition, buildOrderByClauseString(handleColNames), startChunkIdx, totalChunk)
}
conf := d.conf
selectField, selectLen := meta.SelectedField(), meta.SelectedLen()
where := buildWhereClauses(handleColNames, handleVals)
orderByClause := buildOrderByClauseString(handleColNames)
for i, w := range where {
query := buildSelectQuery(db, tbl, selectField, partition, buildWhereCondition(conf, w), orderByClause)
task := NewTaskTableData(meta, newTableData(query, selectLen, false), i+startChunkIdx, totalChunk)
ctxDone := d.sendTaskToChan(tctx, task, taskChan)
if ctxDone {
return tctx.Err()
}
}
return nil
}
// L returns real logger
func (d *Dumper) L() log.Logger {
return d.tctx.L()
}
func selectTiDBTableSample(tctx *tcontext.Context, conn *BaseConn, meta TableMeta) (pkFields []string, pkVals [][]string, err error) {
pkFields, pkColTypes, err := selectTiDBRowKeyFields(tctx, conn, meta, nil)
if err != nil {
return nil, nil, errors.Trace(err)
}
query := buildTiDBTableSampleQuery(pkFields, meta.DatabaseName(), meta.TableName())
pkValNum := len(pkFields)
var iter SQLRowIter
rowRec := MakeRowReceiver(pkColTypes)
buf := new(bytes.Buffer)
err = conn.QuerySQL(tctx, func(rows *sql.Rows) error {
if iter == nil {
iter = &rowIter{
rows: rows,
args: make([]interface{}, pkValNum),
}
}
err = iter.Decode(rowRec)
if err != nil {
return errors.Trace(err)
}
pkValRow := make([]string, 0, pkValNum)
for _, rec := range rowRec.receivers {
rec.WriteToBuffer(buf, true)
pkValRow = append(pkValRow, buf.String())
buf.Reset()
}
pkVals = append(pkVals, pkValRow)
return nil
}, func() {
if iter != nil {
_ = iter.Close()
iter = nil
}
rowRec = MakeRowReceiver(pkColTypes)
pkVals = pkVals[:0]
buf.Reset()
}, query)
if err == nil && iter != nil && iter.Error() != nil {
err = iter.Error()
}
return pkFields, pkVals, err
}
func buildTiDBTableSampleQuery(pkFields []string, dbName, tblName string) string {
template := "SELECT %s FROM `%s`.`%s` TABLESAMPLE REGIONS() ORDER BY %s"
quotaPk := make([]string, len(pkFields))
for i, s := range pkFields {
quotaPk[i] = fmt.Sprintf("`%s`", escapeString(s))
}
pks := strings.Join(quotaPk, ",")
return fmt.Sprintf(template, pks, escapeString(dbName), escapeString(tblName), pks)
}
func selectTiDBRowKeyFields(tctx *tcontext.Context, conn *BaseConn, meta TableMeta, checkPkFields func([]string, []string) error) (pkFields, pkColTypes []string, err error) {
if meta.HasImplicitRowID() {
pkFields, pkColTypes = []string{"_tidb_rowid"}, []string{"BIGINT"}
} else {
pkFields, pkColTypes, err = GetPrimaryKeyAndColumnTypes(tctx, conn, meta)
if err == nil {
if checkPkFields != nil {
err = checkPkFields(pkFields, pkColTypes)
}
}
}
return
}
func checkTiDBTableRegionPkFields(pkFields, pkColTypes []string) (err error) {
if len(pkFields) != 1 || len(pkColTypes) != 1 {
err = errors.Errorf("unsupported primary key for selectTableRegion. pkFields: [%s], pkColTypes: [%s]", strings.Join(pkFields, ", "), strings.Join(pkColTypes, ", "))
return
}
if _, ok := dataTypeInt[pkColTypes[0]]; !ok {
err = errors.Errorf("unsupported primary key type for selectTableRegion. pkFields: [%s], pkColTypes: [%s]", strings.Join(pkFields, ", "), strings.Join(pkColTypes, ", "))