-
Notifications
You must be signed in to change notification settings - Fork 287
/
syncer.go
4158 lines (3730 loc) · 141 KB
/
syncer.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 syncer
import (
"bytes"
"context"
"fmt"
"math"
"path"
"reflect"
"strconv"
"strings"
"sync"
"time"
"github.com/go-mysql-org/go-mysql/mysql"
"github.com/go-mysql-org/go-mysql/replication"
"github.com/pingcap/errors"
"github.com/pingcap/failpoint"
bf "github.com/pingcap/tidb-tools/pkg/binlog-filter"
cm "github.com/pingcap/tidb-tools/pkg/column-mapping"
"github.com/pingcap/tidb/parser"
"github.com/pingcap/tidb/parser/ast"
"github.com/pingcap/tidb/parser/format"
"github.com/pingcap/tidb/parser/model"
"github.com/pingcap/tidb/sessionctx"
"github.com/pingcap/tidb/util/dbutil"
"github.com/pingcap/tidb/util/filter"
regexprrouter "github.com/pingcap/tidb/util/regexpr-router"
router "github.com/pingcap/tidb/util/table-router"
"github.com/pingcap/tiflow/dm/pkg/gtid"
clientv3 "go.etcd.io/etcd/client/v3"
"go.uber.org/atomic"
"go.uber.org/zap"
"github.com/pingcap/tiflow/dm/dm/config"
"github.com/pingcap/tiflow/dm/dm/pb"
"github.com/pingcap/tiflow/dm/dm/unit"
"github.com/pingcap/tiflow/dm/pkg/binlog"
"github.com/pingcap/tiflow/dm/pkg/binlog/event"
"github.com/pingcap/tiflow/dm/pkg/binlog/reader"
"github.com/pingcap/tiflow/dm/pkg/conn"
tcontext "github.com/pingcap/tiflow/dm/pkg/context"
fr "github.com/pingcap/tiflow/dm/pkg/func-rollback"
"github.com/pingcap/tiflow/dm/pkg/ha"
"github.com/pingcap/tiflow/dm/pkg/log"
parserpkg "github.com/pingcap/tiflow/dm/pkg/parser"
"github.com/pingcap/tiflow/dm/pkg/schema"
"github.com/pingcap/tiflow/dm/pkg/shardddl/optimism"
"github.com/pingcap/tiflow/dm/pkg/shardddl/pessimism"
"github.com/pingcap/tiflow/dm/pkg/storage"
"github.com/pingcap/tiflow/dm/pkg/streamer"
"github.com/pingcap/tiflow/dm/pkg/terror"
"github.com/pingcap/tiflow/dm/pkg/utils"
"github.com/pingcap/tiflow/dm/relay"
"github.com/pingcap/tiflow/dm/syncer/dbconn"
operator "github.com/pingcap/tiflow/dm/syncer/err-operator"
"github.com/pingcap/tiflow/dm/syncer/metrics"
onlineddl "github.com/pingcap/tiflow/dm/syncer/online-ddl-tools"
sm "github.com/pingcap/tiflow/dm/syncer/safe-mode"
"github.com/pingcap/tiflow/dm/syncer/shardddl"
"github.com/pingcap/tiflow/pkg/errorutil"
"github.com/pingcap/tiflow/pkg/sqlmodel"
)
var (
waitTime = 10 * time.Millisecond
// MaxDDLConnectionTimeoutMinute also used by SubTask.ExecuteDDL.
MaxDDLConnectionTimeoutMinute = 5
maxDMLConnectionTimeout = "5m"
maxDDLConnectionTimeout = fmt.Sprintf("%dm", MaxDDLConnectionTimeoutMinute)
maxDMLConnectionDuration, _ = time.ParseDuration(maxDMLConnectionTimeout)
defaultMaxPauseOrStopWaitTime = 10 * time.Second
adminQueueName = "admin queue"
defaultBucketCount = 8
)
// BinlogType represents binlog sync type.
type BinlogType uint8
// binlog sync type.
const (
RemoteBinlog BinlogType = iota + 1
LocalBinlog
)
const (
skipJobIdx = iota
ddlJobIdx
workerJobTSArrayInitSize // size = skip + ddl
)
// waitXIDStatus represents the status for waiting XID event when pause/stop task.
type waitXIDStatus int64
const (
noWait waitXIDStatus = iota
waiting
waitComplete
)
// Syncer can sync your MySQL data to another MySQL database.
type Syncer struct {
sync.RWMutex
tctx *tcontext.Context // this ctx only used for logger.
// this ctx derives from a background ctx and was initialized in s.Run, it is used for some background tasks in s.Run
// when this ctx cancelled, syncer will shutdown all background running jobs (except the syncDML and syncDDL) and not wait transaction end.
runCtx *tcontext.Context
runCancel context.CancelFunc
// this ctx only used for syncDML and syncDDL and only cancelled when ungraceful stop.
syncCtx *tcontext.Context
syncCancel context.CancelFunc
// control all goroutines that started in S.Run
runWg sync.WaitGroup
cfg *config.SubTaskConfig
syncCfg replication.BinlogSyncerConfig
cliArgs *config.TaskCliArgs
sgk *ShardingGroupKeeper // keeper to keep all sharding (sub) group in this syncer
osgk *OptShardingGroupKeeper // optimistic ddl's keeper to keep all sharding (sub) group in this syncer
pessimist *shardddl.Pessimist // shard DDL pessimist
optimist *shardddl.Optimist // shard DDL optimist
cli *clientv3.Client
binlogType BinlogType
streamerController *StreamerController
jobWg sync.WaitGroup // counts ddl/flush/asyncFlush job in-flight in s.dmlJobCh and s.ddlJobCh
schemaTracker *schema.Tracker
fromDB *dbconn.UpStreamConn
fromConn *dbconn.DBConn
toDB *conn.BaseDB
toDBConns []*dbconn.DBConn
ddlDB *conn.BaseDB
ddlDBConn *dbconn.DBConn
downstreamTrackConn *dbconn.DBConn
dmlJobCh chan *job
ddlJobCh chan *job
jobsClosed atomic.Bool
jobsChanLock sync.Mutex
waitXIDJob atomic.Int64
isTransactionEnd bool
waitTransactionLock sync.Mutex
tableRouter *regexprrouter.RouteTable
binlogFilter *bf.BinlogEvent
columnMapping *cm.Mapping
baList *filter.Filter
exprFilterGroup *ExprFilterGroup
sessCtx sessionctx.Context
running atomic.Bool
closed atomic.Bool
start atomic.Time
lastTime atomic.Time
// safeMode is used to track if we need to generate dml with safe-mode
// For each binlog event, we will set the current value into eventContext because
// the status of this track may change over time.
safeMode *sm.SafeMode
timezone *time.Location
binlogSizeCount atomic.Int64
lastBinlogSizeCount atomic.Int64
lastCount atomic.Int64
count atomic.Int64
totalTps atomic.Int64
tps atomic.Int64
filteredInsert atomic.Int64
filteredUpdate atomic.Int64
filteredDelete atomic.Int64
checkpoint CheckPoint
checkpointFlushWorker *checkpointFlushWorker
onlineDDL onlineddl.OnlinePlugin
// record process error rather than log.Fatal
runFatalChan chan *pb.ProcessError
// record whether error occurred when execute SQLs
execError atomic.Error
readerHub *streamer.ReaderHub
recordedActiveRelayLog bool
errOperatorHolder *operator.Holder
isReplacingOrInjectingErr bool // true if we are in replace or inject events by handle-error
currentLocationMu struct {
sync.RWMutex
currentLocation binlog.Location // use to calc remain binlog size
}
errLocation struct {
sync.RWMutex
startLocation *binlog.Location
endLocation *binlog.Location
isQueryEvent bool
}
handleJobFunc func(*job) (bool, error)
flushSeq int64
// `lower_case_table_names` setting of upstream db
SourceTableNamesFlavor utils.LowerCaseTableNamesFlavor
tsOffset atomic.Int64 // time offset between upstream and syncer, DM's timestamp - MySQL's timestamp
secondsBehindMaster atomic.Int64 // current task delay second behind upstream
workerJobTSArray []*atomic.Int64 // worker's sync job TS array, note that idx=0 is skip idx and idx=1 is ddl idx,sql worker job idx=(queue id + 2)
lastCheckpointFlushedTime time.Time
firstMeetBinlogTS *int64
exitSafeModeTS *int64 // TS(in binlog header) need to exit safe mode.
locations *locationRecorder
// initial executed binlog location, set once for each instance of syncer.
initExecutedLoc *binlog.Location
relay relay.Process
charsetAndDefaultCollation map[string]string
idAndCollationMap map[int]string
}
// NewSyncer creates a new Syncer.
func NewSyncer(cfg *config.SubTaskConfig, etcdClient *clientv3.Client, relay relay.Process) *Syncer {
logger := log.With(zap.String("task", cfg.Name), zap.String("unit", "binlog replication"))
syncer := &Syncer{
pessimist: shardddl.NewPessimist(&logger, etcdClient, cfg.Name, cfg.SourceID),
optimist: shardddl.NewOptimist(&logger, etcdClient, cfg.Name, cfg.SourceID),
}
syncer.cfg = cfg
syncer.tctx = tcontext.Background().WithLogger(logger)
syncer.jobsClosed.Store(true) // not open yet
syncer.waitXIDJob.Store(int64(noWait))
syncer.isTransactionEnd = true
syncer.closed.Store(false)
syncer.lastBinlogSizeCount.Store(0)
syncer.binlogSizeCount.Store(0)
syncer.lastCount.Store(0)
syncer.count.Store(0)
syncer.handleJobFunc = syncer.handleJob
syncer.cli = etcdClient
syncer.checkpoint = NewRemoteCheckPoint(syncer.tctx, cfg, syncer.checkpointID())
syncer.binlogType = toBinlogType(relay)
syncer.errOperatorHolder = operator.NewHolder(&logger)
syncer.readerHub = streamer.GetReaderHub()
if cfg.ShardMode == config.ShardPessimistic {
// only need to sync DDL in sharding mode
syncer.sgk = NewShardingGroupKeeper(syncer.tctx, cfg)
} else if cfg.ShardMode == config.ShardOptimistic {
syncer.osgk = NewOptShardingGroupKeeper(syncer.tctx, cfg)
}
syncer.recordedActiveRelayLog = false
syncer.workerJobTSArray = make([]*atomic.Int64, cfg.WorkerCount+workerJobTSArrayInitSize)
for i := range syncer.workerJobTSArray {
syncer.workerJobTSArray[i] = atomic.NewInt64(0)
}
syncer.lastCheckpointFlushedTime = time.Time{}
syncer.relay = relay
syncer.locations = &locationRecorder{}
return syncer
}
func (s *Syncer) refreshCliArgs() {
if s.cli == nil {
// for dummy syncer in ut
return
}
cliArgs, err := ha.GetTaskCliArgs(s.cli, s.cfg.Name, s.cfg.SourceID)
if err != nil {
s.tctx.L().Error("failed to get task cli args", zap.Error(err))
}
s.Lock()
s.cliArgs = cliArgs
s.Unlock()
}
func (s *Syncer) newJobChans() {
chanSize := calculateChanSize(s.cfg.QueueSize, s.cfg.WorkerCount, s.cfg.Compact)
s.dmlJobCh = make(chan *job, chanSize)
s.ddlJobCh = make(chan *job, s.cfg.QueueSize)
s.jobsClosed.Store(false)
}
func (s *Syncer) closeJobChans() {
s.jobsChanLock.Lock()
defer s.jobsChanLock.Unlock()
if s.jobsClosed.Load() {
return
}
close(s.dmlJobCh)
close(s.ddlJobCh)
s.jobsClosed.Store(true)
}
// Type implements Unit.Type.
func (s *Syncer) Type() pb.UnitType {
return pb.UnitType_Sync
}
// Init initializes syncer for a sync task, but not start Process.
// if fail, it should not call s.Close.
// some check may move to checker later.
func (s *Syncer) Init(ctx context.Context) (err error) {
rollbackHolder := fr.NewRollbackHolder("syncer")
defer func() {
if err != nil {
rollbackHolder.RollbackReverseOrder()
}
}()
tctx := s.tctx.WithContext(ctx)
s.timezone, err = str2TimezoneOrFromDB(tctx, s.cfg.Timezone, &s.cfg.To)
if err != nil {
return
}
s.syncCfg, err = subtaskCfg2BinlogSyncerCfg(s.cfg, s.timezone)
if err != nil {
return err
}
err = s.createDBs(ctx)
if err != nil {
return err
}
rollbackHolder.Add(fr.FuncRollback{Name: "close-DBs", Fn: s.closeDBs})
if s.cfg.CollationCompatible == config.StrictCollationCompatible {
s.charsetAndDefaultCollation, s.idAndCollationMap, err = dbconn.GetCharsetAndCollationInfo(tctx, s.fromConn)
if err != nil {
return err
}
}
s.streamerController = NewStreamerController(s.syncCfg, s.cfg.EnableGTID, s.fromDB, s.cfg.RelayDir, s.timezone, s.relay)
s.baList, err = filter.New(s.cfg.CaseSensitive, s.cfg.BAList)
if err != nil {
return terror.ErrSyncerUnitGenBAList.Delegate(err)
}
s.binlogFilter, err = bf.NewBinlogEvent(s.cfg.CaseSensitive, s.cfg.FilterRules)
if err != nil {
return terror.ErrSyncerUnitGenBinlogEventFilter.Delegate(err)
}
vars := map[string]string{
"time_zone": s.timezone.String(),
}
s.sessCtx = utils.NewSessionCtx(vars)
s.exprFilterGroup = NewExprFilterGroup(s.sessCtx, s.cfg.ExprFilter)
if len(s.cfg.ColumnMappingRules) > 0 {
s.columnMapping, err = cm.NewMapping(s.cfg.CaseSensitive, s.cfg.ColumnMappingRules)
if err != nil {
return terror.ErrSyncerUnitGenColumnMapping.Delegate(err)
}
}
if s.cfg.OnlineDDL {
s.onlineDDL, err = onlineddl.NewRealOnlinePlugin(tctx, s.cfg)
if err != nil {
return err
}
rollbackHolder.Add(fr.FuncRollback{Name: "close-onlineDDL", Fn: s.closeOnlineDDL})
}
err = s.genRouter()
if err != nil {
return err
}
var schemaMap map[string]string
var tableMap map[string]map[string]string
if s.SourceTableNamesFlavor == utils.LCTableNamesSensitive {
// TODO: we should avoid call this function multi times
allTables, err1 := utils.FetchAllDoTables(ctx, s.fromDB.BaseDB.DB, s.baList)
if err1 != nil {
return err1
}
schemaMap, tableMap = buildLowerCaseTableNamesMap(allTables)
}
switch s.cfg.ShardMode {
case config.ShardPessimistic:
err = s.sgk.Init()
if err != nil {
return err
}
err = s.initShardingGroups(ctx, true)
if err != nil {
return err
}
rollbackHolder.Add(fr.FuncRollback{Name: "close-sharding-group-keeper", Fn: s.sgk.Close})
case config.ShardOptimistic:
if err = s.initOptimisticShardDDL(ctx); err != nil {
return err
}
}
err = s.checkpoint.Init(tctx)
if err != nil {
return err
}
rollbackHolder.Add(fr.FuncRollback{Name: "close-checkpoint", Fn: s.checkpoint.Close})
err = s.checkpoint.Load(tctx)
if err != nil {
return err
}
if s.SourceTableNamesFlavor == utils.LCTableNamesSensitive {
if err = s.checkpoint.CheckAndUpdate(ctx, schemaMap, tableMap); err != nil {
return err
}
if s.onlineDDL != nil {
if err = s.onlineDDL.CheckAndUpdate(s.tctx, schemaMap, tableMap); err != nil {
return err
}
}
}
// when Init syncer, set active relay log info
if s.cfg.Meta == nil || s.cfg.Meta.BinLogName != binlog.FakeBinlogName {
err = s.setInitActiveRelayLog(ctx)
if err != nil {
return err
}
rollbackHolder.Add(fr.FuncRollback{Name: "remove-active-realylog", Fn: s.removeActiveRelayLog})
}
s.reset()
return nil
}
// buildLowerCaseTableNamesMap build a lower case schema map and lower case table map for all tables
// Input: map of schema --> list of tables
// Output: schema names map: lower_case_schema_name --> schema_name
// tables names map: lower_case_schema_name --> lower_case_table_name --> table_name
// Note: the result will skip the schemas and tables that their lower_case_name are the same.
func buildLowerCaseTableNamesMap(tables map[string][]string) (map[string]string, map[string]map[string]string) {
schemaMap := make(map[string]string)
tablesMap := make(map[string]map[string]string)
lowerCaseSchemaSet := make(map[string]string)
for schema, tableNames := range tables {
lcSchema := strings.ToLower(schema)
// track if there are multiple schema names with the same lower case name.
// just skip this kind of schemas.
if rawSchema, ok := lowerCaseSchemaSet[lcSchema]; ok {
delete(schemaMap, lcSchema)
delete(tablesMap, lcSchema)
log.L().Warn("skip check schema with same lower case value",
zap.Strings("schemas", []string{schema, rawSchema}))
continue
}
lowerCaseSchemaSet[lcSchema] = schema
if lcSchema != schema {
schemaMap[lcSchema] = schema
}
tblsMap := make(map[string]string)
lowerCaseTableSet := make(map[string]string)
for _, tb := range tableNames {
lcTbl := strings.ToLower(tb)
if rawTbl, ok := lowerCaseTableSet[lcTbl]; ok {
delete(tblsMap, lcTbl)
log.L().Warn("skip check tables with same lower case value", zap.String("schema", schema),
zap.Strings("table", []string{tb, rawTbl}))
continue
}
if lcTbl != tb {
tblsMap[lcTbl] = tb
}
}
if len(tblsMap) > 0 {
tablesMap[lcSchema] = tblsMap
}
}
return schemaMap, tablesMap
}
// initShardingGroups initializes sharding groups according to source MySQL, filter rules and router rules
// NOTE: now we don't support modify router rules after task has started.
func (s *Syncer) initShardingGroups(ctx context.Context, needCheck bool) error {
// fetch tables from source and filter them
sourceTables, err := s.fromDB.FetchAllDoTables(ctx, s.baList)
if err != nil {
return err
}
// convert according to router rules
// target-ID -> source-IDs
mapper := make(map[string][]string, len(sourceTables))
for schema, tables := range sourceTables {
for _, table := range tables {
sourceTable := &filter.Table{Schema: schema, Name: table}
targetTable := s.route(sourceTable)
targetID := utils.GenTableID(targetTable)
sourceID := utils.GenTableID(sourceTable)
_, ok := mapper[targetID]
if !ok {
mapper[targetID] = make([]string, 0, len(tables))
}
mapper[targetID] = append(mapper[targetID], sourceID)
}
}
loadMeta, err2 := s.sgk.LoadShardMeta(s.cfg.Flavor, s.cfg.EnableGTID)
if err2 != nil {
return err2
}
if needCheck && s.SourceTableNamesFlavor == utils.LCTableNamesSensitive {
// try fix persistent data before init
schemaMap, tableMap := buildLowerCaseTableNamesMap(sourceTables)
if err2 = s.sgk.CheckAndFix(loadMeta, schemaMap, tableMap); err2 != nil {
return err2
}
}
// add sharding group
for targetID, sourceIDs := range mapper {
targetTable := utils.UnpackTableID(targetID)
_, _, _, _, err := s.sgk.AddGroup(targetTable, sourceIDs, loadMeta[targetID], false)
if err != nil {
return err
}
}
shardGroup := s.sgk.Groups()
s.tctx.L().Debug("initial sharding groups", zap.Int("shard group length", len(shardGroup)), zap.Reflect("shard group", shardGroup))
return nil
}
// IsFreshTask implements Unit.IsFreshTask.
func (s *Syncer) IsFreshTask(ctx context.Context) (bool, error) {
globalPoint := s.checkpoint.GlobalPoint()
tablePoint := s.checkpoint.TablePoint()
// doesn't have neither GTID nor binlog pos
return binlog.IsFreshPosition(globalPoint, s.cfg.Flavor, s.cfg.EnableGTID) && len(tablePoint) == 0, nil
}
func (s *Syncer) reset() {
if s.streamerController != nil {
s.streamerController.Close()
}
// create new job chans
s.newJobChans()
s.checkpointFlushWorker = &checkpointFlushWorker{
input: make(chan *checkpointFlushTask, 16),
cp: s.checkpoint,
execError: &s.execError,
afterFlushFn: s.afterFlushCheckpoint,
updateJobMetricsFn: s.updateJobMetrics,
}
s.execError.Store(nil)
s.setErrLocation(nil, nil, false)
s.isReplacingOrInjectingErr = false
s.waitXIDJob.Store(int64(noWait))
s.isTransactionEnd = true
s.flushSeq = 0
s.firstMeetBinlogTS = nil
s.exitSafeModeTS = nil
switch s.cfg.ShardMode {
case config.ShardPessimistic:
// every time start to re-sync from resume, we reset status to make it like a fresh syncing
s.sgk.ResetGroups()
s.pessimist.Reset()
case config.ShardOptimistic:
s.optimist.Reset()
}
}
func (s *Syncer) resetDBs(tctx *tcontext.Context) error {
var err error
for i := 0; i < len(s.toDBConns); i++ {
err = s.toDBConns[i].ResetConn(tctx)
if err != nil {
return terror.WithScope(err, terror.ScopeDownstream)
}
}
if s.onlineDDL != nil {
err = s.onlineDDL.ResetConn(tctx)
if err != nil {
return terror.WithScope(err, terror.ScopeDownstream)
}
}
if s.sgk != nil {
err = s.sgk.dbConn.ResetConn(tctx)
if err != nil {
return terror.WithScope(err, terror.ScopeDownstream)
}
}
err = s.ddlDBConn.ResetConn(tctx)
if err != nil {
return terror.WithScope(err, terror.ScopeDownstream)
}
err = s.downstreamTrackConn.ResetConn(tctx)
if err != nil {
return terror.WithScope(err, terror.ScopeDownstream)
}
err = s.checkpoint.ResetConn(tctx)
if err != nil {
return terror.WithScope(err, terror.ScopeDownstream)
}
return nil
}
// Process implements the dm.Unit interface.
func (s *Syncer) Process(ctx context.Context, pr chan pb.ProcessResult) {
metrics.SyncerExitWithErrorCounter.WithLabelValues(s.cfg.Name, s.cfg.SourceID).Add(0)
newCtx, cancel := context.WithCancel(ctx)
defer cancel()
// create new done chan
// use lock of Syncer to avoid Close while Process
s.Lock()
if s.isClosed() {
s.Unlock()
return
}
s.Unlock()
runFatalChan := make(chan *pb.ProcessError, s.cfg.WorkerCount+1)
s.runFatalChan = runFatalChan
var (
errs = make([]*pb.ProcessError, 0, 2)
errsMu sync.Mutex
)
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
for {
err, ok := <-runFatalChan
if !ok {
return
}
cancel() // cancel s.Run
metrics.SyncerExitWithErrorCounter.WithLabelValues(s.cfg.Name, s.cfg.SourceID).Inc()
errsMu.Lock()
errs = append(errs, err)
errsMu.Unlock()
}
}()
wg.Add(1)
go func() {
defer wg.Done()
<-newCtx.Done() // ctx or newCtx
}()
err := s.Run(newCtx)
if err != nil {
// returned error rather than sent to runFatalChan
// cancel goroutines created in s.Run
cancel()
}
close(runFatalChan) // Run returned, all potential fatal sent to s.runFatalChan
wg.Wait() // wait for receive all fatal from s.runFatalChan
if err != nil {
if utils.IsContextCanceledError(err) {
s.tctx.L().Info("filter out error caused by user cancel", log.ShortError(err))
} else {
s.tctx.L().Debug("unit syncer quits with error", zap.Error(err))
metrics.SyncerExitWithErrorCounter.WithLabelValues(s.cfg.Name, s.cfg.SourceID).Inc()
errsMu.Lock()
errs = append(errs, unit.NewProcessError(err))
errsMu.Unlock()
}
}
isCanceled := false
select {
case <-ctx.Done():
isCanceled = true
default:
}
pr <- pb.ProcessResult{
IsCanceled: isCanceled,
Errors: errs,
}
}
func (s *Syncer) getTableInfo(tctx *tcontext.Context, sourceTable, targetTable *filter.Table) (*model.TableInfo, error) {
ti, err := s.schemaTracker.GetTableInfo(sourceTable)
if err == nil {
return ti, nil
}
if !schema.IsTableNotExists(err) {
return nil, terror.ErrSchemaTrackerCannotGetTable.Delegate(err, sourceTable)
}
if err = s.schemaTracker.CreateSchemaIfNotExists(sourceTable.Schema); err != nil {
return nil, terror.ErrSchemaTrackerCannotCreateSchema.Delegate(err, sourceTable.Schema)
}
// if the table does not exist (IsTableNotExists(err)), continue to fetch the table from downstream and create it.
err = s.trackTableInfoFromDownstream(tctx, sourceTable, targetTable)
if err != nil {
return nil, err
}
ti, err = s.schemaTracker.GetTableInfo(sourceTable)
if err != nil {
return nil, terror.ErrSchemaTrackerCannotGetTable.Delegate(err, sourceTable)
}
return ti, nil
}
// trackTableInfoFromDownstream tries to track the table info from the downstream. It will not overwrite existing table.
func (s *Syncer) trackTableInfoFromDownstream(tctx *tcontext.Context, sourceTable, targetTable *filter.Table) error {
// TODO: Switch to use the HTTP interface to retrieve the TableInfo directly if HTTP port is available
// use parser for downstream.
parser2, err := dbconn.GetParserForConn(tctx, s.ddlDBConn)
if err != nil {
return terror.ErrSchemaTrackerCannotParseDownstreamTable.Delegate(err, targetTable, sourceTable)
}
createSQL, err := dbconn.GetTableCreateSQL(tctx, s.ddlDBConn, targetTable.String())
if err != nil {
return terror.ErrSchemaTrackerCannotFetchDownstreamTable.Delegate(err, targetTable, sourceTable)
}
// rename the table back to original.
var createNode ast.StmtNode
createNode, err = parser2.ParseOneStmt(createSQL, "", "")
if err != nil {
return terror.ErrSchemaTrackerCannotParseDownstreamTable.Delegate(err, targetTable, sourceTable)
}
createStmt := createNode.(*ast.CreateTableStmt)
createStmt.IfNotExists = true
createStmt.Table.Schema = model.NewCIStr(sourceTable.Schema)
createStmt.Table.Name = model.NewCIStr(sourceTable.Name)
// schema tracker sets non-clustered index, so can't handle auto_random.
if v, _ := s.schemaTracker.GetSystemVar(schema.TiDBClusteredIndex); v == "OFF" {
for _, col := range createStmt.Cols {
for i, opt := range col.Options {
if opt.Tp == ast.ColumnOptionAutoRandom {
// col.Options is unordered
col.Options[i] = col.Options[len(col.Options)-1]
col.Options = col.Options[:len(col.Options)-1]
break
}
}
}
}
var newCreateSQLBuilder strings.Builder
restoreCtx := format.NewRestoreCtx(format.DefaultRestoreFlags, &newCreateSQLBuilder)
if err = createStmt.Restore(restoreCtx); err != nil {
return terror.ErrSchemaTrackerCannotParseDownstreamTable.Delegate(err, targetTable, sourceTable)
}
newCreateSQL := newCreateSQLBuilder.String()
tctx.L().Debug("reverse-synchronized table schema",
zap.Stringer("sourceTable", sourceTable),
zap.Stringer("targetTable", targetTable),
zap.String("sql", newCreateSQL),
)
if err = s.schemaTracker.Exec(tctx.Ctx, sourceTable.Schema, newCreateSQL); err != nil {
return terror.ErrSchemaTrackerCannotCreateTable.Delegate(err, sourceTable)
}
return nil
}
var dmlMetric = map[sqlmodel.RowChangeType]string{
sqlmodel.RowChangeInsert: "insert",
sqlmodel.RowChangeUpdate: "update",
sqlmodel.RowChangeDelete: "delete",
}
func (s *Syncer) updateJobMetrics(isFinished bool, queueBucket string, j *job) {
tp := j.tp
targetTable := j.targetTable
count := 1
if tp == ddl {
count = len(j.ddls)
}
m := metrics.AddedJobsTotal
if isFinished {
s.count.Add(int64(count))
m = metrics.FinishedJobsTotal
}
switch tp {
case dml:
m.WithLabelValues(dmlMetric[j.dml.Type()], s.cfg.Name, queueBucket, s.cfg.SourceID, s.cfg.WorkerName, targetTable.Schema, targetTable.Name).Add(float64(count))
case ddl, flush, asyncFlush, conflict, compact:
m.WithLabelValues(tp.String(), s.cfg.Name, queueBucket, s.cfg.SourceID, s.cfg.WorkerName, targetTable.Schema, targetTable.Name).Add(float64(count))
case skip, xid:
// ignore skip/xid jobs
default:
s.tctx.L().Warn("unknown job operation type", zap.Stringer("type", j.tp))
}
}
func (s *Syncer) calcReplicationLag(headerTS int64) int64 {
return time.Now().Unix() - s.tsOffset.Load() - headerTS
}
// updateReplicationJobTS store job TS, it is called after every batch dml job / one skip job / one ddl job is added and committed.
func (s *Syncer) updateReplicationJobTS(job *job, jobIdx int) {
// when job is nil mean no job in this bucket, need do reset this bucket job ts to 0
if job == nil {
s.workerJobTSArray[jobIdx].Store(0)
} else {
s.workerJobTSArray[jobIdx].Store(int64(job.eventHeader.Timestamp))
}
}
func (s *Syncer) updateReplicationLagMetric() {
var lag int64
var minTS int64
for idx := range s.workerJobTSArray {
if ts := s.workerJobTSArray[idx].Load(); ts != int64(0) {
if minTS == int64(0) || ts < minTS {
minTS = ts
}
}
}
if minTS != int64(0) {
lag = s.calcReplicationLag(minTS)
}
metrics.ReplicationLagHistogram.WithLabelValues(s.cfg.Name, s.cfg.SourceID, s.cfg.WorkerName).Observe(float64(lag))
metrics.ReplicationLagGauge.WithLabelValues(s.cfg.Name, s.cfg.SourceID, s.cfg.WorkerName).Set(float64(lag))
s.secondsBehindMaster.Store(lag)
failpoint.Inject("ShowLagInLog", func(v failpoint.Value) {
minLag := v.(int)
if int(lag) >= minLag {
s.tctx.L().Info("ShowLagInLog", zap.Int64("lag", lag))
}
})
// reset skip job TS in case of skip job TS is never updated
if minTS == s.workerJobTSArray[skipJobIdx].Load() {
s.workerJobTSArray[skipJobIdx].Store(0)
}
}
func (s *Syncer) saveTablePoint(table *filter.Table, location binlog.Location) {
ti, err := s.schemaTracker.GetTableInfo(table)
if err != nil && table.Name != "" {
// TODO: if we RENAME tb1 TO tb2, the tracker will remove TableInfo of tb1 but we still save the table
// checkpoint for tb1. We can delete the table checkpoint in future.
s.tctx.L().Warn("table info missing from schema tracker",
zap.Stringer("table", table),
zap.Stringer("location", location),
zap.Error(err))
}
s.checkpoint.SaveTablePoint(table, location, ti)
}
// only used in tests.
var (
lastLocationForTest binlog.Location
lastLocationNumForTest int
waitJobsDoneForTest bool
failExecuteSQLForTest bool
failOnceForTest atomic.Bool
waitBeforeRunExitDurationForTest time.Duration
)
// TODO: move to syncer/job.go
// addJob adds one job to DML queue or DDL queue according to its type.
// Caller should prepare all needed jobs before calling this function, addJob should not generate any new jobs.
// There should not be a second way to send jobs to DML queue or DDL queue.
func (s *Syncer) addJob(job *job) {
failpoint.Inject("countJobFromOneEvent", func() {
if job.tp == dml {
if job.currentLocation.Position.Compare(lastLocationForTest.Position) == 0 {
lastLocationNumForTest++
} else {
lastLocationForTest = job.currentLocation
lastLocationNumForTest = 1
}
// trigger a flush after see one job
if lastLocationNumForTest == 1 {
waitJobsDoneForTest = true
s.tctx.L().Info("meet the first job of an event", zap.Any("binlog position", lastLocationForTest))
}
// mock a execution error after see two jobs.
if lastLocationNumForTest == 2 {
failExecuteSQLForTest = true
s.tctx.L().Info("meet the second job of an event", zap.Any("binlog position", lastLocationForTest))
}
}
})
failpoint.Inject("countJobFromOneGTID", func() {
if job.tp == dml {
if binlog.CompareLocation(job.currentLocation, lastLocationForTest, true) == 0 {
lastLocationNumForTest++
} else {
lastLocationForTest = job.currentLocation
lastLocationNumForTest = 1
}
// trigger a flush after see one job
if lastLocationNumForTest == 1 {
waitJobsDoneForTest = true
s.tctx.L().Info("meet the first job of a GTID", zap.Any("binlog position", lastLocationForTest))
}
// mock a execution error after see two jobs.
if lastLocationNumForTest == 2 {
failExecuteSQLForTest = true
s.tctx.L().Info("meet the second job of a GTID", zap.Any("binlog position", lastLocationForTest))
}
}
})
// avoid job.type data race with compactor.run()
// simply copy the opType for performance, though copy a new job in compactor is better
tp := job.tp
switch tp {
case flush:
s.jobWg.Add(1)
s.dmlJobCh <- job
case asyncFlush:
s.jobWg.Add(1)
s.dmlJobCh <- job
case ddl:
s.updateJobMetrics(false, adminQueueName, job)
s.jobWg.Add(1)
startTime := time.Now()
s.ddlJobCh <- job
metrics.AddJobDurationHistogram.WithLabelValues("ddl", s.cfg.Name, adminQueueName, s.cfg.SourceID).Observe(time.Since(startTime).Seconds())
case dml:
failpoint.Inject("SkipDML", func(val failpoint.Value) {
// first col should be an int and primary key, every row with pk <= val will be skipped
skippedIDUpperBound := val.(int)
firstColVal, _ := strconv.Atoi(fmt.Sprintf("%v", job.dml.RowValues()[0]))
if firstColVal <= skippedIDUpperBound {
failpoint.Goto("skip_dml")
}
})
s.dmlJobCh <- job
failpoint.Label("skip_dml")
failpoint.Inject("checkCheckpointInMiddleOfTransaction", func() {
s.tctx.L().Info("receive dml job", zap.Any("dml job", job))
time.Sleep(500 * time.Millisecond)
})
case gc:
s.dmlJobCh <- job
default:
s.tctx.L().DPanic("unhandled job type", zap.Stringer("job", job))
}
}
// flushIfOutdated checks whether syncer should flush now because last flushing is outdated.
func (s *Syncer) flushIfOutdated() error {
if !s.checkpoint.LastFlushOutdated() {
return nil