github.com/pingcap/tiflow@v0.0.0-20240520035814-5bf52d54e205/tests/integration_tests/util/config.go (about) 1 // Copyright 2020 PingCAP, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // See the License for the specific language governing permissions and 12 // limitations under the License. 13 14 package util 15 16 import ( 17 "flag" 18 "fmt" 19 20 "github.com/BurntSushi/toml" 21 "github.com/pingcap/errors" 22 ) 23 24 // NewConfig creates a new config. 25 func NewConfig() *Config { 26 cfg := &Config{} 27 cfg.FlagSet = flag.NewFlagSet("ticdcTest", flag.ContinueOnError) 28 fs := cfg.FlagSet 29 30 fs.StringVar(&cfg.configFile, "config", "", "Config file") 31 fs.IntVar(&cfg.WorkerCount, "c", 1, "parallel worker count") 32 fs.IntVar(&cfg.JobCount, "n", 1, "total job count") 33 fs.IntVar(&cfg.Batch, "b", 1, "insert batch commit count") 34 fs.StringVar(&cfg.LogLevel, "L", "info", "log level: debug, info, warn, error, fatal") 35 36 return cfg 37 } 38 39 // Config is the configuration. 40 type Config struct { 41 *flag.FlagSet `json:"-"` 42 43 LogLevel string `toml:"log-level" json:"log-level"` 44 45 WorkerCount int `toml:"worker-count" json:"worker-count"` 46 47 JobCount int `toml:"job-count" json:"job-count"` 48 49 Batch int `toml:"batch" json:"batch"` 50 51 PDAddr string `toml:"pd" json:"pd"` 52 53 SourceDBCfg []DBConfig `toml:"source-db" json:"source-db"` 54 55 TargetDBCfg DBConfig `toml:"target-db" json:"target-db"` 56 57 configFile string 58 } 59 60 // Parse parses flag definitions from the argument list. 61 func (c *Config) Parse(arguments []string) error { 62 // Parse first to get config file. 63 err := c.FlagSet.Parse(arguments) 64 if err != nil { 65 return errors.Trace(err) 66 } 67 68 // Load config file if specified. 69 if c.configFile != "" { 70 err = c.configFromFile(c.configFile) 71 if err != nil { 72 return errors.Trace(err) 73 } 74 } 75 76 // Parse again to replace with command line options. 77 err = c.FlagSet.Parse(arguments) 78 if err != nil { 79 return errors.Trace(err) 80 } 81 82 if len(c.FlagSet.Args()) != 0 { 83 return errors.Errorf("'%s' is an invalid flag", c.FlagSet.Arg(0)) 84 } 85 86 return nil 87 } 88 89 func (c *Config) String() string { 90 if c == nil { 91 return "<nil>" 92 } 93 return fmt.Sprintf("Config(%+v)", *c) 94 } 95 96 // configFromFile loads config from file. 97 func (c *Config) configFromFile(path string) error { 98 _, err := toml.DecodeFile(path, c) 99 return errors.Trace(err) 100 }