-
Notifications
You must be signed in to change notification settings - Fork 310
Expand file tree
/
Copy pathtask.go
More file actions
1342 lines (1205 loc) · 53.2 KB
/
Copy pathtask.go
File metadata and controls
1342 lines (1205 loc) · 53.2 KB
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 config
import (
"encoding/json"
"flag"
"fmt"
"math"
"os"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/coreos/go-semver/semver"
"github.com/docker/go-units"
"github.com/dustin/go-humanize"
"github.com/pingcap/tidb/pkg/lightning/config"
"github.com/pingcap/tidb/pkg/parser"
"github.com/pingcap/tidb/pkg/sessionctx/variable"
"github.com/pingcap/tidb/pkg/util/filter"
router "github.com/pingcap/tidb/pkg/util/table-router"
"github.com/pingcap/tiflow/dm/config/dbconfig"
"github.com/pingcap/tiflow/dm/config/security"
"github.com/pingcap/tiflow/dm/pkg/log"
"github.com/pingcap/tiflow/dm/pkg/terror"
"github.com/pingcap/tiflow/dm/pkg/utils"
bf "github.com/pingcap/tiflow/pkg/binlog-filter"
"github.com/pingcap/tiflow/pkg/column-mapping"
"go.uber.org/zap"
"gopkg.in/yaml.v2"
)
// Online DDL Scheme.
const (
GHOST = "gh-ost"
PT = "pt"
)
// shard DDL mode.
const (
ShardPessimistic = "pessimistic"
ShardOptimistic = "optimistic"
tidbTxnMode = "tidb_txn_mode"
tidbTxnOptimistic = "optimistic"
)
// collation_compatible.
const (
LooseCollationCompatible = "loose"
StrictCollationCompatible = "strict"
)
const (
ValidationNone = "none"
ValidationFast = "fast"
ValidationFull = "full"
DefaultValidatorWorkerCount = 4
DefaultValidatorValidateInterval = 10 * time.Second
DefaultValidatorCheckInterval = 5 * time.Second
DefaultValidatorRowErrorDelay = 30 * time.Minute
DefaultValidatorMetaFlushInterval = 5 * time.Minute
DefaultValidatorBatchQuerySize = 100
DefaultValidatorMaxPendingRowSize = "500m"
ValidatorMaxAccumulatedRow = 100000
// PendingRow is substantial in this version (in sysbench test)
// set to MaxInt temporaly and reset in the future.
DefaultValidatorMaxPendingRow = math.MaxInt32
)
// default config item values.
var (
// TaskConfig.
defaultMetaSchema = "dm_meta"
defaultEnableHeartbeat = false
defaultIsSharding = false
defaultUpdateInterval = 1
defaultReportInterval = 10
defaultCollationCompatible = "loose"
// MydumperConfig.
defaultMydumperPath = "./bin/mydumper"
defaultThreads = 4
defaultChunkFilesize = "64"
defaultSkipTzUTC = true
// LoaderConfig.
defaultPoolSize = 16
defaultDir = "./dumped_data"
// SyncerConfig.
defaultWorkerCount = 16
defaultBatch = 100
defaultQueueSize = 1024 // do not give too large default value to avoid OOM
defaultCheckpointFlushInterval = 30 // in seconds
defaultSafeModeDuration = strconv.Itoa(2*defaultCheckpointFlushInterval) + "s"
// TargetDBConfig.
defaultSessionCfg = []struct {
key string
val string
minVersion *semver.Version
}{
{tidbTxnMode, tidbTxnOptimistic, semver.New("3.0.0")},
}
)
// Meta represents binlog's meta pos
// NOTE: refine to put these config structs into pkgs
// NOTE: now, syncer does not support GTID mode and which is supported by relay.
type Meta struct {
BinLogName string `toml:"binlog-name" yaml:"binlog-name"`
BinLogPos uint32 `toml:"binlog-pos" yaml:"binlog-pos"`
BinLogGTID string `toml:"binlog-gtid" yaml:"binlog-gtid"`
}
// Verify does verification on configs
// NOTE: we can't decide to verify `binlog-name` or `binlog-gtid` until being bound to a source (with `enable-gtid` set).
func (m *Meta) Verify() error {
if m != nil && len(m.BinLogName) == 0 && len(m.BinLogGTID) == 0 {
return terror.ErrConfigMetaInvalid.Generate()
}
return nil
}
// MySQLInstance represents a sync config of a MySQL instance.
type MySQLInstance struct {
// it represents a MySQL/MariaDB instance or a replica group
SourceID string `yaml:"source-id"`
Meta *Meta `yaml:"meta"`
FilterRules []string `yaml:"filter-rules"`
// deprecated
ColumnMappingRules []string `yaml:"column-mapping-rules"`
RouteRules []string `yaml:"route-rules"`
ExpressionFilters []string `yaml:"expression-filters"`
// black-white-list is deprecated, use block-allow-list instead
BWListName string `yaml:"black-white-list"`
BAListName string `yaml:"block-allow-list"`
MydumperConfigName string `yaml:"mydumper-config-name"`
Mydumper *MydumperConfig `yaml:"mydumper"`
// MydumperThread is alias for Threads in MydumperConfig, and its priority is higher than Threads
MydumperThread int `yaml:"mydumper-thread"`
LoaderConfigName string `yaml:"loader-config-name"`
Loader *LoaderConfig `yaml:"loader"`
// LoaderThread is alias for PoolSize in LoaderConfig, and its priority is higher than PoolSize
LoaderThread int `yaml:"loader-thread"`
SyncerConfigName string `yaml:"syncer-config-name"`
Syncer *SyncerConfig `yaml:"syncer"`
// SyncerThread is alias for WorkerCount in SyncerConfig, and its priority is higher than WorkerCount
SyncerThread int `yaml:"syncer-thread"`
ContinuousValidatorConfigName string `yaml:"validator-config-name"`
ContinuousValidator ValidatorConfig `yaml:"-"`
}
// VerifyAndAdjust does verification on configs, and adjust some configs.
func (m *MySQLInstance) VerifyAndAdjust() error {
if m == nil {
return terror.ErrConfigMySQLInstNotFound.Generate()
}
if m.SourceID == "" {
return terror.ErrConfigEmptySourceID.Generate()
}
if err := m.Meta.Verify(); err != nil {
return terror.Annotatef(err, "source %s", m.SourceID)
}
if len(m.MydumperConfigName) > 0 && m.Mydumper != nil {
return terror.ErrConfigMydumperCfgConflict.Generate()
}
if len(m.LoaderConfigName) > 0 && m.Loader != nil {
return terror.ErrConfigLoaderCfgConflict.Generate()
}
if len(m.SyncerConfigName) > 0 && m.Syncer != nil {
return terror.ErrConfigSyncerCfgConflict.Generate()
}
if len(m.BAListName) == 0 && len(m.BWListName) != 0 {
m.BAListName = m.BWListName
}
return nil
}
// MydumperConfig represents mydumper process unit's specific config.
type MydumperConfig struct {
MydumperPath string `yaml:"mydumper-path" toml:"mydumper-path" json:"mydumper-path"` // mydumper binary path
Threads int `yaml:"threads" toml:"threads" json:"threads"` // -t, --threads
ChunkFilesize string `yaml:"chunk-filesize" toml:"chunk-filesize" json:"chunk-filesize"` // -F, --chunk-filesize
StatementSize uint64 `yaml:"statement-size" toml:"statement-size" json:"statement-size"` // -S, --statement-size
Rows uint64 `yaml:"rows" toml:"rows" json:"rows"` // -r, --rows
Where string `yaml:"where" toml:"where" json:"where"` // --where
SkipTzUTC bool `yaml:"skip-tz-utc" toml:"skip-tz-utc" json:"skip-tz-utc"` // --skip-tz-utc
ExtraArgs string `yaml:"extra-args" toml:"extra-args" json:"extra-args"` // other extra args
// NOTE: use LoaderConfig.Dir as --outputdir
// TODO zxc: combine -B -T --regex with filter rules?
}
// DefaultMydumperConfig return default mydumper config for task.
func DefaultMydumperConfig() MydumperConfig {
return MydumperConfig{
MydumperPath: defaultMydumperPath,
Threads: defaultThreads,
ChunkFilesize: defaultChunkFilesize,
SkipTzUTC: defaultSkipTzUTC,
}
}
// alias to avoid infinite recursion for UnmarshalYAML.
type rawMydumperConfig MydumperConfig
// UnmarshalYAML implements Unmarshaler.UnmarshalYAML.
func (m *MydumperConfig) UnmarshalYAML(unmarshal func(any) error) error {
raw := rawMydumperConfig(DefaultMydumperConfig())
if err := unmarshal(&raw); err != nil {
return terror.ErrConfigYamlTransform.Delegate(err, "unmarshal mydumper config")
}
*m = MydumperConfig(raw) // raw used only internal, so no deep copy
return nil
}
// LoadMode defines different mode used in load phase.
type LoadMode string
const (
// LoadModeSQL means write data by sql statements, uses tidb-lightning tidb backend to load data.
// deprecated, use LoadModeLogical instead.
LoadModeSQL LoadMode = "sql"
// LoadModeLoader is the legacy sql mode, use loader to load data. this should be replaced by LoadModeLogical mode.
// deprecated, use LoadModeLogical instead.
LoadModeLoader LoadMode = "loader"
// LoadModeLogical means use tidb backend of lightning to load data, which uses SQL to load data.
LoadModeLogical LoadMode = "logical"
// LoadModePhysical means use local backend of lightning to load data, which ingest SST files to load data.
LoadModePhysical LoadMode = "physical"
// LoadModeImportInto means use import-into backend of lightning to load data, which uses IMPORT INTO SQL statement.
LoadModeImportInto LoadMode = "import-into"
)
// LogicalDuplicateResolveType defines the duplication resolution when meet duplicate rows for logical import.
type LogicalDuplicateResolveType string
const (
// OnDuplicateReplace represents replace the old row with new data.
OnDuplicateReplace LogicalDuplicateResolveType = "replace"
// OnDuplicateError represents return an error when meet duplicate row.
OnDuplicateError LogicalDuplicateResolveType = "error"
// OnDuplicateIgnore represents ignore the new data when meet duplicate row.
OnDuplicateIgnore LogicalDuplicateResolveType = "ignore"
)
// PhysicalDuplicateResolveType defines the duplication resolution when meet duplicate rows for physical import.
type PhysicalDuplicateResolveType string
const (
// OnDuplicateNone represents do nothing when meet duplicate row and the task will continue.
OnDuplicateNone PhysicalDuplicateResolveType = "none"
// OnDuplicateManual represents that task should be paused when meet duplicate row to let user handle it manually.
OnDuplicateManual PhysicalDuplicateResolveType = "manual"
)
// PhysicalPostOpLevel defines the configuration of checksum/analyze of physical import.
type PhysicalPostOpLevel string
const (
OpLevelRequired = "required"
OpLevelOptional = "optional"
OpLevelOff = "off"
)
// LoaderConfig represents loader process unit's specific config.
type LoaderConfig struct {
PoolSize int `yaml:"pool-size" toml:"pool-size" json:"pool-size"`
Dir string `yaml:"dir" toml:"dir" json:"dir"`
SortingDirPhysical string `yaml:"sorting-dir-physical" toml:"sorting-dir-physical" json:"sorting-dir-physical"`
SQLMode string `yaml:"-" toml:"-" json:"-"` // wrote by dump unit (DM op) or jobmaster (DM in engine)
ImportMode LoadMode `yaml:"import-mode" toml:"import-mode" json:"import-mode"`
// deprecated, use OnDuplicateLogical instead.
OnDuplicate LogicalDuplicateResolveType `yaml:"on-duplicate" toml:"on-duplicate" json:"on-duplicate"`
OnDuplicateLogical LogicalDuplicateResolveType `yaml:"on-duplicate-logical" toml:"on-duplicate-logical" json:"on-duplicate-logical"`
OnDuplicatePhysical PhysicalDuplicateResolveType `yaml:"on-duplicate-physical" toml:"on-duplicate-physical" json:"on-duplicate-physical"`
DiskQuotaPhysical config.ByteSize `yaml:"disk-quota-physical" toml:"disk-quota-physical" json:"disk-quota-physical"`
ChecksumPhysical PhysicalPostOpLevel `yaml:"checksum-physical" toml:"checksum-physical" json:"checksum-physical"`
Analyze PhysicalPostOpLevel `yaml:"analyze" toml:"analyze" json:"analyze"`
RangeConcurrency int `yaml:"range-concurrency" toml:"range-concurrency" json:"range-concurrency"`
CompressKVPairs string `yaml:"compress-kv-pairs" toml:"compress-kv-pairs" json:"compress-kv-pairs"`
PDAddr string `yaml:"pd-addr" toml:"pd-addr" json:"pd-addr"`
// now only creating task by OpenAPI will use the `Security` field to connect PD.
// TODO: support setting `Security` by dmctl
Security *security.Security `yaml:"-" toml:"security" json:"security"`
}
// DefaultLoaderConfig return default loader config for task.
func DefaultLoaderConfig() LoaderConfig {
return LoaderConfig{
PoolSize: defaultPoolSize,
Dir: defaultDir,
ImportMode: LoadModeLogical,
OnDuplicateLogical: OnDuplicateReplace,
}
}
// alias to avoid infinite recursion for UnmarshalYAML.
type rawLoaderConfig LoaderConfig
// UnmarshalYAML implements Unmarshaler.UnmarshalYAML.
func (m *LoaderConfig) UnmarshalYAML(unmarshal func(any) error) error {
raw := rawLoaderConfig(DefaultLoaderConfig())
if err := unmarshal(&raw); err != nil {
return terror.ErrConfigYamlTransform.Delegate(err, "unmarshal loader config")
}
*m = LoaderConfig(raw) // raw used only internal, so no deep copy
return nil
}
func (m *LoaderConfig) adjust() error {
if m.ImportMode == "" {
m.ImportMode = LoadModeLogical
}
if strings.EqualFold(string(m.ImportMode), string(LoadModeSQL)) ||
strings.EqualFold(string(m.ImportMode), string(LoadModeLoader)) {
m.ImportMode = LoadModeLogical
}
m.ImportMode = LoadMode(strings.ToLower(string(m.ImportMode)))
switch m.ImportMode {
case LoadModeLoader, LoadModeSQL, LoadModeLogical, LoadModePhysical, LoadModeImportInto:
default:
return terror.ErrConfigInvalidLoadMode.Generate(m.ImportMode)
}
if m.PoolSize == 0 {
m.PoolSize = defaultPoolSize
}
if m.OnDuplicateLogical == "" {
m.OnDuplicateLogical = OnDuplicateReplace
}
m.OnDuplicateLogical = LogicalDuplicateResolveType(strings.ToLower(string(m.OnDuplicateLogical)))
switch m.OnDuplicateLogical {
case OnDuplicateReplace, OnDuplicateError, OnDuplicateIgnore:
default:
return terror.ErrConfigInvalidDuplicateResolution.Generate(m.OnDuplicateLogical)
}
if m.OnDuplicatePhysical == "" {
m.OnDuplicatePhysical = OnDuplicateNone
}
m.OnDuplicatePhysical = PhysicalDuplicateResolveType(strings.ToLower(string(m.OnDuplicatePhysical)))
switch m.OnDuplicatePhysical {
case OnDuplicateNone, OnDuplicateManual:
default:
return terror.ErrConfigInvalidPhysicalDuplicateResolution.Generate(m.OnDuplicatePhysical)
}
if m.ChecksumPhysical == "" {
m.ChecksumPhysical = OpLevelRequired
}
m.ChecksumPhysical = PhysicalPostOpLevel(strings.ToLower(string(m.ChecksumPhysical)))
switch m.ChecksumPhysical {
case OpLevelRequired, OpLevelOptional, OpLevelOff:
default:
return terror.ErrConfigInvalidPhysicalChecksum.Generate(m.ChecksumPhysical)
}
if m.Analyze == "" {
m.Analyze = OpLevelOptional
}
m.Analyze = PhysicalPostOpLevel(strings.ToLower(string(m.Analyze)))
switch m.Analyze {
case OpLevelRequired, OpLevelOptional, OpLevelOff:
default:
return terror.ErrConfigInvalidLoadAnalyze.Generate(m.Analyze)
}
return nil
}
// SyncerConfig represents syncer process unit's specific config.
type SyncerConfig struct {
MetaFile string `yaml:"meta-file" toml:"meta-file" json:"meta-file"` // meta filename, used only when load SubConfig directly
WorkerCount int `yaml:"worker-count" toml:"worker-count" json:"worker-count"`
Batch int `yaml:"batch" toml:"batch" json:"batch"`
QueueSize int `yaml:"queue-size" toml:"queue-size" json:"queue-size"`
// checkpoint flush interval in seconds.
CheckpointFlushInterval int `yaml:"checkpoint-flush-interval" toml:"checkpoint-flush-interval" json:"checkpoint-flush-interval"`
// TODO: add this two new config items for openapi.
Compact bool `yaml:"compact" toml:"compact" json:"compact"`
MultipleRows bool `yaml:"multiple-rows" toml:"multiple-rows" json:"multiple-rows"`
// deprecated
MaxRetry int `yaml:"max-retry" toml:"max-retry" json:"max-retry"`
// deprecated
AutoFixGTID bool `yaml:"auto-fix-gtid" toml:"auto-fix-gtid" json:"auto-fix-gtid"`
EnableGTID bool `yaml:"enable-gtid" toml:"enable-gtid" json:"enable-gtid"`
// deprecated
DisableCausality bool `yaml:"disable-detect" toml:"disable-detect" json:"disable-detect"`
SafeMode bool `yaml:"safe-mode" toml:"safe-mode" json:"safe-mode"`
SafeModeDuration string `yaml:"safe-mode-duration" toml:"safe-mode-duration" json:"safe-mode-duration"`
// deprecated, use `ansi-quotes` in top level config instead
EnableANSIQuotes bool `yaml:"enable-ansi-quotes" toml:"enable-ansi-quotes" json:"enable-ansi-quotes"`
}
// IsForeignKeyChecksEnabled reports whether the downstream session keeps FK checks on.
func IsForeignKeyChecksEnabled(session map[string]string) bool {
for key, value := range session {
if strings.EqualFold(key, "foreign_key_checks") {
trimmed := strings.Trim(value, " '\"")
return variable.TiDBOptOn(trimmed)
}
}
return false
}
// CheckForeignKeyChecksSyncerOptions rejects syncer options that change DML statement boundaries.
func CheckForeignKeyChecksSyncerOptions(session map[string]string, syncerCfg SyncerConfig) error {
if !IsForeignKeyChecksEnabled(session) {
return nil
}
if syncerCfg.Compact {
return terror.ErrConfigUnsupportedForeignKeyChecksOption.Generate("compact")
}
if syncerCfg.MultipleRows {
return terror.ErrConfigUnsupportedForeignKeyChecksOption.Generate("multiple-rows")
}
return nil
}
// DefaultSyncerConfig return default syncer config for task.
func DefaultSyncerConfig() SyncerConfig {
return SyncerConfig{
WorkerCount: defaultWorkerCount,
Batch: defaultBatch,
QueueSize: defaultQueueSize,
CheckpointFlushInterval: defaultCheckpointFlushInterval,
SafeModeDuration: defaultSafeModeDuration,
}
}
// alias to avoid infinite recursion for UnmarshalYAML.
type rawSyncerConfig SyncerConfig
// UnmarshalYAML implements Unmarshaler.UnmarshalYAML.
func (m *SyncerConfig) UnmarshalYAML(unmarshal func(any) error) error {
raw := rawSyncerConfig(DefaultSyncerConfig())
if err := unmarshal(&raw); err != nil {
return terror.ErrConfigYamlTransform.Delegate(err, "unmarshal syncer config")
}
*m = SyncerConfig(raw) // raw used only internal, so no deep copy
return nil
}
type ValidatorConfig struct {
Mode string `yaml:"mode" toml:"mode" json:"mode"`
WorkerCount int `yaml:"worker-count" toml:"worker-count" json:"worker-count"`
ValidateInterval Duration `yaml:"validate-interval" toml:"validate-interval" json:"validate-interval"`
CheckInterval Duration `yaml:"check-interval" toml:"check-interval" json:"check-interval"`
RowErrorDelay Duration `yaml:"row-error-delay" toml:"row-error-delay" json:"row-error-delay"`
MetaFlushInterval Duration `yaml:"meta-flush-interval" toml:"meta-flush-interval" json:"meta-flush-interval"`
BatchQuerySize int `yaml:"batch-query-size" toml:"batch-query-size" json:"batch-query-size"`
MaxPendingRowSize string `yaml:"max-pending-row-size" toml:"max-pending-row-size" json:"max-pending-row-size"`
MaxPendingRowCount int `yaml:"max-pending-row-count" toml:"max-pending-row-count" json:"max-pending-row-count"`
StartTime string `yaml:"-" toml:"start-time" json:"-"`
}
func (v *ValidatorConfig) Adjust() error {
if v.Mode == "" {
v.Mode = ValidationNone
}
if v.Mode != ValidationNone && v.Mode != ValidationFast && v.Mode != ValidationFull {
return terror.ErrConfigValidationMode
}
if v.WorkerCount <= 0 {
v.WorkerCount = DefaultValidatorWorkerCount
}
if v.ValidateInterval.Duration == 0 {
v.ValidateInterval.Duration = DefaultValidatorValidateInterval
}
if v.CheckInterval.Duration == 0 {
v.CheckInterval.Duration = DefaultValidatorCheckInterval
}
if v.RowErrorDelay.Duration == 0 {
v.RowErrorDelay.Duration = DefaultValidatorRowErrorDelay
}
if v.MetaFlushInterval.Duration == 0 {
v.MetaFlushInterval.Duration = DefaultValidatorMetaFlushInterval
}
if v.BatchQuerySize == 0 {
v.BatchQuerySize = DefaultValidatorBatchQuerySize
}
if v.MaxPendingRowSize == "" {
v.MaxPendingRowSize = DefaultValidatorMaxPendingRowSize
}
_, err := units.RAMInBytes(v.MaxPendingRowSize)
if err != nil {
return err
}
if v.MaxPendingRowCount == 0 {
v.MaxPendingRowCount = DefaultValidatorMaxPendingRow
}
return nil
}
func defaultValidatorConfig() ValidatorConfig {
return ValidatorConfig{
Mode: ValidationNone,
}
}
// TaskConfig is the configuration for Task.
type TaskConfig struct {
*flag.FlagSet `yaml:"-" toml:"-" json:"-"`
Name string `yaml:"name" toml:"name" json:"name"`
TaskMode string `yaml:"task-mode" toml:"task-mode" json:"task-mode"`
IsSharding bool `yaml:"is-sharding" toml:"is-sharding" json:"is-sharding"`
ShardMode string `yaml:"shard-mode" toml:"shard-mode" json:"shard-mode"` // when `shard-mode` set, we always enable sharding support.
StrictOptimisticShardMode bool `yaml:"strict-optimistic-shard-mode" toml:"strict-optimistic-shard-mode" json:"strict-optimistic-shard-mode"`
// treat it as hidden configuration
IgnoreCheckingItems []string `yaml:"ignore-checking-items" toml:"ignore-checking-items" json:"ignore-checking-items"`
// we store detail status in meta
// don't save configuration into it
MetaSchema string `yaml:"meta-schema" toml:"meta-schema" json:"meta-schema"`
// deprecated
EnableHeartbeat bool `yaml:"enable-heartbeat" toml:"enable-heartbeat" json:"enable-heartbeat"`
// deprecated
HeartbeatUpdateInterval int `yaml:"heartbeat-update-interval" toml:"heartbeat-update-interval" json:"heartbeat-update-interval"`
// deprecated
HeartbeatReportInterval int `yaml:"heartbeat-report-interval" toml:"heartbeat-report-interval" json:"heartbeat-report-interval"`
Timezone string `yaml:"timezone" toml:"timezone" json:"timezone"`
// handle schema/table name mode, and only for schema/table name
// if case insensitive, we would convert schema/table name to lower case
CaseSensitive bool `yaml:"case-sensitive" toml:"case-sensitive" json:"case-sensitive"`
// default "loose" handle create sql by original sql, will not add default collation as upstream
// "strict" will add default collation as upstream, and downstream will occur error when downstream don't support
CollationCompatible string `yaml:"collation_compatible" toml:"collation_compatible" json:"collation_compatible"`
TargetDB *dbconfig.DBConfig `yaml:"target-database" toml:"target-database" json:"target-database"`
MySQLInstances []*MySQLInstance `yaml:"mysql-instances" toml:"mysql-instances" json:"mysql-instances"`
OnlineDDL bool `yaml:"online-ddl" toml:"online-ddl" json:"online-ddl"`
// pt/gh-ost name rule,support regex
ShadowTableRules []string `yaml:"shadow-table-rules" toml:"shadow-table-rules" json:"shadow-table-rules"`
TrashTableRules []string `yaml:"trash-table-rules" toml:"trash-table-rules" json:"trash-table-rules"`
// deprecated
OnlineDDLScheme string `yaml:"online-ddl-scheme" toml:"online-ddl-scheme" json:"online-ddl-scheme"`
Routes map[string]*router.TableRule `yaml:"routes" toml:"routes" json:"routes"`
Filters map[string]*bf.BinlogEventRule `yaml:"filters" toml:"filters" json:"filters"`
// deprecated
ColumnMappings map[string]*column.Rule `yaml:"column-mappings" toml:"column-mappings" json:"column-mappings"`
ExprFilter map[string]*ExpressionFilter `yaml:"expression-filter" toml:"expression-filter" json:"expression-filter"`
// black-white-list is deprecated, use block-allow-list instead
BWList map[string]*filter.Rules `yaml:"black-white-list" toml:"black-white-list" json:"black-white-list"`
BAList map[string]*filter.Rules `yaml:"block-allow-list" toml:"block-allow-list" json:"block-allow-list"`
Mydumpers map[string]*MydumperConfig `yaml:"mydumpers" toml:"mydumpers" json:"mydumpers"`
Loaders map[string]*LoaderConfig `yaml:"loaders" toml:"loaders" json:"loaders"`
Syncers map[string]*SyncerConfig `yaml:"syncers" toml:"syncers" json:"syncers"`
Validators map[string]*ValidatorConfig `yaml:"validators" toml:"validators" json:"validators"`
CleanDumpFile bool `yaml:"clean-dump-file" toml:"clean-dump-file" json:"clean-dump-file"`
// deprecated
EnableANSIQuotes bool `yaml:"ansi-quotes" toml:"ansi-quotes" json:"ansi-quotes"`
// deprecated, replaced by `start-task --remove-meta`
RemoveMeta bool `yaml:"remove-meta"`
// task experimental configs
Experimental struct {
AsyncCheckpointFlush bool `yaml:"async-checkpoint-flush" toml:"async-checkpoint-flush" json:"async-checkpoint-flush"`
} `yaml:"experimental" toml:"experimental" json:"experimental"`
}
// NewTaskConfig creates a TaskConfig.
func NewTaskConfig() *TaskConfig {
cfg := &TaskConfig{
// explicitly set default value
MetaSchema: defaultMetaSchema,
EnableHeartbeat: defaultEnableHeartbeat,
HeartbeatUpdateInterval: defaultUpdateInterval,
HeartbeatReportInterval: defaultReportInterval,
MySQLInstances: make([]*MySQLInstance, 0, 5),
IsSharding: defaultIsSharding,
Routes: make(map[string]*router.TableRule),
Filters: make(map[string]*bf.BinlogEventRule),
ColumnMappings: make(map[string]*column.Rule),
ExprFilter: make(map[string]*ExpressionFilter),
BWList: make(map[string]*filter.Rules),
BAList: make(map[string]*filter.Rules),
Mydumpers: make(map[string]*MydumperConfig),
Loaders: make(map[string]*LoaderConfig),
Syncers: make(map[string]*SyncerConfig),
Validators: make(map[string]*ValidatorConfig),
CleanDumpFile: true,
OnlineDDL: true,
CollationCompatible: defaultCollationCompatible,
}
cfg.FlagSet = flag.NewFlagSet("task", flag.ContinueOnError)
return cfg
}
// String returns the config's yaml string.
func (c *TaskConfig) String() string {
cfg, err := yaml.Marshal(c)
if err != nil {
log.L().Error("marshal task config to yaml", zap.String("task", c.Name), log.ShortError(err))
}
return string(cfg)
}
// JSON returns the config's json string.
func (c *TaskConfig) JSON() string {
//nolint:staticcheck
cfg, err := json.Marshal(c)
if err != nil {
log.L().Error("marshal task config to json", zap.String("task", c.Name), log.ShortError(err))
}
return string(cfg)
}
// DecodeFile loads and decodes config from file.
func (c *TaskConfig) DecodeFile(fpath string) error {
bs, err := os.ReadFile(fpath)
if err != nil {
return terror.ErrConfigReadCfgFromFile.Delegate(err, fpath)
}
err = yaml.UnmarshalStrict(bs, c)
if err != nil {
return terror.ErrConfigYamlTransform.Delegate(err)
}
return c.adjust()
}
// FromYaml loads config from file data.
func (c *TaskConfig) FromYaml(data string) error {
err := yaml.UnmarshalStrict([]byte(data), c)
if err != nil {
return terror.ErrConfigYamlTransform.Delegate(err, "decode task config failed")
}
return c.adjust()
}
// RawDecode loads config from file data.
func (c *TaskConfig) RawDecode(data string) error {
return terror.ErrConfigYamlTransform.Delegate(yaml.UnmarshalStrict([]byte(data), c), "decode task config failed")
}
// find unused items in config.
var configRefPrefixes = []string{"RouteRules", "FilterRules", "Mydumper", "Loader", "Syncer", "ExprFilter", "Validator"}
const (
routeRulesIdx = iota
filterRulesIdx
mydumperIdx
loaderIdx
syncerIdx
exprFilterIdx
validatorIdx
)
// Adjust adjusts and verifies config.
func (c *TaskConfig) Adjust() error {
if c == nil {
return terror.ErrConfigYamlTransform.New("task config is nil")
}
return c.adjust()
}
func (c *TaskConfig) adjust() error {
if len(c.Name) == 0 {
return terror.ErrConfigNeedUniqueTaskName.Generate()
}
switch c.TaskMode {
case ModeFull, ModeIncrement, ModeAll, ModeDump, ModeLoad, ModeLoadSync:
default:
return terror.ErrConfigInvalidTaskMode.Generate()
}
if c.MetaSchema == "" {
c.MetaSchema = defaultMetaSchema
}
if c.ShardMode != "" && c.ShardMode != ShardPessimistic && c.ShardMode != ShardOptimistic {
return terror.ErrConfigShardModeNotSupport.Generate(c.ShardMode)
} else if c.ShardMode == "" && c.IsSharding {
c.ShardMode = ShardPessimistic // use the pessimistic mode as default for back compatible.
}
if c.StrictOptimisticShardMode && c.ShardMode != ShardOptimistic {
return terror.ErrConfigStrictOptimisticShardMode.Generate()
}
if len(c.ColumnMappings) > 0 {
return terror.ErrConfigColumnMappingDeprecated.Generate()
}
if c.CollationCompatible != "" && c.CollationCompatible != LooseCollationCompatible && c.CollationCompatible != StrictCollationCompatible {
return terror.ErrConfigCollationCompatibleNotSupport.Generate(c.CollationCompatible)
} else if c.CollationCompatible == "" {
c.CollationCompatible = LooseCollationCompatible
}
for _, item := range c.IgnoreCheckingItems {
if err := ValidateCheckingItem(item); err != nil {
return err
}
}
if c.OnlineDDLScheme != "" && c.OnlineDDLScheme != PT && c.OnlineDDLScheme != GHOST {
return terror.ErrConfigOnlineSchemeNotSupport.Generate(c.OnlineDDLScheme)
} else if c.OnlineDDLScheme == PT || c.OnlineDDLScheme == GHOST {
c.OnlineDDL = true
log.L().Warn("'online-ddl-scheme' will be deprecated soon. Recommend that use online-ddl instead of online-ddl-scheme.")
}
if c.TargetDB == nil {
return terror.ErrConfigNeedTargetDB.Generate()
}
if len(c.MySQLInstances) == 0 {
return terror.ErrConfigMySQLInstsAtLeastOne.Generate()
}
for name, exprFilter := range c.ExprFilter {
if exprFilter.Schema == "" {
return terror.ErrConfigExprFilterEmptyName.Generate(name, "schema")
}
if exprFilter.Table == "" {
return terror.ErrConfigExprFilterEmptyName.Generate(name, "table")
}
setFields := make([]string, 0, 1)
if exprFilter.InsertValueExpr != "" {
if err := checkValidExpr(exprFilter.InsertValueExpr); err != nil {
return terror.ErrConfigExprFilterWrongGrammar.Generate(name, exprFilter.InsertValueExpr, err)
}
setFields = append(setFields, "insert: ["+exprFilter.InsertValueExpr+"]")
}
if exprFilter.UpdateOldValueExpr != "" || exprFilter.UpdateNewValueExpr != "" {
if exprFilter.UpdateOldValueExpr != "" {
if err := checkValidExpr(exprFilter.UpdateOldValueExpr); err != nil {
return terror.ErrConfigExprFilterWrongGrammar.Generate(name, exprFilter.UpdateOldValueExpr, err)
}
}
if exprFilter.UpdateNewValueExpr != "" {
if err := checkValidExpr(exprFilter.UpdateNewValueExpr); err != nil {
return terror.ErrConfigExprFilterWrongGrammar.Generate(name, exprFilter.UpdateNewValueExpr, err)
}
}
setFields = append(setFields, "update (old value): ["+exprFilter.UpdateOldValueExpr+"] update (new value): ["+exprFilter.UpdateNewValueExpr+"]")
}
if exprFilter.DeleteValueExpr != "" {
if err := checkValidExpr(exprFilter.DeleteValueExpr); err != nil {
return terror.ErrConfigExprFilterWrongGrammar.Generate(name, exprFilter.DeleteValueExpr, err)
}
setFields = append(setFields, "delete: ["+exprFilter.DeleteValueExpr+"]")
}
if len(setFields) > 1 {
return terror.ErrConfigExprFilterManyExpr.Generate(name, setFields)
}
}
for _, validatorCfg := range c.Validators {
if err := validatorCfg.Adjust(); err != nil {
return err
}
}
instanceIDs := make(map[string]int) // source-id -> instance-index
globalConfigReferCount := map[string]int{}
duplicateErrorStrings := make([]string, 0)
for i, inst := range c.MySQLInstances {
if err := inst.VerifyAndAdjust(); err != nil {
return terror.Annotatef(err, "mysql-instance: %s", humanize.Ordinal(i))
}
if iid, ok := instanceIDs[inst.SourceID]; ok {
return terror.ErrConfigMySQLInstSameSourceID.Generate(iid, i, inst.SourceID)
}
instanceIDs[inst.SourceID] = i
switch c.TaskMode {
case ModeFull, ModeAll, ModeDump, ModeLoad:
if inst.Meta != nil {
log.L().Warn("metadata will not be used. for Full/Dump/Load mode, incremental sync will never occur; for All mode, the meta dumped by MyDumper will be used", zap.Int("mysql instance", i), zap.String("task mode", c.TaskMode))
}
case ModeIncrement:
if inst.Meta == nil {
log.L().Warn("mysql-instance doesn't set meta for incremental mode, user should specify start_time to start task.", zap.String("sourceID", inst.SourceID))
} else {
err := inst.Meta.Verify()
if err != nil {
return terror.Annotatef(err, "mysql-instance: %d", i)
}
}
}
for _, name := range inst.RouteRules {
if _, ok := c.Routes[name]; !ok {
return terror.ErrConfigRouteRuleNotFound.Generate(i, name)
}
globalConfigReferCount[configRefPrefixes[routeRulesIdx]+name]++
}
for _, name := range inst.FilterRules {
if _, ok := c.Filters[name]; !ok {
return terror.ErrConfigFilterRuleNotFound.Generate(i, name)
}
globalConfigReferCount[configRefPrefixes[filterRulesIdx]+name]++
}
// only when BAList is empty use BWList
if len(c.BAList) == 0 && len(c.BWList) != 0 {
c.BAList = c.BWList
}
if _, ok := c.BAList[inst.BAListName]; len(inst.BAListName) > 0 && !ok {
return terror.ErrConfigBAListNotFound.Generate(i, inst.BAListName)
}
if len(inst.MydumperConfigName) > 0 {
rule, ok := c.Mydumpers[inst.MydumperConfigName]
if !ok {
return terror.ErrConfigMydumperCfgNotFound.Generate(i, inst.MydumperConfigName)
}
globalConfigReferCount[configRefPrefixes[mydumperIdx]+inst.MydumperConfigName]++
if rule != nil {
inst.Mydumper = new(MydumperConfig)
*inst.Mydumper = *rule // ref mydumper config
}
}
if inst.Mydumper == nil {
if len(c.Mydumpers) != 0 {
log.L().Warn("mysql instance don't refer mydumper's configuration with mydumper-config-name, the default configuration will be used", zap.String("mysql instance", inst.SourceID))
}
defaultCfg := DefaultMydumperConfig()
inst.Mydumper = &defaultCfg
} else if inst.Mydumper.ChunkFilesize == "" {
// avoid too big dump file that can't sent concurrently
inst.Mydumper.ChunkFilesize = defaultChunkFilesize
}
if inst.MydumperThread != 0 {
inst.Mydumper.Threads = inst.MydumperThread
}
if HasDump(c.TaskMode) && len(inst.Mydumper.MydumperPath) == 0 {
// only verify if set, whether is valid can only be verify when we run it
return terror.ErrConfigMydumperPathNotValid.Generate(i)
}
if len(inst.LoaderConfigName) > 0 {
rule, ok := c.Loaders[inst.LoaderConfigName]
if !ok {
return terror.ErrConfigLoaderCfgNotFound.Generate(i, inst.LoaderConfigName)
}
globalConfigReferCount[configRefPrefixes[loaderIdx]+inst.LoaderConfigName]++
if rule != nil {
inst.Loader = new(LoaderConfig)
*inst.Loader = *rule // ref loader config
}
}
if inst.Loader == nil {
if len(c.Loaders) != 0 {
log.L().Warn("mysql instance don't refer loader's configuration with loader-config-name, the default configuration will be used", zap.String("mysql instance", inst.SourceID))
}
defaultCfg := DefaultLoaderConfig()
inst.Loader = &defaultCfg
}
if inst.LoaderThread != 0 {
inst.Loader.PoolSize = inst.LoaderThread
}
// import-into does not support sharding / multi-source tasks.
// NOTE: TaskConfig.adjust() runs before generating SubTaskConfig, so we validate it here
// to avoid multi-source import-into tasks passing admission and failing later at runtime.
if len(c.MySQLInstances) > 1 && strings.EqualFold(string(inst.Loader.ImportMode), string(LoadModeImportInto)) {
return terror.ErrConfigImportIntoShardingNotSupport.Generate()
}
if len(inst.SyncerConfigName) > 0 {
rule, ok := c.Syncers[inst.SyncerConfigName]
if !ok {
return terror.ErrConfigSyncerCfgNotFound.Generate(i, inst.SyncerConfigName)
}
globalConfigReferCount[configRefPrefixes[syncerIdx]+inst.SyncerConfigName]++
if rule != nil {
inst.Syncer = new(SyncerConfig)
*inst.Syncer = *rule // ref syncer config
}
}
if inst.Syncer == nil {
if len(c.Syncers) != 0 {
log.L().Warn("mysql instance don't refer syncer's configuration with syncer-config-name, the default configuration will be used", zap.String("mysql instance", inst.SourceID))
}
defaultCfg := DefaultSyncerConfig()
inst.Syncer = &defaultCfg
}
if inst.Syncer.QueueSize == 0 {
inst.Syncer.QueueSize = defaultQueueSize
}
if inst.Syncer.CheckpointFlushInterval == 0 {
inst.Syncer.CheckpointFlushInterval = defaultCheckpointFlushInterval
}
if inst.Syncer.SafeModeDuration == "" {
inst.Syncer.SafeModeDuration = strconv.Itoa(2*inst.Syncer.CheckpointFlushInterval) + "s"
}
if duration, err := time.ParseDuration(inst.Syncer.SafeModeDuration); err != nil {
return terror.ErrConfigInvalidSafeModeDuration.Generate(inst.Syncer.SafeModeDuration, err)
} else if inst.Syncer.SafeMode && duration == 0 {
return terror.ErrConfigConfictSafeModeDurationAndSafeMode.Generate()
}
if inst.SyncerThread != 0 {
inst.Syncer.WorkerCount = inst.SyncerThread
}
inst.ContinuousValidator = defaultValidatorConfig()
if inst.ContinuousValidatorConfigName != "" {
rule, ok := c.Validators[inst.ContinuousValidatorConfigName]
if !ok {
return terror.ErrContinuousValidatorCfgNotFound.Generate(i, inst.ContinuousValidatorConfigName)
}
globalConfigReferCount[configRefPrefixes[validatorIdx]+inst.ContinuousValidatorConfigName]++
if rule != nil {
inst.ContinuousValidator = *rule
}
}
// for backward compatible, set global config `ansi-quotes: true` if any syncer is true
if inst.Syncer.EnableANSIQuotes {
log.L().Warn("DM could discover proper ANSI_QUOTES, `enable-ansi-quotes` is no longer take effect")
}
if inst.Syncer.DisableCausality {
log.L().Warn("`disable-causality` is no longer take effect")
}
for _, name := range inst.ExpressionFilters {
if _, ok := c.ExprFilter[name]; !ok {
return terror.ErrConfigExprFilterNotFound.Generate(i, name)
}
globalConfigReferCount[configRefPrefixes[exprFilterIdx]+name]++
}
if dupeRules := checkDuplicateString(inst.RouteRules); len(dupeRules) > 0 {
duplicateErrorStrings = append(duplicateErrorStrings, fmt.Sprintf("mysql-instance(%d)'s route-rules: %s", i, strings.Join(dupeRules, ", ")))
}
if dupeRules := checkDuplicateString(inst.FilterRules); len(dupeRules) > 0 {
duplicateErrorStrings = append(duplicateErrorStrings, fmt.Sprintf("mysql-instance(%d)'s filter-rules: %s", i, strings.Join(dupeRules, ", ")))
}
if dupeRules := checkDuplicateString(inst.ColumnMappingRules); len(dupeRules) > 0 {
duplicateErrorStrings = append(duplicateErrorStrings, fmt.Sprintf("mysql-instance(%d)'s column-mapping-rules: %s", i, strings.Join(dupeRules, ", ")))
}
if dupeRules := checkDuplicateString(inst.ExpressionFilters); len(dupeRules) > 0 {
duplicateErrorStrings = append(duplicateErrorStrings, fmt.Sprintf("mysql-instance(%d)'s expression-filters: %s", i, strings.Join(dupeRules, ", ")))
}
}
if len(duplicateErrorStrings) > 0 {
return terror.ErrConfigDuplicateCfgItem.Generate(strings.Join(duplicateErrorStrings, "\n"))
}
var unusedConfigs []string
for route := range c.Routes {
if globalConfigReferCount[configRefPrefixes[routeRulesIdx]+route] == 0 {
unusedConfigs = append(unusedConfigs, route)
}
}
for filter := range c.Filters {
if globalConfigReferCount[configRefPrefixes[filterRulesIdx]+filter] == 0 {
unusedConfigs = append(unusedConfigs, filter)
}
}
for mydumper := range c.Mydumpers {
if globalConfigReferCount[configRefPrefixes[mydumperIdx]+mydumper] == 0 {
unusedConfigs = append(unusedConfigs, mydumper)
}
}