2026-08-15 01:27:23 +08:00

120 lines
3.1 KiB
Go

// Package config 提供 Agent 与 Gateway 的配置加载(环境变量优先,内置默认值)。
package config
import (
"os"
"strconv"
"strings"
"time"
)
// AgentConfig 是 Agent 端运行配置。
type AgentConfig struct {
HostID string
AgentVersion string
Service string
GatewayURL string
AgentToken string
LogFiles []string
CoreInterval time.Duration
DiskInterval time.Duration
NetworkInterval time.Duration
ProcessInterval time.Duration
BatchSize int
FlushInterval time.Duration
CheckpointDriver string // memory | file | redis
CheckpointFile string
RedisURL string
CollectTimeout time.Duration
}
// DefaultAgentConfig 返回 Agent 默认配置。
func DefaultAgentConfig() AgentConfig {
return AgentConfig{
HostID: env("HMS_HOST_ID", "host-001"),
AgentVersion: env("HMS_AGENT_VERSION", "0.1.0"),
Service: env("HMS_SERVICE", "host"),
GatewayURL: env("HMS_GATEWAY_URL", "http://127.0.0.1:4318"),
AgentToken: env("HMS_AGENT_TOKEN", "dev-token"),
LogFiles: splitCSV(env("HMS_LOG_FILES", "")),
CoreInterval: durEnv("HMS_CORE_INTERVAL", 15*time.Second),
DiskInterval: durEnv("HMS_DISK_INTERVAL", 30*time.Second),
NetworkInterval: durEnv("HMS_NETWORK_INTERVAL", 30*time.Second),
ProcessInterval: durEnv("HMS_PROCESS_INTERVAL", 60*time.Second),
BatchSize: intEnv("HMS_BATCH_SIZE", 128),
FlushInterval: durEnv("HMS_FLUSH_INTERVAL", 10*time.Second),
CheckpointDriver: env("HMS_CHECKPOINT_DRIVER", "file"),
CheckpointFile: env("HMS_CHECKPOINT_FILE", "checkpoint.json"),
RedisURL: env("HMS_REDIS_URL", "redis://127.0.0.1:6379/0"),
CollectTimeout: durEnv("HMS_COLLECT_TIMEOUT", 5*time.Second),
}
}
// GatewayConfig 是服务端 Collector Gateway 配置。
type GatewayConfig struct {
Addr string
AgentToken string
// 查询内存存储的保留上限。
MaxMetricsPerHost int
MaxLogsPerHost int
RedisURL string
}
// DefaultGatewayConfig 返回 Gateway 默认配置。
func DefaultGatewayConfig() GatewayConfig {
return GatewayConfig{
Addr: env("HMS_GATEWAY_ADDR", "0.0.0.0:4318"),
AgentToken: env("HMS_AGENT_TOKEN", "dev-token"),
MaxMetricsPerHost: intEnv("HMS_MAX_METRICS_PER_HOST", 20000),
MaxLogsPerHost: intEnv("HMS_MAX_LOGS_PER_HOST", 20000),
RedisURL: env("HMS_REDIS_URL", "redis://127.0.0.1:6379/0"),
}
}
func env(key, def string) string {
if v, ok := os.LookupEnv(key); ok && v != "" {
return v
}
return def
}
func durEnv(key string, def time.Duration) time.Duration {
if v, ok := os.LookupEnv(key); ok && v != "" {
if d, err := time.ParseDuration(v); err == nil {
return d
}
}
return def
}
func intEnv(key string, def int) int {
if v, ok := os.LookupEnv(key); ok && v != "" {
if n, err := strconv.Atoi(v); err == nil {
return n
}
}
return def
}
func splitCSV(v string) []string {
if v == "" {
return nil
}
parts := strings.Split(v, ",")
out := make([]string, 0, len(parts))
for _, p := range parts {
if p = strings.TrimSpace(p); p != "" {
out = append(out, p)
}
}
return out
}