💥 feat(agent)!: 添加主机监控代理首版

* 实现周期采集、快照缓存、本地 HTTP API 和主动上报

* 补齐 Linux 和 Windows 主机、网络、资源、进程和 TCP 采集

* 添加服务生命周期管理、配置加载、构建脚本和测试覆盖

BREAKING CHANGE: network.ips 拆分为 network.ipv4s 和 network.ipv6s。
This commit is contained in:
codex
2026-05-18 15:25:51 +00:00
commit 89d5e27874
33 changed files with 4205 additions and 0 deletions

149
internal/config/config.go Normal file
View File

@@ -0,0 +1,149 @@
package config
import (
"encoding/json"
"errors"
"os"
"strconv"
"time"
)
// Config contains all runtime, reporting, collection, and service settings.
type Config struct {
HostID string `json:"host_id"`
HTTP HTTPConfig `json:"http"`
Collect CollectConfig `json:"collect"`
Report ReportConfig `json:"report"`
Service ServiceConfig `json:"service"`
}
// HTTPConfig controls the local HTTP API listener.
type HTTPConfig struct {
ListenAddress string `json:"listen_address"`
}
// CollectConfig controls periodic host status collection.
type CollectConfig struct {
Interval Duration `json:"interval"`
Timeout Duration `json:"timeout"`
}
// ReportConfig controls optional periodic status POST reporting.
type ReportConfig struct {
Enabled bool `json:"enabled"`
Endpoint string `json:"endpoint"`
Interval Duration `json:"interval"`
Timeout Duration `json:"timeout"`
}
// ServiceConfig controls operating system service registration metadata.
type ServiceConfig struct {
Name string `json:"name"`
DisplayName string `json:"display_name"`
Description string `json:"description"`
}
// Duration wraps time.Duration so JSON config can use Go duration strings.
type Duration time.Duration
// Duration returns the standard library duration value.
func (d Duration) Duration() time.Duration {
return time.Duration(d)
}
// MarshalJSON writes the duration as a Go duration string such as "30s".
func (d Duration) MarshalJSON() ([]byte, error) {
return json.Marshal(time.Duration(d).String())
}
// UnmarshalJSON parses a Go duration string from JSON.
func (d *Duration) UnmarshalJSON(data []byte) error {
var raw string
if err := json.Unmarshal(data, &raw); err != nil {
return err
}
parsed, err := time.ParseDuration(raw)
if err != nil {
return err
}
*d = Duration(parsed)
return nil
}
// Default returns safe local defaults for running the agent.
func Default() Config {
return Config{
HTTP: HTTPConfig{ListenAddress: "127.0.0.1:8080"},
Collect: CollectConfig{
Interval: Duration(30 * time.Second),
Timeout: Duration(10 * time.Second),
},
Report: ReportConfig{
Enabled: false,
Interval: Duration(60 * time.Second),
Timeout: Duration(5 * time.Second),
},
Service: ServiceConfig{
Name: "mfd-monitor-agent",
DisplayName: "MFD Monitor Agent",
Description: "Collects host status and exposes it over HTTP.",
},
}
}
// Load reads optional JSON config, applies environment overrides, and validates required settings.
func Load(path string) (Config, error) {
cfg := Default()
if path != "" {
data, err := os.ReadFile(path)
if err != nil {
return cfg, err
}
if err := json.Unmarshal(data, &cfg); err != nil {
return cfg, err
}
}
applyEnv(&cfg)
if cfg.Report.Enabled && cfg.Report.Endpoint == "" {
return cfg, errors.New("report endpoint is required when reporting is enabled")
}
return cfg, nil
}
// applyEnv overlays supported MFD_AGENT_* environment variables onto cfg.
func applyEnv(cfg *Config) {
if value := os.Getenv("MFD_AGENT_HOST_ID"); value != "" {
cfg.HostID = value
}
if value := os.Getenv("MFD_AGENT_LISTEN"); value != "" {
cfg.HTTP.ListenAddress = value
}
if value := os.Getenv("MFD_AGENT_REPORT_ENABLED"); value != "" {
if parsed, err := strconv.ParseBool(value); err == nil {
cfg.Report.Enabled = parsed
}
}
if value := os.Getenv("MFD_AGENT_REPORT_ENDPOINT"); value != "" {
cfg.Report.Endpoint = value
}
if value := os.Getenv("MFD_AGENT_REPORT_INTERVAL"); value != "" {
if parsed, err := time.ParseDuration(value); err == nil {
cfg.Report.Interval = Duration(parsed)
}
}
if value := os.Getenv("MFD_AGENT_REPORT_TIMEOUT"); value != "" {
if parsed, err := time.ParseDuration(value); err == nil {
cfg.Report.Timeout = Duration(parsed)
}
}
if value := os.Getenv("MFD_AGENT_COLLECT_INTERVAL"); value != "" {
if parsed, err := time.ParseDuration(value); err == nil {
cfg.Collect.Interval = Duration(parsed)
}
}
if value := os.Getenv("MFD_AGENT_COLLECT_TIMEOUT"); value != "" {
if parsed, err := time.ParseDuration(value); err == nil {
cfg.Collect.Timeout = Duration(parsed)
}
}
}

