liuhaijun 3f5f28d785 add sheduling agent
Change-Id: I89f35fb3984044c57f10727432755012542f9fd8
2023-11-16 10:55:57 +00:00

112 lines
2.6 KiB
Go

package config
import (
"os"
"path/filepath"
"sync"
"git.inspur.com/sbg-jszt/cfn/cfn-schedule-agent/pkg/utils"
"github.com/spf13/viper"
)
// Conf 配置项主结构体
// mapstructure(配置文件属性名称无法与类属性名称直接对应)
type Conf struct {
AppConfig `yaml:"app" mapstructure:"app"`
Server ServerConfig `yaml:"server" mapstructure:"server"`
PostgreSql PostgreSqlConfigMap `yaml:"postgres" mapstructure:"postgres"`
Redis RedisConfig `yaml:"redis" mapstructure:"redis"`
Nats NatsConfig `yaml:"nats_config" mapstructure:"nats_config"`
//Minio MinioConfig `yaml:"minio" mapstructure:"minio"`
Logger LoggerConfig `yaml:"logger" mapstructure:"logger"`
Schedule ScheduleServer `yaml:"schedule" mapstructure:"schedule"`
AgentVersion string `yaml:"agent_version" mapstructure:"agent_version"`
ZombieCleaner bool `yaml:"zombie_cleaner" mapstructure:"zombie_cleaner"`
}
var Config = &Conf{
AppConfig: App,
Server: Server,
PostgreSql: PostgreSql,
Redis: Redis,
Nats: Nats,
//Minio: Minio,
Logger: Logger,
Schedule: Schedule,
}
var once sync.Once
func InitConfig(configPath string) {
once.Do(func() {
// 加载 .yaml 配置
loadYaml(configPath)
})
}
// todo 环境变量注入配置 or 与nacos集成
func loadYaml(configPath string) {
var yamlConfig string
if configPath == "" {
runDirectory, _ := utils.GetCurrentPath()
yamlConfig = filepath.Join(runDirectory, "/config.yaml")
} else {
yamlConfig = filepath.Join(configPath)
}
viper.SetConfigFile(yamlConfig)
viper.SetConfigType("yaml")
err := viper.ReadInConfig()
if err != nil {
panic("Failed to read configuration file:" + err.Error())
}
for _, key := range viper.AllKeys() {
value := viper.GetString(key)
realValue := expandValueEnv(value)
if value != realValue {
viper.Set(key, realValue)
}
}
err = viper.Unmarshal(Config)
if err != nil {
panic("Failed to load configuration:" + err.Error())
}
}
func expandValueEnv(value string) (realValue string) {
realValue = value
vLen := len(value)
// 3 = ${}
if vLen < 3 {
return
}
// Need start with "${" and end with "}", then return.
if value[0] != '$' || value[1] != '{' || value[vLen-1] != '}' {
return
}
key := ""
defaultV := ""
// value start with "${"
for i := 2; i < vLen; i++ {
if value[i] == '|' && (i+1 < vLen && value[i+1] == '|') {
key = value[2:i]
defaultV = value[i+2 : vLen-1] // other string is default value.
break
} else if value[i] == '}' {
key = value[2:i]
break
}
}
realValue = os.Getenv(key)
if realValue == "" {
realValue = defaultV
}
return
}