This repository has been archived by the owner on Nov 24, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 188
/
syncer.go
3386 lines (3000 loc) · 114 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"
"crypto/tls"
"fmt"
"os"
"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"
"github.com/pingcap/parser"
"github.com/pingcap/parser/ast"
"github.com/pingcap/parser/format"
"github.com/pingcap/parser/model"
bf "github.com/pingcap/tidb-tools/pkg/binlog-filter"
cm "github.com/pingcap/tidb-tools/pkg/column-mapping"
"github.com/pingcap/tidb-tools/pkg/dbutil"
"github.com/pingcap/tidb-tools/pkg/filter"
router "github.com/pingcap/tidb-tools/pkg/table-router"
toolutils "github.com/pingcap/tidb-tools/pkg/utils"
"go.etcd.io/etcd/clientv3"
"go.uber.org/atomic"
"go.uber.org/zap"
"github.com/pingcap/dm/dm/config"
common2 "github.com/pingcap/dm/dm/ctl/common"
"github.com/pingcap/dm/dm/pb"
"github.com/pingcap/dm/dm/unit"
"github.com/pingcap/dm/pkg/binlog"
"github.com/pingcap/dm/pkg/binlog/common"
"github.com/pingcap/dm/pkg/binlog/event"
"github.com/pingcap/dm/pkg/binlog/reader"
"github.com/pingcap/dm/pkg/conn"
tcontext "github.com/pingcap/dm/pkg/context"
fr "github.com/pingcap/dm/pkg/func-rollback"
"github.com/pingcap/dm/pkg/gtid"
"github.com/pingcap/dm/pkg/ha"
"github.com/pingcap/dm/pkg/log"
parserpkg "github.com/pingcap/dm/pkg/parser"
"github.com/pingcap/dm/pkg/schema"
"github.com/pingcap/dm/pkg/shardddl/pessimism"
"github.com/pingcap/dm/pkg/streamer"
"github.com/pingcap/dm/pkg/terror"
"github.com/pingcap/dm/pkg/utils"
"github.com/pingcap/dm/syncer/dbconn"
operator "github.com/pingcap/dm/syncer/err-operator"
"github.com/pingcap/dm/syncer/metrics"
onlineddl "github.com/pingcap/dm/syncer/online-ddl-tools"
sm "github.com/pingcap/dm/syncer/safe-mode"
"github.com/pingcap/dm/syncer/shardddl"
)
var (
maxRetryCount = 100
retryTimeout = 3 * time.Second
waitTime = 10 * time.Millisecond
statusTime = 30 * time.Second
// MaxDDLConnectionTimeoutMinute also used by SubTask.ExecuteDDL.
MaxDDLConnectionTimeoutMinute = 5
maxDMLConnectionTimeout = "5m"
maxDDLConnectionTimeout = fmt.Sprintf("%dm", MaxDDLConnectionTimeoutMinute)
maxDMLConnectionDuration, _ = time.ParseDuration(maxDMLConnectionTimeout)
maxDMLExecutionDuration = 30 * time.Second
adminQueueName = "admin queue"
defaultBucketCount = 8
)
// BinlogType represents binlog sync type.
type BinlogType uint8
// binlog sync type.
const (
RemoteBinlog BinlogType = iota + 1
LocalBinlog
skipLagKey = "skip"
ddlLagKey = "ddl"
)
// Syncer can sync your MySQL data to another MySQL database.
type Syncer struct {
sync.RWMutex
tctx *tcontext.Context
cfg *config.SubTaskConfig
syncCfg replication.BinlogSyncerConfig
sgk *ShardingGroupKeeper // 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
enableRelay bool
wg sync.WaitGroup
jobWg sync.WaitGroup
schemaTracker *schema.Tracker
fromDB *UpStreamConn
toDB *conn.BaseDB
toDBConns []*dbconn.DBConn
ddlDB *conn.BaseDB
ddlDBConn *dbconn.DBConn
jobs []chan *job
jobsClosed atomic.Bool
jobsChanLock sync.Mutex
queueBucketMapping []string
c *causality
tableRouter *router.Table
binlogFilter *bf.BinlogEvent
columnMapping *cm.Mapping
baList *filter.Filter
exprFilterGroup *ExprFilterGroup
closed atomic.Bool
start time.Time
lastTime struct {
sync.RWMutex
t time.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
done chan struct{}
checkpoint CheckPoint
onlineDDL onlineddl.OnlinePlugin
// record process error rather than log.Fatal
runFatalChan chan *pb.ProcessError
// record whether error occurred when execute SQLs
execError atomic.Error
heartbeat *Heartbeat
readerHub *streamer.ReaderHub
recordedActiveRelayLog bool
errOperatorHolder *operator.Holder
isReplacingErr bool // true if we are in replace 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
}
addJobFunc func(*job) error
// `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
workerLagMap map[string]*atomic.Int64 // worker's sync lag key:WorkerLagKey val: lag
}
// NewSyncer creates a new Syncer.
func NewSyncer(cfg *config.SubTaskConfig, etcdClient *clientv3.Client) *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.closed.Store(false)
syncer.lastBinlogSizeCount.Store(0)
syncer.binlogSizeCount.Store(0)
syncer.lastCount.Store(0)
syncer.count.Store(0)
syncer.c = newCausality()
syncer.done = nil
syncer.setTimezone()
syncer.addJobFunc = syncer.addJob
syncer.enableRelay = cfg.UseRelay
syncer.cli = etcdClient
syncer.checkpoint = NewRemoteCheckPoint(syncer.tctx, cfg, syncer.checkpointID())
syncer.binlogType = toBinlogType(cfg.UseRelay)
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)
}
syncer.recordedActiveRelayLog = false
syncer.workerLagMap = make(map[string]*atomic.Int64, cfg.WorkerCount+2) // map size = WorkerCount + ddlkey + skipkey
return syncer
}
// GetSecondsBehindMaster returns secondsBehindMaster.
func (s *Syncer) GetSecondsBehindMaster() int64 {
return s.secondsBehindMaster.Load()
}
func (s *Syncer) newJobChans(count int) {
s.closeJobChans()
s.jobs = make([]chan *job, 0, count)
for i := 0; i < count; i++ {
s.jobs = append(s.jobs, 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
}
for _, ch := range s.jobs {
close(ch)
}
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)
err = s.setSyncCfg()
if err != nil {
return err
}
err = s.createDBs(ctx)
if err != nil {
return err
}
rollbackHolder.Add(fr.FuncRollback{Name: "close-DBs", Fn: s.closeDBs})
s.schemaTracker, err = schema.NewTracker(ctx, s.cfg.Name, s.cfg.To.Session, s.ddlDBConn.BaseConn)
if err != nil {
return terror.ErrSchemaTrackerInit.Delegate(err)
}
s.streamerController = NewStreamerController(s.syncCfg, s.cfg.EnableGTID, s.fromDB, s.binlogType, s.cfg.RelayDir, s.timezone)
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)
}
s.exprFilterGroup = NewExprFilterGroup(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
}
}
}
if s.cfg.EnableHeartbeat {
s.heartbeat, err = GetHeartbeat(&HeartbeatConfig{
serverID: s.cfg.ServerID,
primaryCfg: s.cfg.From,
updateInterval: int64(s.cfg.HeartbeatUpdateInterval),
reportInterval: int64(s.cfg.HeartbeatReportInterval),
})
if err != nil {
return err
}
err = s.heartbeat.AddTask(s.cfg.Name)
if err != nil {
return err
}
rollbackHolder.Add(fr.FuncRollback{Name: "remove-heartbeat", Fn: s.removeHeartbeat})
}
// when Init syncer, set active relay log info
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-schema -> target-table -> source-IDs
mapper := make(map[string]map[string][]string, len(sourceTables))
for schema, tables := range sourceTables {
for _, table := range tables {
targetSchema, targetTable := s.renameShardingSchema(schema, table)
mSchema, ok := mapper[targetSchema]
if !ok {
mapper[targetSchema] = make(map[string][]string, len(tables))
mSchema = mapper[targetSchema]
}
_, ok = mSchema[targetTable]
if !ok {
mSchema[targetTable] = make([]string, 0, len(tables))
}
ID, _ := utils.GenTableID(schema, table)
mSchema[targetTable] = append(mSchema[targetTable], ID)
}
}
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 targetSchema, mSchema := range mapper {
for targetTable, sourceIDs := range mSchema {
tableID, _ := utils.GenTableID(targetSchema, targetTable)
_, _, _, _, err := s.sgk.AddGroup(targetSchema, targetTable, sourceIDs, loadMeta[tableID], 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(s.tctx)
}
// create new job chans
s.newJobChans(s.cfg.WorkerCount + 1)
s.execError.Store(nil)
s.setErrLocation(nil, nil, false)
s.isReplacingErr = false
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.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.done = make(chan struct{})
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()
}
s.closeJobChans() // Run returned, all jobs sent, we can close s.jobs
s.wg.Wait() // wait for sync goroutine to return
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")
} else {
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:
}
if len(errs) != 0 {
// pause because of error occurred
s.Pause()
}
// try to rollback checkpoints, if they already flushed, no effect
prePos := s.checkpoint.GlobalPoint()
s.checkpoint.Rollback(s.schemaTracker)
currPos := s.checkpoint.GlobalPoint()
if binlog.CompareLocation(prePos, currPos, s.cfg.EnableGTID) != 0 {
s.tctx.L().Warn("something wrong with rollback global checkpoint", zap.Stringer("previous position", prePos), zap.Stringer("current position", currPos))
}
pr <- pb.ProcessResult{
IsCanceled: isCanceled,
Errors: errs,
}
}
func (s *Syncer) getMasterStatus(ctx context.Context) (mysql.Position, gtid.Set, error) {
return s.fromDB.getMasterStatus(ctx, s.cfg.Flavor)
}
func (s *Syncer) getTable(tctx *tcontext.Context, origSchema, origTable, renamedSchema, renamedTable string) (*model.TableInfo, error) {
ti, err := s.schemaTracker.GetTable(origSchema, origTable)
if err == nil {
return ti, nil
}
if !schema.IsTableNotExists(err) {
return nil, terror.ErrSchemaTrackerCannotGetTable.Delegate(err, origSchema, origTable)
}
if err = s.schemaTracker.CreateSchemaIfNotExists(origSchema); err != nil {
return nil, terror.ErrSchemaTrackerCannotCreateSchema.Delegate(err, origSchema)
}
// if table already exists in checkpoint, create it in schema tracker
if ti = s.checkpoint.GetFlushedTableInfo(origSchema, origTable); ti != nil {
if err = s.schemaTracker.CreateTableIfNotExists(origSchema, origTable, ti); err != nil {
return nil, terror.ErrSchemaTrackerCannotCreateTable.Delegate(err, origSchema, origTable)
}
tctx.L().Debug("lazy init table info in schema tracker", zap.String("schema", origSchema), zap.String("table", origTable))
return ti, nil
}
// in optimistic shard mode, we should try to get the init schema (the one before modified by other tables) first.
if s.cfg.ShardMode == config.ShardOptimistic {
ti, err = s.trackInitTableInfoOptimistic(origSchema, origTable, renamedSchema, renamedTable)
if err != nil {
return nil, err
}
}
// if the table does not exist (IsTableNotExists(err)), continue to fetch the table from downstream and create it.
if ti == nil {
err = s.trackTableInfoFromDownstream(tctx, origSchema, origTable, renamedSchema, renamedTable)
if err != nil {
return nil, err
}
}
ti, err = s.schemaTracker.GetTable(origSchema, origTable)
if err != nil {
return nil, terror.ErrSchemaTrackerCannotGetTable.Delegate(err, origSchema, origTable)
}
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, origSchema, origTable, renamedSchema, renamedTable string) error {
// TODO: Switch to use the HTTP interface to retrieve the TableInfo directly if HTTP port is available
// use parser for downstream.
parser2, err := utils.GetParserForConn(tctx.Ctx, s.ddlDBConn.BaseConn.DBConn)
if err != nil {
return terror.ErrSchemaTrackerCannotParseDownstreamTable.Delegate(err, renamedSchema, renamedTable, origSchema, origTable)
}
rows, err := s.ddlDBConn.QuerySQL(tctx, "SHOW CREATE TABLE "+dbutil.TableName(renamedSchema, renamedTable))
if err != nil {
return terror.ErrSchemaTrackerCannotFetchDownstreamTable.Delegate(err, renamedSchema, renamedTable, origSchema, origTable)
}
defer rows.Close()
for rows.Next() {
var tableName, createSQL string
if err = rows.Scan(&tableName, &createSQL); err != nil {
return terror.WithScope(terror.DBErrorAdapt(err, terror.ErrDBDriverError), terror.ScopeDownstream)
}
// rename the table back to original.
var createNode ast.StmtNode
createNode, err = parser2.ParseOneStmt(createSQL, "", "")
if err != nil {
return terror.ErrSchemaTrackerCannotParseDownstreamTable.Delegate(err, renamedSchema, renamedTable, origSchema, origTable)
}
createStmt := createNode.(*ast.CreateTableStmt)
createStmt.IfNotExists = true
createStmt.Table.Schema = model.NewCIStr(origSchema)
createStmt.Table.Name = model.NewCIStr(origTable)
// 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, renamedSchema, renamedTable, origSchema, origTable)
}
newCreateSQL := newCreateSQLBuilder.String()
tctx.L().Debug("reverse-synchronized table schema",
zap.String("origSchema", origSchema),
zap.String("origTable", origTable),
zap.String("renamedSchema", renamedSchema),
zap.String("renamedTable", renamedTable),
zap.String("sql", newCreateSQL),
)
if err = s.schemaTracker.Exec(tctx.Ctx, origSchema, newCreateSQL); err != nil {
return terror.ErrSchemaTrackerCannotCreateTable.Delegate(err, origSchema, origTable)
}
}
if err = rows.Err(); err != nil {
return terror.WithScope(terror.DBErrorAdapt(err, terror.ErrDBDriverError), terror.ScopeDownstream)
}
return nil
}
func (s *Syncer) addCount(isFinished bool, queueBucket string, tp opType, n int64) {
m := metrics.AddedJobsTotal
if isFinished {
s.count.Add(n)
m = metrics.FinishedJobsTotal
}
switch tp {
case insert:
m.WithLabelValues("insert", s.cfg.Name, queueBucket, s.cfg.SourceID).Add(float64(n))
case update:
m.WithLabelValues("update", s.cfg.Name, queueBucket, s.cfg.SourceID).Add(float64(n))
case del:
m.WithLabelValues("del", s.cfg.Name, queueBucket, s.cfg.SourceID).Add(float64(n))
case ddl:
m.WithLabelValues("ddl", s.cfg.Name, queueBucket, s.cfg.SourceID).Add(float64(n))
case xid:
// ignore xid jobs
case flush:
m.WithLabelValues("flush", s.cfg.Name, queueBucket, s.cfg.SourceID).Add(float64(n))
case skip:
// ignore skip jobs
default:
s.tctx.L().Warn("unknown job operation type", zap.Stringer("type", tp))
}
}
func (s *Syncer) calcReplicationLag(headerTS int64) int64 {
return time.Now().Unix() - s.tsOffset.Load() - headerTS
}
// updateReplicationLag calculates syncer's replication lag by job, it is called after every batch dml job / one skip job / one ddl
// job is committed.
func (s *Syncer) updateReplicationLag(job *job, lagKey string) {
var lag int64
// when job is nil mean no job in this bucket, need do reset this bucket lag to 0
if job == nil {
s.workerLagMap[lagKey].Store(0)
} else {
failpoint.Inject("BlockSyncerUpdateLag", func(v failpoint.Value) {
args := strings.Split(v.(string), ",")
jtp := args[0] // job type
t, _ := strconv.Atoi(args[1]) // sleep time
if job.tp.String() == jtp {
s.tctx.L().Info("BlockSyncerUpdateLag", zap.String("job type", jtp), zap.Int("sleep time", t))
time.Sleep(time.Second * time.Duration(t))
}
})
switch job.tp {
case ddl, skip:
// NOTE: we handle ddl/skip job separately because ddl job will clean all the dml job before execution
lag = s.calcReplicationLag(int64(job.eventHeader.Timestamp))
default: // dml job
// NOTE workerlagmap already init all dml key(queueBucketName) before syncer running.
s.workerLagMap[lagKey].Store(s.calcReplicationLag(int64(job.eventHeader.Timestamp)))
}
}
// find all job queue lag choose the max one
for _, l := range s.workerLagMap {
if wl := l.Load(); wl > lag {
lag = wl
}
}
metrics.ReplicationLagGauge.WithLabelValues(s.cfg.Name).Set(float64(lag))
s.secondsBehindMaster.Store(lag)
}
func (s *Syncer) checkWait(job *job) bool {
if job.tp == ddl {
return true
}
if s.checkpoint.CheckGlobalPoint() {
return true
}
return false
}
func (s *Syncer) saveTablePoint(db, table string, location binlog.Location) {
ti, err := s.schemaTracker.GetTable(db, table)
if err != nil && table != "" {
s.tctx.L().DPanic("table info missing from schema tracker",
zap.String("schema", db),
zap.String("table", table),
zap.Stringer("location", location),
zap.Error(err))
}
s.checkpoint.SaveTablePoint(db, table, location, ti)
}
// only used in tests.
var (
lastPos mysql.Position
lastPosNum int
waitJobsDone bool
failExecuteSQL bool
failOnce atomic.Bool
)
func (s *Syncer) addJob(job *job) error {
failpoint.Inject("countJobFromOneEvent", func() {
if job.currentLocation.Position.Compare(lastPos) == 0 {
lastPosNum++
} else {
lastPos = job.currentLocation.Position
lastPosNum = 1
}
// trigger a flush after see one job
if lastPosNum == 1 {
waitJobsDone = true
s.tctx.L().Info("meet the first job of an event", zap.Any("binlog position", lastPos))
}
// mock a execution error after see two jobs.
if lastPosNum == 2 {
failExecuteSQL = true
s.tctx.L().Info("meet the second job of an event", zap.Any("binlog position", lastPos))
}
})
var queueBucket int
switch job.tp {
case xid:
s.saveGlobalPoint(job.location)
return nil
case skip:
s.updateReplicationLag(job, skipLagKey)
case flush:
metrics.AddedJobsTotal.WithLabelValues("flush", s.cfg.Name, adminQueueName, s.cfg.SourceID).Inc()
// ugly code addJob and sync, refine it later
s.jobWg.Add(s.cfg.WorkerCount)
for i := 0; i < s.cfg.WorkerCount; i++ {
startTime := time.Now()
s.jobs[i] <- job
// flush for every DML queue
metrics.AddJobDurationHistogram.WithLabelValues("flush", s.cfg.Name, s.queueBucketMapping[i], s.cfg.SourceID).Observe(time.Since(startTime).Seconds())
}
s.jobWg.Wait()
metrics.FinishedJobsTotal.WithLabelValues("flush", s.cfg.Name, adminQueueName, s.cfg.SourceID).Inc()
return s.flushCheckPoints()
case ddl:
s.jobWg.Wait()
metrics.AddedJobsTotal.WithLabelValues("ddl", s.cfg.Name, adminQueueName, s.cfg.SourceID).Inc()
s.jobWg.Add(1)
queueBucket = s.cfg.WorkerCount
startTime := time.Now()
s.jobs[queueBucket] <- job
metrics.AddJobDurationHistogram.WithLabelValues("ddl", s.cfg.Name, adminQueueName, s.cfg.SourceID).Observe(time.Since(startTime).Seconds())
case insert, update, del:
s.jobWg.Add(1)
queueBucket = int(utils.GenHashKey(job.key)) % s.cfg.WorkerCount
s.addCount(false, s.queueBucketMapping[queueBucket], job.tp, 1)
startTime := time.Now()
s.tctx.L().Debug("queue for key", zap.Int("queue", queueBucket), zap.String("key", job.key))
s.jobs[queueBucket] <- job
metrics.AddJobDurationHistogram.WithLabelValues(job.tp.String(), s.cfg.Name, s.queueBucketMapping[queueBucket], s.cfg.SourceID).Observe(time.Since(startTime).Seconds())
}
// nolint:ifshort
wait := s.checkWait(job)
failpoint.Inject("flushFirstJobOfEvent", func() {
if waitJobsDone {
s.tctx.L().Info("trigger flushFirstJobOfEvent")
waitJobsDone = false
wait = true
}
})
if wait {
s.jobWg.Wait()
s.c.reset()
}
if s.execError.Load() != nil {
// nolint:nilerr
return nil
}
switch job.tp {
case ddl:
failpoint.Inject("ExitAfterDDLBeforeFlush", func() {
s.tctx.L().Warn("exit triggered", zap.String("failpoint", "ExitAfterDDLBeforeFlush"))
utils.OsExit(1)
})
// interrupted after executed DDL and before save checkpoint.
failpoint.Inject("FlushCheckpointStage", func(val failpoint.Value) {
err := handleFlushCheckpointStage(3, val.(int), "before save checkpoint")
if err != nil {
failpoint.Return(err)
}
})
// only save checkpoint for DDL and XID (see above)
s.saveGlobalPoint(job.location)