package config import ( "agent-wdd/log" "agent-wdd/utils" "os" "runtime" "github.com/spf13/viper" "gopkg.in/yaml.v3" ) var WddConfigFilePath = "/usr/local/etc/wdd/agent-wdd-config.yaml" // ConfigCache 配置缓存 var ConfigCache = &Config{ TimeStamp: "", ModifiedTimes: 0, Agent: Agent{ OS: OS{}, Network: Network{}, CPU: CPU{}, Mem: Memory{}, Swap: Swap{}, Disks: []Disk{}, }, } func init() { // 根据运行的操作系统不同, 修改 WddConfigFilePath 的位置 if runtime.GOOS == "windows" { homedir, _ := os.UserHomeDir() WddConfigFilePath = homedir + "\\agent-wdd\\agent-wdd-config.yaml" } } type Config struct { TimeStamp string `yaml:"timestamp"` ModifiedTimes int `yaml:"modifiedTimes"` Agent Agent `yaml:"agent"` } type Agent struct { OS OS `yaml:"os"` Network Network `yaml:"network"` CPU CPU `yaml:"cpu"` Mem Memory `yaml:"mem"` Swap Swap `yaml:"swap"` Disks []Disk `yaml:"disks"` } type OS struct { Hostname string `yaml:"hostname"` OsName string `yaml:"os_name"` OsFamily string `yaml:"os_family"` OsVersion string `yaml:"os_version"` OsType string `yaml:"os_type"` Kernel string `yaml:"kernel"` Arch string `yaml:"arch"` IsUbuntuType bool `yaml:"is_ubuntu_type",comment:"是否是ubuntu类型的操作系统"` PackInit bool `yaml:"pack_init",comment:"是否初始化,ubuntu需要"` } type Network struct { Internet int `yaml:"internet"` Public PublicInfo `yaml:"public"` Interfaces []Interface `yaml:"interfaces"` } type PublicInfo struct { IPv4 string `yaml:"ipv4"` IPv6 string `yaml:"ipv6"` Country string `yaml:"country"` City string `yaml:"city"` ASN string `yaml:"asn"` } type Interface struct { Name string `yaml:"name"` IPv4 string `yaml:"ipv4"` IPv6 string `yaml:"ipv6"` MAC string `yaml:"mac"` } type CPU struct { Cores int `yaml:"cores"` Brand string `yaml:"brand"` Mhz string `yaml:"mhz"` Arch string `yaml:"arch"` Virt string `yaml:"virt"` Hypervisor string `yaml:"hypervisor"` } type Memory struct { Size string `yaml:"size"` Type string `yaml:"type"` Speed int `yaml:"speed"` } type Swap struct { Open bool `yaml:"open"` Size string `yaml:"size"` } type Disk struct { Path string `yaml:"path"` Size string `yaml:"size"` Usage string `yaml:"usage"` Percent string `yaml:"percent"` } func InitConfig() { // 检查配置文件是否存在 if !utils.FileOrFolderExists(WddConfigFilePath) { utils.AppendContentToFile("", WddConfigFilePath) } v := viper.New() v.SetConfigFile(WddConfigFilePath) v.SetConfigType("yaml") if err := v.ReadInConfig(); err != nil { log.Error("读取配置文件失败: %w", err) panic(err) } if err := v.Unmarshal(&ConfigCache); err != nil { log.Error("解析配置失败: %w", err) panic(err) } } // 写入配置文件 func SaveConfig() { // 每次写入新的时间 ConfigCache.TimeStamp = utils.CurrentTimeString() // 每次增加修改文件的次数计数 ConfigCache.ModifiedTimes += 1 data, err := yaml.Marshal(&ConfigCache) if err != nil { log.Error("YAML序列化失败: %w", err) } if err := os.WriteFile(WddConfigFilePath, data, 0644); err != nil { log.Error("写入文件失败: %w", err) } }