forked from pingcap/tidb
/
config.go
1493 lines (1340 loc) · 53.8 KB
/
config.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,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package config
import (
"context"
"crypto/tls"
"encoding/json"
"fmt"
"math"
"net"
"net/url"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"time"
"unicode/utf8"
"github.com/BurntSushi/toml"
"github.com/docker/go-units"
gomysql "github.com/go-sql-driver/mysql"
"github.com/pingcap/errors"
"github.com/twotigers93/tidb/br/pkg/lightning/common"
"github.com/twotigers93/tidb/br/pkg/lightning/log"
tidbcfg "github.com/twotigers93/tidb/config"
"github.com/twotigers93/tidb/parser/mysql"
"github.com/twotigers93/tidb/util"
filter "github.com/twotigers93/tidb/util/table-filter"
router "github.com/twotigers93/tidb/util/table-router"
"go.uber.org/atomic"
"go.uber.org/zap"
)
// constants for config items
const (
// ImportMode defines mode of import for tikv.
ImportMode = "import"
// NormalMode defines mode of normal for tikv.
NormalMode = "normal"
// BackendTiDB is a constant for choosing the "TiDB" backend in the configuration.
BackendTiDB = "tidb"
// BackendLocal is a constant for choosing the "Local" backup in the configuration.
// In this mode, we write & sort kv pairs with local storage and directly write them to tikv.
BackendLocal = "local"
// CheckpointDriverMySQL is a constant for choosing the "MySQL" checkpoint driver in the configuration.
CheckpointDriverMySQL = "mysql"
// CheckpointDriverFile is a constant for choosing the "File" checkpoint driver in the configuration.
CheckpointDriverFile = "file"
// ReplaceOnDup indicates using REPLACE INTO to insert data
ReplaceOnDup = "replace"
// IgnoreOnDup indicates using INSERT IGNORE INTO to insert data
IgnoreOnDup = "ignore"
// ErrorOnDup indicates using INSERT INTO to insert data, which would violate PK or UNIQUE constraint
ErrorOnDup = "error"
KVWriteBatchSize = 32768
DefaultRangeConcurrency = 16
defaultDistSQLScanConcurrency = 15
defaultBuildStatsConcurrency = 20
defaultIndexSerialScanConcurrency = 20
defaultChecksumTableConcurrency = 2
DefaultTableConcurrency = 6
defaultIndexConcurrency = 2
DefaultRegionCheckBackoffLimit = 1800
DefaultRegionSplitBatchSize = 4096
// defaultMetaSchemaName is the default database name used to store lightning metadata
defaultMetaSchemaName = "lightning_metadata"
defaultTaskInfoSchemaName = "lightning_task_info"
// autoDiskQuotaLocalReservedSpeed is the estimated size increase per
// millisecond per write thread the local backend may gain on all engines.
// This is used to compute the maximum size overshoot between two disk quota
// checks, if the first one has barely passed.
//
// With cron.check-disk-quota = 1m, region-concurrency = 40, this should
// contribute 2.3 GiB to the reserved size.
// autoDiskQuotaLocalReservedSpeed uint64 = 1 * units.KiB
DefaultEngineMemCacheSize = 512 * units.MiB
DefaultLocalWriterMemCacheSize = 128 * units.MiB
defaultCSVDataCharacterSet = "binary"
defaultCSVDataInvalidCharReplace = utf8.RuneError
)
var (
supportedStorageTypes = []string{"file", "local", "s3", "noop", "gcs", "gs"}
defaultFilter = []string{
"*.*",
"!mysql.*",
"!sys.*",
"!INFORMATION_SCHEMA.*",
"!PERFORMANCE_SCHEMA.*",
"!METRICS_SCHEMA.*",
"!INSPECTION_SCHEMA.*",
}
)
// GetDefaultFilter gets the default table filter used in Lightning.
// It clones the original default filter,
// so that the original value won't be changed when the returned slice's element is changed.
func GetDefaultFilter() []string {
return append([]string{}, defaultFilter...)
}
// DBStore is the database connection information.
type DBStore struct {
Host string `toml:"host" json:"host"`
Port int `toml:"port" json:"port"`
User string `toml:"user" json:"user"`
Psw string `toml:"password" json:"-"`
StatusPort int `toml:"status-port" json:"status-port"`
PdAddr string `toml:"pd-addr" json:"pd-addr"`
StrSQLMode string `toml:"sql-mode" json:"sql-mode"`
TLS string `toml:"tls" json:"tls"`
Security *Security `toml:"security" json:"security"`
SQLMode mysql.SQLMode `toml:"-" json:"-"`
MaxAllowedPacket uint64 `toml:"max-allowed-packet" json:"max-allowed-packet"`
DistSQLScanConcurrency int `toml:"distsql-scan-concurrency" json:"distsql-scan-concurrency"`
BuildStatsConcurrency int `toml:"build-stats-concurrency" json:"build-stats-concurrency"`
IndexSerialScanConcurrency int `toml:"index-serial-scan-concurrency" json:"index-serial-scan-concurrency"`
ChecksumTableConcurrency int `toml:"checksum-table-concurrency" json:"checksum-table-concurrency"`
Vars map[string]string `toml:"-" json:"vars"`
IOTotalBytes *atomic.Uint64 `toml:"-" json:"-"`
UUID string `toml:"-" json:"-"`
}
// Config is the configuration.
type Config struct {
TaskID int64 `toml:"-" json:"id"`
App Lightning `toml:"lightning" json:"lightning"`
TiDB DBStore `toml:"tidb" json:"tidb"`
Checkpoint Checkpoint `toml:"checkpoint" json:"checkpoint"`
Mydumper MydumperRuntime `toml:"mydumper" json:"mydumper"`
TikvImporter TikvImporter `toml:"tikv-importer" json:"tikv-importer"`
PostRestore PostRestore `toml:"post-restore" json:"post-restore"`
Cron Cron `toml:"cron" json:"cron"`
Routes []*router.TableRule `toml:"routes" json:"routes"`
Security Security `toml:"security" json:"security"`
BWList filter.MySQLReplicationRules `toml:"black-white-list" json:"black-white-list"`
}
// String implements fmt.Stringer interface.
func (cfg *Config) String() string {
bytes, err := json.Marshal(cfg)
if err != nil {
log.L().Error("marshal config to json error", log.ShortError(err))
}
return string(bytes)
}
// ToTLS creates a common.TLS from the config.
func (cfg *Config) ToTLS() (*common.TLS, error) {
hostPort := net.JoinHostPort(cfg.TiDB.Host, strconv.Itoa(cfg.TiDB.StatusPort))
return common.NewTLS(
cfg.Security.CAPath,
cfg.Security.CertPath,
cfg.Security.KeyPath,
hostPort,
cfg.Security.CABytes,
cfg.Security.CertBytes,
cfg.Security.KeyBytes,
)
}
// Lightning is the root configuration of lightning.
type Lightning struct {
TableConcurrency int `toml:"table-concurrency" json:"table-concurrency"`
IndexConcurrency int `toml:"index-concurrency" json:"index-concurrency"`
RegionConcurrency int `toml:"region-concurrency" json:"region-concurrency"`
IOConcurrency int `toml:"io-concurrency" json:"io-concurrency"`
CheckRequirements bool `toml:"check-requirements" json:"check-requirements"`
MetaSchemaName string `toml:"meta-schema-name" json:"meta-schema-name"`
MaxError MaxError `toml:"max-error" json:"max-error"`
TaskInfoSchemaName string `toml:"task-info-schema-name" json:"task-info-schema-name"`
}
// PostOpLevel represents the level of post-operation.
type PostOpLevel int
// PostOpLevel constants.
const (
OpLevelOff PostOpLevel = iota
OpLevelOptional
OpLevelRequired
)
// UnmarshalTOML implements toml.Unmarshaler interface.
func (t *PostOpLevel) UnmarshalTOML(v interface{}) error {
switch val := v.(type) {
case bool:
if val {
*t = OpLevelRequired
} else {
*t = OpLevelOff
}
case string:
return t.FromStringValue(val)
default:
return errors.Errorf("invalid op level '%v', please choose valid option between ['off', 'optional', 'required']", v)
}
return nil
}
// MarshalText implements encoding.TextMarshaler interface.
func (t PostOpLevel) MarshalText() ([]byte, error) {
return []byte(t.String()), nil
}
// FromStringValue parse command line parameter.
func (t *PostOpLevel) FromStringValue(s string) error {
switch strings.ToLower(s) {
//nolint:goconst // This 'false' and other 'false's aren't the same.
case "off", "false":
*t = OpLevelOff
case "required", "true":
*t = OpLevelRequired
case "optional":
*t = OpLevelOptional
default:
return errors.Errorf("invalid op level '%s', please choose valid option between ['off', 'optional', 'required']", s)
}
return nil
}
// MarshalJSON implements json.Marshaler interface.
func (t *PostOpLevel) MarshalJSON() ([]byte, error) {
return []byte(`"` + t.String() + `"`), nil
}
// UnmarshalJSON implements json.Unmarshaler interface.
func (t *PostOpLevel) UnmarshalJSON(data []byte) error {
return t.FromStringValue(strings.Trim(string(data), `"`))
}
// String returns the string representation of the level.
func (t PostOpLevel) String() string {
switch t {
case OpLevelOff:
return "off"
case OpLevelOptional:
return "optional"
case OpLevelRequired:
return "required"
default:
panic(fmt.Sprintf("invalid post process type '%d'", t))
}
}
// CheckpointKeepStrategy represents the strategy to keep checkpoint data.
type CheckpointKeepStrategy int
const (
// CheckpointRemove remove checkpoint data
CheckpointRemove CheckpointKeepStrategy = iota
// CheckpointRename keep by rename checkpoint file/db according to task id
CheckpointRename
// CheckpointOrigin keep checkpoint data unchanged
CheckpointOrigin
)
// UnmarshalTOML implements toml.Unmarshaler interface.
func (t *CheckpointKeepStrategy) UnmarshalTOML(v interface{}) error {
switch val := v.(type) {
case bool:
if val {
*t = CheckpointRename
} else {
*t = CheckpointRemove
}
case string:
return t.FromStringValue(val)
default:
return errors.Errorf("invalid checkpoint keep strategy '%v', please choose valid option between ['remove', 'rename', 'origin']", v)
}
return nil
}
// MarshalText implements encoding.TextMarshaler interface.
func (t CheckpointKeepStrategy) MarshalText() ([]byte, error) {
return []byte(t.String()), nil
}
// FromStringValue parser command line parameter.
func (t *CheckpointKeepStrategy) FromStringValue(s string) error {
switch strings.ToLower(s) {
//nolint:goconst // This 'false' and other 'false's aren't the same.
case "remove", "false":
*t = CheckpointRemove
case "rename", "true":
*t = CheckpointRename
case "origin":
*t = CheckpointOrigin
default:
return errors.Errorf("invalid checkpoint keep strategy '%s', please choose valid option between ['remove', 'rename', 'origin']", s)
}
return nil
}
// MarshalJSON implements json.Marshaler interface.
func (t *CheckpointKeepStrategy) MarshalJSON() ([]byte, error) {
return []byte(`"` + t.String() + `"`), nil
}
// UnmarshalJSON implements json.Unmarshaler interface.
func (t *CheckpointKeepStrategy) UnmarshalJSON(data []byte) error {
return t.FromStringValue(strings.Trim(string(data), `"`))
}
// String implements fmt.Stringer interface.
func (t CheckpointKeepStrategy) String() string {
switch t {
case CheckpointRemove:
return "remove"
case CheckpointRename:
return "rename"
case CheckpointOrigin:
return "origin"
default:
panic(fmt.Sprintf("invalid post process type '%d'", t))
}
}
// MaxError configures the maximum number of acceptable errors per kind.
type MaxError struct {
// Syntax is the maximum number of syntax errors accepted.
// When tolerated, the file chunk causing syntax error will be skipped, and adds 1 to the counter.
// TODO Currently this is hard-coded to zero.
Syntax atomic.Int64 `toml:"syntax" json:"-"`
// Charset is the maximum number of character-set conversion errors accepted.
// When tolerated, and `data-invalid-char-replace` is not changed from "\ufffd",
// every invalid byte in the source file will be converted to U+FFFD and adds 1 to the counter.
// Note that a failed conversion a column's character set (e.g. UTF8-to-GBK conversion)
// is counted as a type error, not a charset error.
// TODO character-set conversion is not yet implemented.
Charset atomic.Int64 `toml:"charset" json:"-"`
// Type is the maximum number of type errors accepted.
// This includes strict-mode errors such as zero in dates, integer overflow, character string too long, etc.
// In TiDB backend, this also includes all possible SQL errors raised from INSERT,
// such as unique key conflict when `on-duplicate` is set to `error`.
// When tolerated, the row causing the error will be skipped, and adds 1 to the counter.
// The default value is zero, which means that such errors are not tolerated.
Type atomic.Int64 `toml:"type" json:"type"`
// Conflict is the maximum number of unique key conflicts in local backend accepted.
// When tolerated, every pair of conflict adds 1 to the counter.
// Those pairs will NOT be deleted from the target. Conflict resolution is performed separately.
// The default value is max int64, which means conflict errors will be recorded as much as possible.
// Sometime the actual number of conflict record logged will be greater than the value configured here,
// because conflict error data are recorded batch by batch.
// If the limit is reached in a single batch, the entire batch of records will be persisted before an error is reported.
Conflict atomic.Int64 `toml:"conflict" json:"conflict"`
}
// UnmarshalTOML implements toml.Unmarshaler interface.
func (cfg *MaxError) UnmarshalTOML(v interface{}) error {
defaultValMap := map[string]int64{
"syntax": 0,
"charset": math.MaxInt64,
"type": 0,
"conflict": math.MaxInt64,
}
// set default value first
cfg.Syntax.Store(defaultValMap["syntax"])
cfg.Charset.Store(defaultValMap["charset"])
cfg.Type.Store(defaultValMap["type"])
cfg.Conflict.Store(defaultValMap["conflict"])
switch val := v.(type) {
case int64:
// ignore val that is smaller than 0
if val >= 0 {
// only set type error
cfg.Type.Store(val)
}
return nil
case map[string]interface{}:
// support stuff like `max-error = { charset = 1000, type = 1000 }`.
getVal := func(k string, v interface{}) int64 {
defaultVal, ok := defaultValMap[k]
if !ok {
return 0
}
iVal, ok := v.(int64)
if !ok || iVal < 0 {
return defaultVal
}
return iVal
}
for k, v := range val {
switch k {
case "type":
cfg.Type.Store(getVal(k, v))
case "conflict":
cfg.Conflict.Store(getVal(k, v))
}
}
return nil
default:
return errors.Errorf("invalid max-error '%v', should be an integer or a map of string:int64", v)
}
}
// PausePDSchedulerScope the scope when pausing pd schedulers.
type PausePDSchedulerScope string
// constants for PausePDSchedulerScope.
const (
// PausePDSchedulerScopeTable pause scheduler by adding schedule=deny label to target key range of the table.
PausePDSchedulerScopeTable PausePDSchedulerScope = "table"
// PausePDSchedulerScopeGlobal pause scheduler by remove global schedulers.
// schedulers removed includes:
// - balance-leader-scheduler
// - balance-hot-region-scheduler
// - balance-region-scheduler
// - shuffle-leader-scheduler
// - shuffle-region-scheduler
// - shuffle-hot-region-scheduler
// and we also set configs below:
// - max-merge-region-keys = 0
// - max-merge-region-size = 0
// - leader-schedule-limit = min(40, <store-count> * <current value of leader-schedule-limit>)
// - region-schedule-limit = min(40, <store-count> * <current value of region-schedule-limit>)
// - max-snapshot-count = min(40, <store-count> * <current value of max-snapshot-count>)
// - enable-location-replacement = false
// - max-pending-peer-count = math.MaxInt32
// see br/pkg/pdutil/pd.go for more detail.
PausePDSchedulerScopeGlobal PausePDSchedulerScope = "global"
)
// DuplicateResolutionAlgorithm is the config type of how to resolve duplicates.
type DuplicateResolutionAlgorithm int
const (
// DupeResAlgNone doesn't detect duplicate.
DupeResAlgNone DuplicateResolutionAlgorithm = iota
// DupeResAlgRecord only records duplicate records to `lightning_task_info.conflict_error_v1` table on the target TiDB.
DupeResAlgRecord
// DupeResAlgRemove records all duplicate records like the 'record' algorithm and remove all information related to the
// duplicated rows. Users need to analyze the lightning_task_info.conflict_error_v1 table to add back the correct rows.
DupeResAlgRemove
// DupeResAlgErr reports an error and stops the import process.
// Note: this value is only used for internal.
DupeResAlgErr
)
// UnmarshalTOML implements the toml.Unmarshaler interface.
func (dra *DuplicateResolutionAlgorithm) UnmarshalTOML(v interface{}) error {
if val, ok := v.(string); ok {
return dra.FromStringValue(val)
}
return errors.Errorf("invalid duplicate-resolution '%v', please choose valid option between ['record', 'none', 'remove']", v)
}
// MarshalText implements the encoding.TextMarshaler interface.
func (dra DuplicateResolutionAlgorithm) MarshalText() ([]byte, error) {
return []byte(dra.String()), nil
}
// FromStringValue parses the string value to the DuplicateResolutionAlgorithm.
func (dra *DuplicateResolutionAlgorithm) FromStringValue(s string) error {
switch strings.ToLower(s) {
case "record":
*dra = DupeResAlgRecord
case "none":
*dra = DupeResAlgNone
case "remove":
*dra = DupeResAlgRemove
default:
return errors.Errorf("invalid duplicate-resolution '%s', please choose valid option between ['record', 'none', 'remove']", s)
}
return nil
}
// MarshalJSON implements the json.Marshaler interface.
func (dra *DuplicateResolutionAlgorithm) MarshalJSON() ([]byte, error) {
return []byte(`"` + dra.String() + `"`), nil
}
// UnmarshalJSON implements the json.Unmarshaler interface.
func (dra *DuplicateResolutionAlgorithm) UnmarshalJSON(data []byte) error {
return dra.FromStringValue(strings.Trim(string(data), `"`))
}
// String implements the fmt.Stringer interface.
func (dra DuplicateResolutionAlgorithm) String() string {
switch dra {
case DupeResAlgRecord:
return "record"
case DupeResAlgNone:
return "none"
case DupeResAlgRemove:
return "remove"
default:
panic(fmt.Sprintf("invalid duplicate-resolution type '%d'", dra))
}
}
// CompressionType is the config type of compression algorithm.
type CompressionType int
const (
// CompressionNone means no compression.
CompressionNone CompressionType = iota
// CompressionGzip means gzip compression.
CompressionGzip
)
// UnmarshalTOML implements toml.Unmarshaler.
func (t *CompressionType) UnmarshalTOML(v interface{}) error {
if val, ok := v.(string); ok {
return t.FromStringValue(val)
}
return errors.Errorf("invalid compression-type '%v', please choose valid option between ['gzip']", v)
}
// MarshalText implements encoding.TextMarshaler.
func (t CompressionType) MarshalText() ([]byte, error) {
return []byte(t.String()), nil
}
// FromStringValue parses a string to CompressionType.
func (t *CompressionType) FromStringValue(s string) error {
switch strings.ToLower(s) {
case "":
*t = CompressionNone
case "gz", "gzip":
*t = CompressionGzip
default:
return errors.Errorf("invalid compression-type '%s', please choose valid option between ['gzip']", s)
}
return nil
}
// MarshalJSON implements json.Marshaler.
func (t *CompressionType) MarshalJSON() ([]byte, error) {
return []byte(`"` + t.String() + `"`), nil
}
// UnmarshalJSON implements json.Unmarshaler.
func (t *CompressionType) UnmarshalJSON(data []byte) error {
return t.FromStringValue(strings.Trim(string(data), `"`))
}
// String implements fmt.Stringer.
func (t CompressionType) String() string {
switch t {
case CompressionGzip:
return "gzip"
case CompressionNone:
return ""
default:
panic(fmt.Sprintf("invalid compression type '%d'", t))
}
}
// PostRestore has some options which will be executed after kv restored.
type PostRestore struct {
Checksum PostOpLevel `toml:"checksum" json:"checksum"`
Analyze PostOpLevel `toml:"analyze" json:"analyze"`
Level1Compact bool `toml:"level-1-compact" json:"level-1-compact"`
PostProcessAtLast bool `toml:"post-process-at-last" json:"post-process-at-last"`
Compact bool `toml:"compact" json:"compact"`
}
// StringOrStringSlice can unmarshal a TOML string as string slice with one element.
type StringOrStringSlice []string
// UnmarshalTOML implements the toml.Unmarshaler interface.
func (s *StringOrStringSlice) UnmarshalTOML(in interface{}) error {
switch v := in.(type) {
case string:
*s = []string{v}
case []interface{}:
*s = make([]string, 0, len(v))
for _, vv := range v {
vs, ok := vv.(string)
if !ok {
return errors.Errorf("invalid string slice '%v'", in)
}
*s = append(*s, vs)
}
default:
return errors.Errorf("invalid string slice '%v'", in)
}
return nil
}
// CSVConfig is the config for CSV files.
type CSVConfig struct {
// Separator, Delimiter and Terminator should all be in utf8mb4 encoding.
Separator string `toml:"separator" json:"separator"`
Delimiter string `toml:"delimiter" json:"delimiter"`
Terminator string `toml:"terminator" json:"terminator"`
Null StringOrStringSlice `toml:"null" json:"null"`
Header bool `toml:"header" json:"header"`
HeaderSchemaMatch bool `toml:"header-schema-match" json:"header-schema-match"`
TrimLastSep bool `toml:"trim-last-separator" json:"trim-last-separator"`
NotNull bool `toml:"not-null" json:"not-null"`
// deprecated, use `escaped-by` instead.
BackslashEscape bool `toml:"backslash-escape" json:"backslash-escape"`
// EscapedBy has higher priority than BackslashEscape, currently it must be a single character if set.
EscapedBy string `toml:"escaped-by" json:"escaped-by"`
// hide these options for lightning configuration file, they can only be used by LOAD DATA
// https://dev.mysql.com/doc/refman/8.0/en/load-data.html#load-data-field-line-handling
StartingBy string `toml:"-" json:"-"`
AllowEmptyLine bool `toml:"-" json:"-"`
// For non-empty Delimiter (for example quotes), null elements inside quotes are not considered as null except for
// `\N` (when escape-by is `\`). That is to say, `\N` is special for null because it always means null.
QuotedNullIsText bool `toml:"-" json:"-"`
// ref https://dev.mysql.com/doc/refman/8.0/en/load-data.html
// > If the field begins with the ENCLOSED BY character, instances of that character are recognized as terminating a
// > field value only if followed by the field or line TERMINATED BY sequence.
// This means we will meet unescaped quote in a quoted field
// > The "BIG" boss -> The "BIG" boss
// This means we will meet unescaped quote in a unquoted field
UnescapedQuote bool `toml:"-" json:"-"`
}
// MydumperRuntime is the runtime config for mydumper.
type MydumperRuntime struct {
ReadBlockSize ByteSize `toml:"read-block-size" json:"read-block-size"`
BatchSize ByteSize `toml:"batch-size" json:"batch-size"`
BatchImportRatio float64 `toml:"batch-import-ratio" json:"batch-import-ratio"`
SourceID string `toml:"source-id" json:"source-id"`
SourceDir string `toml:"data-source-dir" json:"data-source-dir"`
CharacterSet string `toml:"character-set" json:"character-set"`
CSV CSVConfig `toml:"csv" json:"csv"`
MaxRegionSize ByteSize `toml:"max-region-size" json:"max-region-size"`
Filter []string `toml:"filter" json:"filter"`
FileRouters []*FileRouteRule `toml:"files" json:"files"`
// Deprecated: only used to keep the compatibility.
NoSchema bool `toml:"no-schema" json:"no-schema"`
CaseSensitive bool `toml:"case-sensitive" json:"case-sensitive"`
StrictFormat bool `toml:"strict-format" json:"strict-format"`
DefaultFileRules bool `toml:"default-file-rules" json:"default-file-rules"`
IgnoreColumns AllIgnoreColumns `toml:"ignore-data-columns" json:"ignore-data-columns"`
// DataCharacterSet is the character set of the source file. Only CSV files are supported now. The following options are supported.
// - utf8mb4
// - GB18030
// - GBK: an extension of the GB2312 character set and is also known as Code Page 936.
// - binary: no attempt to convert the encoding.
// Leave DataCharacterSet empty will make it use `binary` by default.
DataCharacterSet string `toml:"data-character-set" json:"data-character-set"`
// DataInvalidCharReplace is the replacement characters for non-compatible characters, which shouldn't duplicate with the separators or line breaks.
// Changing the default value will result in increased parsing time. Non-compatible characters do not cause an increase in error.
DataInvalidCharReplace string `toml:"data-invalid-char-replace" json:"data-invalid-char-replace"`
}
// AllIgnoreColumns is a slice of IgnoreColumns.
type AllIgnoreColumns []*IgnoreColumns
// IgnoreColumns is the config for ignoring columns.
type IgnoreColumns struct {
DB string `toml:"db" json:"db"`
Table string `toml:"table" json:"table"`
TableFilter []string `toml:"table-filter" json:"table-filter"`
Columns []string `toml:"columns" json:"columns"`
}
// ColumnsMap returns a map of columns.
func (ic *IgnoreColumns) ColumnsMap() map[string]struct{} {
columnMap := make(map[string]struct{}, len(ic.Columns))
for _, c := range ic.Columns {
columnMap[c] = struct{}{}
}
return columnMap
}
// GetIgnoreColumns gets Ignore config by schema name/regex and table name/regex.
func (igCols AllIgnoreColumns) GetIgnoreColumns(db string, table string, caseSensitive bool) (*IgnoreColumns, error) {
if !caseSensitive {
db = strings.ToLower(db)
table = strings.ToLower(table)
}
for i, ig := range igCols {
if ig.DB == db && ig.Table == table {
return igCols[i], nil
}
f, err := filter.Parse(ig.TableFilter)
if err != nil {
return nil, common.ErrInvalidConfig.GenWithStack("invalid table filter %s in ignore columns", strings.Join(ig.TableFilter, ","))
}
if f.MatchTable(db, table) {
return igCols[i], nil
}
}
return &IgnoreColumns{Columns: make([]string, 0)}, nil
}
// FileRouteRule is the rule for routing files.
type FileRouteRule struct {
Pattern string `json:"pattern" toml:"pattern" yaml:"pattern"`
Path string `json:"path" toml:"path" yaml:"path"`
Schema string `json:"schema" toml:"schema" yaml:"schema"`
Table string `json:"table" toml:"table" yaml:"table"`
Type string `json:"type" toml:"type" yaml:"type"`
Key string `json:"key" toml:"key" yaml:"key"`
Compression string `json:"compression" toml:"compression" yaml:"compression"`
// unescape the schema/table name only used in lightning's internal logic now.
Unescape bool `json:"-" toml:"-" yaml:"-"`
// TODO: DataCharacterSet here can override the same field in [mydumper.csv] with a higher level.
// This could provide users a more flexible usage to configure different files with
// different data charsets.
// DataCharacterSet string `toml:"data-character-set" json:"data-character-set"`
}
// TikvImporter is the config for tikv-importer.
type TikvImporter struct {
// Deprecated: only used to keep the compatibility.
Addr string `toml:"addr" json:"addr"`
Backend string `toml:"backend" json:"backend"`
OnDuplicate string `toml:"on-duplicate" json:"on-duplicate"`
MaxKVPairs int `toml:"max-kv-pairs" json:"max-kv-pairs"`
SendKVPairs int `toml:"send-kv-pairs" json:"send-kv-pairs"`
CompressKVPairs CompressionType `toml:"compress-kv-pairs" json:"compress-kv-pairs"`
RegionSplitSize ByteSize `toml:"region-split-size" json:"region-split-size"`
RegionSplitKeys int `toml:"region-split-keys" json:"region-split-keys"`
RegionSplitBatchSize int `toml:"region-split-batch-size" json:"region-split-batch-size"`
RegionSplitConcurrency int `toml:"region-split-concurrency" json:"region-split-concurrency"`
RegionCheckBackoffLimit int `toml:"region-check-backoff-limit" json:"region-check-backoff-limit"`
SortedKVDir string `toml:"sorted-kv-dir" json:"sorted-kv-dir"`
DiskQuota ByteSize `toml:"disk-quota" json:"disk-quota"`
RangeConcurrency int `toml:"range-concurrency" json:"range-concurrency"`
DuplicateResolution DuplicateResolutionAlgorithm `toml:"duplicate-resolution" json:"duplicate-resolution"`
IncrementalImport bool `toml:"incremental-import" json:"incremental-import"`
KeyspaceName string `toml:"keyspace-name" json:"keyspace-name"`
AddIndexBySQL bool `toml:"add-index-by-sql" json:"add-index-by-sql"`
EngineMemCacheSize ByteSize `toml:"engine-mem-cache-size" json:"engine-mem-cache-size"`
LocalWriterMemCacheSize ByteSize `toml:"local-writer-mem-cache-size" json:"local-writer-mem-cache-size"`
StoreWriteBWLimit ByteSize `toml:"store-write-bwlimit" json:"store-write-bwlimit"`
// default is PausePDSchedulerScopeTable to compatible with previous version(>= 6.1)
PausePDSchedulerScope PausePDSchedulerScope `toml:"pause-pd-scheduler-scope" json:"pause-pd-scheduler-scope"`
}
// Checkpoint is the config for checkpoint.
type Checkpoint struct {
Schema string `toml:"schema" json:"schema"`
DSN string `toml:"dsn" json:"-"` // DSN may contain password, don't expose this to JSON.
MySQLParam *common.MySQLConnectParam `toml:"-" json:"-"` // For some security reason, we use MySQLParam instead of DSN.
Driver string `toml:"driver" json:"driver"`
Enable bool `toml:"enable" json:"enable"`
KeepAfterSuccess CheckpointKeepStrategy `toml:"keep-after-success" json:"keep-after-success"`
}
// Cron is the config for cron.
type Cron struct {
SwitchMode Duration `toml:"switch-mode" json:"switch-mode"`
LogProgress Duration `toml:"log-progress" json:"log-progress"`
CheckDiskQuota Duration `toml:"check-disk-quota" json:"check-disk-quota"`
}
// Security is the config for security.
type Security struct {
CAPath string `toml:"ca-path" json:"ca-path"`
CertPath string `toml:"cert-path" json:"cert-path"`
KeyPath string `toml:"key-path" json:"key-path"`
// RedactInfoLog indicates that whether enabling redact log
RedactInfoLog bool `toml:"redact-info-log" json:"redact-info-log"`
TLSConfig *tls.Config `toml:"-" json:"-"`
AllowFallbackToPlaintext bool `toml:"-" json:"-"`
// When DM/engine uses lightning as a library, it can directly pass in the content
CABytes []byte `toml:"-" json:"-"`
CertBytes []byte `toml:"-" json:"-"`
KeyBytes []byte `toml:"-" json:"-"`
}
// BuildTLSConfig builds the tls config which is used by SQL drier later.
func (sec *Security) BuildTLSConfig() error {
if sec == nil || sec.TLSConfig != nil {
return nil
}
tlsConfig, err := util.NewTLSConfig(
util.WithCAPath(sec.CAPath),
util.WithCertAndKeyPath(sec.CertPath, sec.KeyPath),
util.WithCAContent(sec.CABytes),
util.WithCertAndKeyContent(sec.CertBytes, sec.KeyBytes),
)
if err != nil {
return errors.Trace(err)
}
sec.TLSConfig = tlsConfig
return nil
}
// Duration which can be deserialized from a TOML string.
// Implemented as https://github.com/BurntSushi/toml#using-the-encodingtextunmarshaler-interface
type Duration struct {
time.Duration
}
// UnmarshalText implements encoding.TextUnmarshaler.
func (d *Duration) UnmarshalText(text []byte) error {
var err error
d.Duration, err = time.ParseDuration(string(text))
return errors.Trace(err)
}
// MarshalText implements encoding.TextMarshaler.
func (d Duration) MarshalText() ([]byte, error) {
return []byte(d.String()), nil
}
// MarshalJSON implements json.Marshaler.
func (d *Duration) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, d.Duration)), nil
}
// Charset defines character set
type Charset int
// Charset constants
const (
Binary Charset = iota
UTF8MB4
GB18030
GBK
Latin1
ASCII
)
// String return the string value of charset
func (c Charset) String() string {
switch c {
case Binary:
return "binary"
case UTF8MB4:
return "utf8mb4"
case GB18030:
return "gb18030"
case GBK:
return "gbk"
case Latin1:
return "latin1"
case ASCII:
return "ascii"
default:
return "unknown_charset"
}
}
// ParseCharset parser character set for string
func ParseCharset(dataCharacterSet string) (Charset, error) {
switch strings.ToLower(dataCharacterSet) {
case "", "binary":
return Binary, nil
case "utf8", "utf8mb4":
return UTF8MB4, nil
case "gb18030":
return GB18030, nil
case "gbk":
return GBK, nil
case "latin1":
return Latin1, nil
case "ascii":
return ASCII, nil
default:
return Binary, errors.Errorf("found unsupported data-character-set: %s", dataCharacterSet)
}
}
// NewConfig creates a new Config.
func NewConfig() *Config {
return &Config{
App: Lightning{
RegionConcurrency: runtime.NumCPU(),
TableConcurrency: 0,
IndexConcurrency: 0,
IOConcurrency: 5,
CheckRequirements: true,
MaxError: MaxError{
Charset: *atomic.NewInt64(math.MaxInt64),
Conflict: *atomic.NewInt64(math.MaxInt64),
},
TaskInfoSchemaName: defaultTaskInfoSchemaName,
},
Checkpoint: Checkpoint{
Enable: true,
},
TiDB: DBStore{
Host: "127.0.0.1",
User: "root",
StatusPort: 10080,
StrSQLMode: "ONLY_FULL_GROUP_BY,NO_AUTO_CREATE_USER",
MaxAllowedPacket: defaultMaxAllowedPacket,
BuildStatsConcurrency: defaultBuildStatsConcurrency,
DistSQLScanConcurrency: defaultDistSQLScanConcurrency,
IndexSerialScanConcurrency: defaultIndexSerialScanConcurrency,
ChecksumTableConcurrency: defaultChecksumTableConcurrency,
},
Cron: Cron{
SwitchMode: Duration{Duration: 5 * time.Minute},
LogProgress: Duration{Duration: 5 * time.Minute},
CheckDiskQuota: Duration{Duration: 1 * time.Minute},
},
Mydumper: MydumperRuntime{
ReadBlockSize: ReadBlockSize,
CSV: CSVConfig{
Separator: ",",
Delimiter: `"`,
Header: true,
HeaderSchemaMatch: true,
NotNull: false,
Null: []string{`\N`},
BackslashEscape: true,
EscapedBy: `\`,
TrimLastSep: false,
},
StrictFormat: false,
MaxRegionSize: MaxRegionSize,
Filter: GetDefaultFilter(),
DataCharacterSet: defaultCSVDataCharacterSet,
DataInvalidCharReplace: string(defaultCSVDataInvalidCharReplace),
},
TikvImporter: TikvImporter{
Backend: "",
OnDuplicate: ReplaceOnDup,
MaxKVPairs: 4096,
SendKVPairs: KVWriteBatchSize,
RegionSplitSize: 0,
RegionSplitBatchSize: DefaultRegionSplitBatchSize,
RegionSplitConcurrency: runtime.GOMAXPROCS(0),
RegionCheckBackoffLimit: DefaultRegionCheckBackoffLimit,
DiskQuota: ByteSize(math.MaxInt64),
DuplicateResolution: DupeResAlgNone,
PausePDSchedulerScope: PausePDSchedulerScopeTable,
},
PostRestore: PostRestore{
Checksum: OpLevelRequired,
Analyze: OpLevelOptional,
PostProcessAtLast: true,
},
}
}
// LoadFromGlobal resets the current configuration to the global settings.
func (cfg *Config) LoadFromGlobal(global *GlobalConfig) error {
if err := cfg.LoadFromTOML(global.ConfigFileContent); err != nil {
return err
}
cfg.TiDB.Host = global.TiDB.Host
cfg.TiDB.Port = global.TiDB.Port
cfg.TiDB.User = global.TiDB.User
cfg.TiDB.Psw = global.TiDB.Psw
cfg.TiDB.StatusPort = global.TiDB.StatusPort
cfg.TiDB.PdAddr = global.TiDB.PdAddr
cfg.Mydumper.NoSchema = global.Mydumper.NoSchema
cfg.Mydumper.SourceDir = global.Mydumper.SourceDir
cfg.Mydumper.Filter = global.Mydumper.Filter
cfg.TikvImporter.Backend = global.TikvImporter.Backend
cfg.TikvImporter.SortedKVDir = global.TikvImporter.SortedKVDir
cfg.Checkpoint.Enable = global.Checkpoint.Enable
cfg.PostRestore.Checksum = global.PostRestore.Checksum
cfg.PostRestore.Analyze = global.PostRestore.Analyze
cfg.App.CheckRequirements = global.App.CheckRequirements
cfg.Security = global.Security
cfg.Mydumper.IgnoreColumns = global.Mydumper.IgnoreColumns
return nil
}
// LoadFromTOML overwrites the current configuration by the TOML data
// If data contains toml items not in Config and GlobalConfig, return an error
// If data contains toml items not in Config, thus won't take effect, warn user