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
/
Copy pathsyncer.go
2372 lines (2074 loc) · 76.5 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 (
"context"
"fmt"
"math"
"strconv"
"strings"
"sync"
"time"
"github.com/pingcap/errors"
"github.com/pingcap/failpoint"
"github.com/pingcap/parser"
"github.com/pingcap/parser/ast"
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"
"github.com/pingcap/tidb-tools/pkg/table-router"
"github.com/siddontang/go-mysql/mysql"
"github.com/siddontang/go-mysql/replication"
"github.com/siddontang/go/sync2"
"go.uber.org/zap"
"github.com/pingcap/dm/dm/config"
"github.com/pingcap/dm/dm/pb"
"github.com/pingcap/dm/dm/unit"
"github.com/pingcap/dm/pkg/binlog"
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/log"
"github.com/pingcap/dm/pkg/streamer"
"github.com/pingcap/dm/pkg/tracing"
"github.com/pingcap/dm/pkg/utils"
sm "github.com/pingcap/dm/syncer/safe-mode"
"github.com/pingcap/dm/syncer/sql-operator"
)
var (
maxRetryCount = 100
retryTimeout = 3 * time.Second
waitTime = 10 * time.Millisecond
eventTimeout = 1 * time.Minute
maxEventTimeout = 1 * time.Hour
statusTime = 30 * time.Second
// MaxDDLConnectionTimeoutMinute also used by SubTask.ExecuteDDL
MaxDDLConnectionTimeoutMinute = 10
maxDMLConnectionTimeout = "1m"
maxDDLConnectionTimeout = fmt.Sprintf("%dm", MaxDDLConnectionTimeoutMinute)
adminQueueName = "admin queue"
defaultBucketCount = 8
)
// BinlogType represents binlog sync type
type BinlogType uint8
// binlog sync type
const (
RemoteBinlog BinlogType = iota + 1
LocalBinlog
)
// Syncer can sync your MySQL data to another MySQL database.
type Syncer struct {
sync.RWMutex
tctx *tcontext.Context
cfg *config.SubTaskConfig
syncCfg replication.BinlogSyncerConfig
shardingSyncCfg replication.BinlogSyncerConfig // used by sharding group to re-consume DMLs
sgk *ShardingGroupKeeper // keeper to keep all sharding (sub) group in this syncer
ddlInfoCh chan *pb.DDLInfo // DDL info pending to sync, only support sync one DDL lock one time, refine if needed
ddlExecInfo *DDLExecInfo // DDL execute (ignore) info
injectEventCh chan *replication.BinlogEvent // extra binlog event chan, used to inject binlog event into the main for loop
// TODO: extract to interface?
syncer *replication.BinlogSyncer
localReader *streamer.BinlogReader
binlogType BinlogType
streamer streamer.Streamer
wg sync.WaitGroup
jobWg sync.WaitGroup
tables map[string]*table // table cache: `target-schema`.`target-table` -> table
cacheColumns map[string][]string // table columns cache: `target-schema`.`target-table` -> column names list
genColsCache *GenColCache
fromDB *Conn
toDBs []*Conn
ddlDB *Conn
jobs []chan *job
jobsClosed sync2.AtomicBool
jobsChanLock sync.Mutex
queueBucketMapping []string
c *causality
tableRouter *router.Table
binlogFilter *bf.BinlogEvent
columnMapping *cm.Mapping
bwList *filter.Filter
closed sync2.AtomicBool
start time.Time
lastTime struct {
sync.RWMutex
t time.Time
}
timezone *time.Location
binlogSizeCount sync2.AtomicInt64
lastBinlogSizeCount sync2.AtomicInt64
lastCount sync2.AtomicInt64
count sync2.AtomicInt64
totalTps sync2.AtomicInt64
tps sync2.AtomicInt64
done chan struct{}
checkpoint CheckPoint
onlineDDL OnlinePlugin
// record process error rather than log.Fatal
runFatalChan chan *pb.ProcessError
// record whether error occurred when execute SQLs
execErrorDetected sync2.AtomicBool
execErrors struct {
sync.Mutex
errors []*ExecErrorContext
}
sqlOperatorHolder *operator.Holder
heartbeat *Heartbeat
readerHub *streamer.ReaderHub
tracer *tracing.Tracer
currentPosMu struct {
sync.RWMutex
currentPos mysql.Position // use to calc remain binlog size
}
addJobFunc func(*job) error
}
// NewSyncer creates a new Syncer.
func NewSyncer(cfg *config.SubTaskConfig) *Syncer {
syncer := new(Syncer)
syncer.cfg = cfg
syncer.tctx = tcontext.Background().WithLogger(log.With(zap.String("task", cfg.Name), zap.String("unit", "binlog replication")))
syncer.jobsClosed.Set(true) // not open yet
syncer.closed.Set(false)
syncer.lastBinlogSizeCount.Set(0)
syncer.binlogSizeCount.Set(0)
syncer.lastCount.Set(0)
syncer.count.Set(0)
syncer.tables = make(map[string]*table)
syncer.cacheColumns = make(map[string][]string)
syncer.genColsCache = NewGenColCache()
syncer.c = newCausality()
syncer.done = make(chan struct{})
syncer.bwList = filter.New(cfg.CaseSensitive, cfg.BWList)
syncer.injectEventCh = make(chan *replication.BinlogEvent)
syncer.tracer = tracing.GetTracer()
syncer.setTimezone()
syncer.addJobFunc = syncer.addJob
syncer.checkpoint = NewRemoteCheckPoint(syncer.tctx, cfg, syncer.checkpointID())
syncer.syncCfg = replication.BinlogSyncerConfig{
ServerID: uint32(syncer.cfg.ServerID),
Flavor: syncer.cfg.Flavor,
Host: syncer.cfg.From.Host,
Port: uint16(syncer.cfg.From.Port),
User: syncer.cfg.From.User,
Password: syncer.cfg.From.Password,
UseDecimal: true,
VerifyChecksum: true,
TimestampStringLocation: syncer.timezone,
}
syncer.binlogType = toBinlogType(cfg.BinlogType)
syncer.sqlOperatorHolder = operator.NewHolder()
syncer.readerHub = streamer.GetReaderHub()
if cfg.IsSharding {
// only need to sync DDL in sharding mode
// for sharding group's config, we should use a different ServerID
// now, use 2**32 -1 - config's ServerID simply
// maybe we can refactor to remove RemoteBinlog support in DM
syncer.shardingSyncCfg = syncer.syncCfg
syncer.shardingSyncCfg.ServerID = math.MaxUint32 - syncer.syncCfg.ServerID
syncer.sgk = NewShardingGroupKeeper(syncer.tctx, cfg)
syncer.ddlInfoCh = make(chan *pb.DDLInfo, 1)
syncer.ddlExecInfo = NewDDLExecInfo()
}
return syncer
}
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, 1000))
}
s.jobsClosed.Set(false)
}
func (s *Syncer) closeJobChans() {
s.jobsChanLock.Lock()
defer s.jobsChanLock.Unlock()
if s.jobsClosed.Get() {
return
}
for _, ch := range s.jobs {
close(ch)
}
s.jobsClosed.Set(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() (err error) {
rollbackHolder := fr.NewRollbackHolder("syncer")
defer func() {
if err != nil {
rollbackHolder.RollbackReverseOrder()
}
}()
err = s.createDBs()
if err != nil {
return errors.Trace(err)
}
rollbackHolder.Add(fr.FuncRollback{Name: "close-DBs", Fn: s.closeDBs})
s.binlogFilter, err = bf.NewBinlogEvent(s.cfg.CaseSensitive, s.cfg.FilterRules)
if err != nil {
return errors.Trace(err)
}
if len(s.cfg.ColumnMappingRules) > 0 {
s.columnMapping, err = cm.NewMapping(s.cfg.CaseSensitive, s.cfg.ColumnMappingRules)
if err != nil {
return errors.Trace(err)
}
}
if s.cfg.OnlineDDLScheme != "" {
fn, ok := OnlineDDLSchemes[s.cfg.OnlineDDLScheme]
if !ok {
return errors.NotSupportedf("online ddl scheme (%s)", s.cfg.OnlineDDLScheme)
}
s.onlineDDL, err = fn(s.tctx, s.cfg)
if err != nil {
return errors.Trace(err)
}
rollbackHolder.Add(fr.FuncRollback{Name: "close-onlineDDL", Fn: s.closeOnlineDDL})
}
err = s.genRouter()
if err != nil {
return errors.Trace(err)
}
if s.cfg.IsSharding {
err = s.initShardingGroups()
if err != nil {
return errors.Trace(err)
}
rollbackHolder.Add(fr.FuncRollback{Name: "close-sharding-group-keeper", Fn: s.sgk.Close})
}
err = s.checkpoint.Init(nil)
if err != nil {
return errors.Trace(err)
}
rollbackHolder.Add(fr.FuncRollback{Name: "close-checkpoint", Fn: s.checkpoint.Close})
if s.cfg.RemoveMeta {
err = s.checkpoint.Clear()
if err != nil {
return errors.Annotate(err, "clear checkpoint in syncer")
}
if s.onlineDDL != nil {
err = s.onlineDDL.Clear()
if err != nil {
return errors.Annotate(err, "clear online ddl in syncer")
}
}
s.tctx.L().Info("all previous meta cleared")
}
err = s.checkpoint.Load()
if err != nil {
return errors.Trace(err)
}
if s.cfg.EnableHeartbeat {
s.heartbeat, err = GetHeartbeat(&HeartbeatConfig{
serverID: s.cfg.ServerID,
masterCfg: s.cfg.From,
updateInterval: int64(s.cfg.HeartbeatUpdateInterval),
reportInterval: int64(s.cfg.HeartbeatReportInterval),
})
if err != nil {
return errors.Trace(err)
}
err = s.heartbeat.AddTask(s.cfg.Name)
if err != nil {
return errors.Trace(err)
}
rollbackHolder.Add(fr.FuncRollback{Name: "remove-heartbeat", Fn: s.removeHeartbeat})
}
// when Init syncer, set active relay log info
err = s.setInitActiveRelayLog()
if err != nil {
return errors.Trace(err)
}
rollbackHolder.Add(fr.FuncRollback{Name: "remove-active-realylog", Fn: s.removeActiveRelayLog})
// init successfully, close done chan to make Syncer can be closed
// when Process started, we will re-create done chan again
// NOTE: we should refactor the Concurrency Model some day
s.done = make(chan struct{})
close(s.done)
return nil
}
// 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() error {
// fetch tables from source and filter them
sourceTables, err := utils.FetchAllDoTables(s.fromDB.db, s.bwList)
if err != nil {
return errors.Trace(err)
}
// clear old sharding group and initials some needed data
err = s.sgk.Init(nil)
if err != nil {
return errors.Trace(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, _ := GenTableID(schema, table)
mSchema[targetTable] = append(mSchema[targetTable], ID)
}
}
loadMeta, err2 := s.sgk.LoadShardMeta()
if err2 != nil {
return errors.Trace(err2)
}
// add sharding group
for targetSchema, mSchema := range mapper {
for targetTable, sourceIDs := range mSchema {
tableID, _ := GenTableID(targetSchema, targetTable)
_, _, _, _, err := s.sgk.AddGroup(targetSchema, targetTable, sourceIDs, loadMeta[tableID], false)
if err != nil {
return errors.Trace(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() (bool, error) {
globalPoint := s.checkpoint.GlobalPoint()
return globalPoint.Compare(minCheckpoint) <= 0, nil
}
func (s *Syncer) resetReplicationSyncer() {
if s.binlogType == RemoteBinlog {
// create new binlog-syncer
if s.syncer != nil {
s.closeBinlogSyncer(s.syncer)
}
s.syncer = replication.NewBinlogSyncer(s.syncCfg)
} else if s.binlogType == LocalBinlog {
// TODO: close old local reader before creating a new one
s.localReader = streamer.NewBinlogReader(s.tctx, &streamer.BinlogReaderConfig{
RelayDir: s.cfg.RelayDir,
Timezone: s.timezone,
})
}
}
// Process implements the dm.Unit interface.
func (s *Syncer) Process(ctx context.Context, pr chan pb.ProcessResult) {
syncerExitWithErrorCounter.WithLabelValues(s.cfg.Name).Add(0)
newCtx, cancel := context.WithCancel(ctx)
defer cancel()
s.resetReplicationSyncer()
// create new done chan
s.done = make(chan struct{})
// create new job chans
s.newJobChans(s.cfg.WorkerCount + 1)
// clear tables info
s.clearAllTables()
runFatalChan := make(chan *pb.ProcessError, s.cfg.WorkerCount+1)
s.runFatalChan = runFatalChan
s.execErrorDetected.Set(false)
s.resetExecErrors()
errs := make([]*pb.ProcessError, 0, 2)
if s.cfg.IsSharding {
// every time start to re-sync from resume, we reset status to make it like a fresh syncing
s.sgk.ResetGroups()
s.ddlExecInfo.Renew()
}
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
for {
err, ok := <-runFatalChan
if !ok {
return
}
cancel() // cancel s.Run
syncerExitWithErrorCounter.WithLabelValues(s.cfg.Name).Inc()
errs = append(errs, err)
}
}()
wg.Add(1)
go func() {
defer wg.Done()
<-newCtx.Done() // ctx or newCtx
if s.ddlExecInfo != nil {
s.ddlExecInfo.Close() // let Run can return
}
}()
wg.Add(1)
go func() {
s.runBackgroundJob(newCtx)
wg.Done()
}()
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 {
syncerExitWithErrorCounter.WithLabelValues(s.cfg.Name).Inc()
errs = append(errs, unit.NewProcessError(pb.ErrorType_UnknownError, errors.ErrorStack(err)))
}
isCanceled := false
if len(errs) == 0 {
select {
case <-ctx.Done():
isCanceled = true
default:
}
} else {
// pause because of error occurred
s.Pause()
}
// try to rollback checkpoints, if they already flushed, no effect
prePos := s.checkpoint.GlobalPoint()
s.checkpoint.Rollback()
currPos := s.checkpoint.GlobalPoint()
if prePos.Compare(currPos) != 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() (mysql.Position, gtid.Set, error) {
return utils.GetMasterStatus(s.fromDB.db, s.cfg.Flavor)
}
// clearTables is used for clear table cache of given table. this function must
// be called when DDL is applied to this table.
func (s *Syncer) clearTables(schema, table string) {
key := dbutil.TableName(schema, table)
delete(s.tables, key)
delete(s.cacheColumns, key)
s.genColsCache.clearTable(schema, table)
}
func (s *Syncer) clearAllTables() {
s.tables = make(map[string]*table)
s.cacheColumns = make(map[string][]string)
s.genColsCache.reset()
}
func (s *Syncer) getTableFromDB(db *Conn, schema string, name string) (*table, error) {
table := &table{}
table.schema = schema
table.name = name
table.indexColumns = make(map[string][]*column)
err := getTableColumns(s.tctx, db, table, s.cfg.MaxRetry)
if err != nil {
return nil, errors.Trace(err)
}
err = getTableIndex(s.tctx, db, table, s.cfg.MaxRetry)
if err != nil {
return nil, errors.Trace(err)
}
if len(table.columns) == 0 {
return nil, errors.Errorf("invalid table %s.%s", schema, name)
}
return table, nil
}
func (s *Syncer) getTable(schema string, table string) (*table, []string, error) {
key := dbutil.TableName(schema, table)
value, ok := s.tables[key]
if ok {
return value, s.cacheColumns[key], nil
}
db := s.toDBs[len(s.toDBs)-1]
t, err := s.getTableFromDB(db, schema, table)
if err != nil {
return nil, nil, errors.Trace(err)
}
// compute cache column list for column mapping
columns := make([]string, 0, len(t.columns))
for _, c := range t.columns {
columns = append(columns, c.name)
}
s.tables[key] = t
s.cacheColumns[key] = columns
return t, columns, nil
}
func (s *Syncer) addCount(isFinished bool, queueBucket string, tp opType, n int64) {
m := addedJobsTotal
if isFinished {
m = finishedJobsTotal
}
switch tp {
case insert:
m.WithLabelValues("insert", s.cfg.Name, queueBucket).Add(float64(n))
case update:
m.WithLabelValues("update", s.cfg.Name, queueBucket).Add(float64(n))
case del:
m.WithLabelValues("del", s.cfg.Name, queueBucket).Add(float64(n))
case ddl:
m.WithLabelValues("ddl", s.cfg.Name, queueBucket).Add(float64(n))
case xid:
// ignore xid jobs
case flush:
m.WithLabelValues("flush", s.cfg.Name, queueBucket).Add(float64(n))
case skip:
// ignore skip jobs
default:
s.tctx.L().Warn("unknown job operation type", zap.Stringer("type", tp))
}
s.count.Add(n)
}
func (s *Syncer) checkWait(job *job) bool {
if job.tp == ddl {
return true
}
if s.checkpoint.CheckGlobalPoint() {
return true
}
return false
}
func (s *Syncer) addJob(job *job) error {
var (
queueBucket int
execDDLReq *pb.ExecDDLRequest
)
switch job.tp {
case xid:
s.saveGlobalPoint(job.pos)
return nil
case flush:
addedJobsTotal.WithLabelValues("flush", s.cfg.Name, adminQueueName).Inc()
// ugly code addJob and sync, refine it later
s.jobWg.Add(s.cfg.WorkerCount)
for i := 0; i < s.cfg.WorkerCount; i++ {
s.jobs[i] <- job
}
s.jobWg.Wait()
finishedJobsTotal.WithLabelValues("flush", s.cfg.Name, adminQueueName).Inc()
return errors.Trace(s.flushCheckPoints())
case ddl:
s.jobWg.Wait()
addedJobsTotal.WithLabelValues("ddl", s.cfg.Name, adminQueueName).Inc()
s.jobWg.Add(1)
queueBucket = s.cfg.WorkerCount
s.jobs[queueBucket] <- job
if job.ddlExecItem != nil {
execDDLReq = job.ddlExecItem.req
}
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)
s.jobs[queueBucket] <- job
}
if s.tracer.Enable() {
_, err := s.tracer.CollectSyncerJobEvent(job.traceID, job.traceGID, int32(job.tp), job.pos, job.currentPos, s.queueBucketMapping[queueBucket], job.sql, job.ddls, job.args, execDDLReq, pb.SyncerJobState_queued)
if err != nil {
s.tctx.L().Error("fail to collect binlog replication job event", log.ShortError(err))
}
}
wait := s.checkWait(job)
if wait {
s.jobWg.Wait()
s.c.reset()
}
switch job.tp {
case ddl:
// only save checkpoint for DDL and XID (see above)
s.saveGlobalPoint(job.pos)
if len(job.sourceSchema) > 0 {
s.checkpoint.SaveTablePoint(job.sourceSchema, job.sourceTable, job.pos)
}
// reset sharding group after checkpoint saved
s.resetShardingGroup(job.targetSchema, job.targetTable)
case insert, update, del:
// save job's current pos for DML events
if len(job.sourceSchema) > 0 {
s.checkpoint.SaveTablePoint(job.sourceSchema, job.sourceTable, job.currentPos)
}
}
if wait {
return errors.Trace(s.flushCheckPoints())
}
return nil
}
func (s *Syncer) saveGlobalPoint(globalPoint mysql.Position) {
if s.cfg.IsSharding {
globalPoint = s.sgk.AdjustGlobalPoint(globalPoint)
}
s.checkpoint.SaveGlobalPoint(globalPoint)
}
func (s *Syncer) resetShardingGroup(schema, table string) {
if s.cfg.IsSharding {
// for DDL sharding group, reset group after checkpoint saved
group := s.sgk.Group(schema, table)
if group != nil {
group.Reset()
}
}
}
// flushCheckPoints flushes previous saved checkpoint in memory to persistent storage, like TiDB
// we flush checkpoints in three cases:
// 1. DDL executed
// 2. at intervals (and job executed)
// 3. pausing / stopping the sync (driven by `s.flushJobs`)
// but when error occurred, we can not flush checkpoint, otherwise data may lost
// and except rejecting to flush the checkpoint, we also need to rollback the checkpoint saved before
// this should be handled when `s.Run` returned
//
// we may need to refactor the concurrency model to make the work-flow more clearer later
func (s *Syncer) flushCheckPoints() error {
if s.execErrorDetected.Get() {
s.tctx.L().Warn("error detected when executing SQL job, skip flush checkpoint", zap.Stringer("checkpoint", s.checkpoint))
return nil
}
var (
exceptTableIDs map[string]bool
exceptTables [][]string
shardMetaSQLs []string
shardMetaArgs [][]interface{}
)
if s.cfg.IsSharding {
// flush all checkpoints except tables which are unresolved for sharding DDL
exceptTableIDs, exceptTables = s.sgk.UnresolvedTables()
s.tctx.L().Info("flush checkpoints except for these tables", zap.Reflect("tables", exceptTables))
shardMetaSQLs, shardMetaArgs = s.sgk.PrepareFlushSQLs(exceptTableIDs)
s.tctx.L().Info("prepare flush sqls", zap.Strings("shard meta sqls", shardMetaSQLs), zap.Reflect("shard meta arguments", shardMetaArgs))
}
err := s.checkpoint.FlushPointsExcept(exceptTables, shardMetaSQLs, shardMetaArgs)
if err != nil {
return errors.Annotatef(err, "flush checkpoint %s", s.checkpoint)
}
s.tctx.L().Info("flushed checkpoint", zap.Stringer("checkpoint", s.checkpoint))
// update current active relay log after checkpoint flushed
err = s.updateActiveRelayLog(s.checkpoint.GlobalPoint())
if err != nil {
return errors.Trace(err)
}
return nil
}
func (s *Syncer) sync(ctx *tcontext.Context, queueBucket string, db *Conn, jobChan chan *job) {
defer s.wg.Done()
idx := 0
count := s.cfg.Batch
jobs := make([]*job, 0, count)
tpCnt := make(map[opType]int64)
clearF := func() {
for i := 0; i < idx; i++ {
s.jobWg.Done()
}
idx = 0
jobs = jobs[0:0]
for tpName, v := range tpCnt {
s.addCount(true, queueBucket, tpName, v)
tpCnt[tpName] = 0
}
}
fatalF := func(err error, errType pb.ErrorType) {
s.execErrorDetected.Set(true)
s.runFatalChan <- unit.NewProcessError(errType, errors.ErrorStack(err))
clearF()
}
executeSQLs := func() error {
if len(jobs) == 0 {
return nil
}
errCtx := db.executeSQLJob(s.tctx, jobs, s.cfg.MaxRetry)
var err error
if errCtx != nil {
err = errCtx.err
s.appendExecErrors(errCtx)
}
if s.tracer.Enable() {
syncerJobState := s.tracer.FinishedSyncerJobState(err)
for _, job := range jobs {
_, err2 := s.tracer.CollectSyncerJobEvent(job.traceID, job.traceGID, int32(job.tp), job.pos, job.currentPos, queueBucket, job.sql, job.ddls, nil, nil, syncerJobState)
if err2 != nil {
s.tctx.L().Error("fail to collect binlog replication job event", log.ShortError(err2))
}
}
}
return errors.Trace(err)
}
var err error
for {
select {
case sqlJob, ok := <-jobChan:
if !ok {
return
}
idx++
if sqlJob.tp == ddl {
err = executeSQLs()
if err != nil {
fatalF(err, pb.ErrorType_ExecSQL)
continue
}
if sqlJob.ddlExecItem != nil && sqlJob.ddlExecItem.req != nil && !sqlJob.ddlExecItem.req.Exec {
s.tctx.L().Info("ignore sharding DDLs", zap.Strings("ddls", sqlJob.ddls))
} else {
args := make([][]interface{}, len(sqlJob.ddls))
err = db.executeSQL(s.tctx, sqlJob.ddls, args, 1)
if err != nil && ignoreDDLError(err) {
err = nil
}
if s.tracer.Enable() {
syncerJobState := s.tracer.FinishedSyncerJobState(err)
var execDDLReq *pb.ExecDDLRequest
if sqlJob.ddlExecItem != nil {
execDDLReq = sqlJob.ddlExecItem.req
}
_, traceErr := s.tracer.CollectSyncerJobEvent(sqlJob.traceID, sqlJob.traceGID, int32(sqlJob.tp), sqlJob.pos, sqlJob.currentPos, queueBucket, sqlJob.sql, sqlJob.ddls, nil, execDDLReq, syncerJobState)
if traceErr != nil {
s.tctx.L().Error("fail to collect binlog replication job event", log.ShortError(traceErr))
}
}
}
if err != nil {
s.appendExecErrors(&ExecErrorContext{
err: err,
pos: sqlJob.currentPos,
jobs: fmt.Sprintf("%v", sqlJob.ddls),
})
}
if s.cfg.IsSharding {
// for sharding DDL syncing, send result back
if sqlJob.ddlExecItem != nil {
sqlJob.ddlExecItem.resp <- errors.Trace(err)
}
s.ddlExecInfo.ClearBlockingDDL()
}
if err != nil {
// errro then pause.
fatalF(err, pb.ErrorType_ExecSQL)
continue
}
tpCnt[sqlJob.tp] += int64(len(sqlJob.ddls))
clearF()
} else if sqlJob.tp != flush && len(sqlJob.sql) > 0 {
jobs = append(jobs, sqlJob)
tpCnt[sqlJob.tp]++
}
if idx >= count || sqlJob.tp == flush {
err = executeSQLs()
if err != nil {
fatalF(err, pb.ErrorType_ExecSQL)
continue
}
clearF()
}
default:
if len(jobs) > 0 {
err = executeSQLs()
if err != nil {
fatalF(err, pb.ErrorType_ExecSQL)
continue
}
clearF()
} else {
time.Sleep(waitTime)
}
}
}
}
// redirectStreamer redirects binlog stream to given position
func (s *Syncer) redirectStreamer(pos mysql.Position) error {
var err error
s.tctx.L().Info("reset global streamer", zap.Stringer("position", pos))
s.resetReplicationSyncer()
if s.binlogType == RemoteBinlog {
s.streamer, err = s.getBinlogStreamer(s.syncer, pos)
} else if s.binlogType == LocalBinlog {
s.streamer, err = s.getBinlogStreamer(s.localReader, pos)
}
return errors.Trace(err)
}
// Run starts running for sync, we should guarantee it can rerun when paused.
func (s *Syncer) Run(ctx context.Context) (err error) {
defer func() {
close(s.done)
}()
parser2, err := utils.GetParser(s.fromDB.db, s.cfg.EnableANSIQuotes)
if err != nil {
return errors.Trace(err)
}
fresh, err := s.IsFreshTask()
if err != nil {
return errors.Trace(err)
} else if fresh {
// for fresh task, we try to load checkpoints from meta (file or config item)
err = s.checkpoint.LoadMeta()
if err != nil {
return errors.Trace(err)
}
}
// currentPos is the pos for current received event (End_log_pos in `show binlog events` for mysql)
// lastPos is the pos for last received (ROTATE / QUERY / XID) event (End_log_pos in `show binlog events` for mysql)
// we use currentPos to replace and skip binlog event of specfied position and update table checkpoint in sharding ddl
// we use lastPos to update global checkpoint and table checkpoint
var (
currentPos = s.checkpoint.GlobalPoint() // also init to global checkpoint
lastPos = s.checkpoint.GlobalPoint()
)
s.tctx.L().Info("replicate binlog from checkpoint", zap.Stringer("checkpoint", lastPos))
if s.binlogType == RemoteBinlog {
s.streamer, err = s.getBinlogStreamer(s.syncer, lastPos)
} else if s.binlogType == LocalBinlog {
s.streamer, err = s.getBinlogStreamer(s.localReader, lastPos)
}
if err != nil {
return errors.Trace(err)
}
s.queueBucketMapping = make([]string, 0, s.cfg.WorkerCount+1)
for i := 0; i < s.cfg.WorkerCount; i++ {
s.wg.Add(1)
name := queueBucketName(i)
s.queueBucketMapping = append(s.queueBucketMapping, name)
go func(i int, n string) {
ctx2, cancel := context.WithCancel(ctx)
ctctx := s.tctx.WithContext(ctx2)
s.sync(ctctx, n, s.toDBs[i], s.jobs[i])
cancel()
}(i, name)
}
s.queueBucketMapping = append(s.queueBucketMapping, adminQueueName)
s.wg.Add(1)
go func() {
ctx2, cancel := context.WithCancel(ctx)
ctctx := s.tctx.WithContext(ctx2)
s.sync(ctctx, adminQueueName, s.ddlDB, s.jobs[s.cfg.WorkerCount])
cancel()
}()
s.wg.Add(1)
go func() {