package config import ( "errors" "flag" "fmt" "os" "path/filepath" "certmanager/pkg/client" yaml "gopkg.in/yaml.v3" ) const ( defaultHostname = "localhost" configFilename = "certmanagerd.yaml" logFilename = "certmanagerd.log" pidFilename = "certmanagerd.pid" ) var ( buildVersion = "NONE" ) type WserviceConfig struct { PortNum int `json:"port" yaml:"port"` } type GserviceConfig struct { PortNum int `json:"port" yaml:"port"` } type Config struct { Wservice WserviceConfig `json:"wservice" yaml:"wservice"` Gservice GserviceConfig `json:"gservice" yaml:"gservice"` Hostname string `json:"hostname" yaml:"hostname"` Debug bool `json:"debug" yaml:"debug"` Build string `json:"build" yaml:"build"` LogPath string `json:"logfile" yaml:"logfile"` RunPath string `json:"runfile" yaml:"runfile"` DataDir string `json:"datadir" yaml:"datadir"` Daemon bool `json:"daemon" yaml:"daemon"` } func NewConfig() *Config { conf := &Config{ Gservice: GserviceConfig{ PortNum: client.DefaultGrpcPort, }, Wservice: WserviceConfig{ PortNum: client.DefaultWrpcPort, }, DataDir: datadirPath, Debug: false, Hostname: defaultHostname, Build: buildVersion, Daemon: true, } conf.LogPath = filepath.Join(logdirPath, logFilename) conf.RunPath = filepath.Join(rundirPath, pidFilename) return conf } func (conf *Config) ReadFile() error { var err error configPath := filepath.Join(confdirPath, configFilename) confBytes, err := os.ReadFile(configPath) if err != nil { return err } err = yaml.Unmarshal(confBytes, conf) if err != nil { return err } conf.Normalize() err = conf.Validate() if err != nil { return err } return nil } func (conf *Config) ReadEnv() error { var err error return err } func (conf *Config) ReadOpts() error { var err error exeName := filepath.Base(os.Args[0]) flag.IntVar(&conf.Wservice.PortNum, "wport", conf.Wservice.PortNum, "wrpc listen port") flag.IntVar(&conf.Gservice.PortNum, "gport", conf.Gservice.PortNum, "grpc listen port") flag.BoolVar(&conf.Daemon, "daemon", conf.Daemon, "run as daemon") flag.BoolVar(&conf.Debug, "debug", conf.Debug, "on debug mode") help := func() { fmt.Println("") fmt.Printf("Usage: %s [option]\n", exeName) fmt.Println("") fmt.Println("Options:") flag.PrintDefaults() fmt.Println("") } flag.Usage = help flag.Parse() return err } func (conf *Config) Yaml() (string, error) { var err error var res string yamlBytes, err := yaml.Marshal(conf) if err != nil { return res, err } res = string(yamlBytes) return res, err } func (conf *Config) Normalize() { if conf.Gservice.PortNum == 0 { conf.Gservice.PortNum = client.DefaultGrpcPort } if conf.Wservice.PortNum == 0 { conf.Wservice.PortNum = client.DefaultWrpcPort } } func (conf *Config) Validate() error { var err []error return errors.Join(err...) }