View File

@@ -0,0 +1,71 @@
package config
import (
"os"
"testing"
"time"
)
// TestDefaultConfigUsesLocalhostAndSaneIntervals verifies safe local defaults.
func TestDefaultConfigUsesLocalhostAndSaneIntervals(t *testing.T) {
cfg := Default()
if cfg.HTTP.ListenAddress != "127.0.0.1:8080" {
t.Fatalf("listen address = %q", cfg.HTTP.ListenAddress)
}
if cfg.Collect.Interval <= 0 || cfg.Collect.Timeout <= 0 {
t.Fatalf("collect intervals must be positive: %+v", cfg.Collect)
}
if cfg.Report.Enabled {
t.Fatal("reporting should be disabled by default")
}
}
// TestLoadAppliesEnvironmentOverrides verifies environment variables override defaults.
func TestLoadAppliesEnvironmentOverrides(t *testing.T) {
t.Setenv("MFD_AGENT_LISTEN", "127.0.0.1:9090")
t.Setenv("MFD_AGENT_REPORT_ENABLED", "true")
t.Setenv("MFD_AGENT_REPORT_ENDPOINT", "http://center/status")
t.Setenv("MFD_AGENT_REPORT_INTERVAL", "2s")
t.Setenv("MFD_AGENT_HOST_ID", "host-a")
cfg, err := Load("")
if err != nil {
t.Fatal(err)
}
if cfg.HTTP.ListenAddress != "127.0.0.1:9090" {
t.Fatalf("listen address = %q", cfg.HTTP.ListenAddress)
}
if !cfg.Report.Enabled || cfg.Report.Endpoint != "http://center/status" {
t.Fatalf("report config not applied: %+v", cfg.Report)
}
if cfg.Report.Interval.Duration() != 2*time.Second {
t.Fatalf("report interval = %s", cfg.Report.Interval.Duration())
}
if cfg.HostID != "host-a" {
t.Fatalf("host id = %q", cfg.HostID)
}
}
// TestLoadJSONConfigFile verifies JSON config files are parsed into Config.
func TestLoadJSONConfigFile(t *testing.T) {
file, err := os.CreateTemp(t.TempDir(), "config-*.json")
if err != nil {
t.Fatal(err)
}
_, _ = file.WriteString(`{"http":{"listen_address":"127.0.0.1:7070"},"collect":{"interval":"3s","timeout":"1s"}}`)
_ = file.Close()
cfg, err := Load(file.Name())
if err != nil {
t.Fatal(err)
}
if cfg.HTTP.ListenAddress != "127.0.0.1:7070" {
t.Fatalf("listen address = %q", cfg.HTTP.ListenAddress)
}
if cfg.Collect.Interval.Duration() != 3*time.Second || cfg.Collect.Timeout.Duration() != time.Second {
t.Fatalf("collect config = %+v", cfg.Collect)
}
}