✨ feat(agent): 添加 token 鉴权和流程文档

* 默认监听调整为 0.0.0.0:8080,并要求查询参数 token
* 支持首次 run 自动生成含随机 token 的配置文件
* 补充 HTTP 鉴权、配置校验和相关测试
* 完善代码注释,覆盖缓存、上报、服务和平台采集路径
* 新增架构与开发流程文档,补充一键构建脚本
This commit is contained in:
codex
2026-05-22 06:46:21 +00:00
parent 877e4cf41d
commit de3fd88948
19 changed files with 875 additions and 125 deletions

View File

@@ -11,6 +11,7 @@ import (
"mfd-monitor-agent/internal/config"
)
// currentUID 是测试可替换的当前用户 ID 查询函数。
var currentUID = os.Geteuid
// linuxManager 通过 systemd 管理 agent 服务。
@@ -28,9 +29,11 @@ func (linuxManager) Install(executable string, cfg config.Config, opts InstallOp
}
unit := renderSystemdUnit(executable, opts.ConfigPath, cfg)
path := "/etc/systemd/system/" + cfg.Service.Name + ".service"
// 安装阶段写入 systemd unit,需要 root 权限且会影响系统服务注册。
if err := os.WriteFile(path, []byte(unit), 0644); err != nil {
return fmt.Errorf("write systemd unit: %w", err)
}
// unit 文件变化后必须重载 systemd,再启用服务随系统启动。
if err := exec.Command("systemctl", "daemon-reload").Run(); err != nil {
return fmt.Errorf("systemctl daemon-reload: %w", err)
}
@@ -44,6 +47,7 @@ func (linuxManager) Install(executable string, cfg config.Config, opts InstallOp
func renderSystemdUnit(executable string, configPath string, cfg config.Config) string {
args := []string{executable, "run"}
if configPath != "" {
// install 接收的 -config 会固化到 ExecStart,保证服务模式读取同一配置。
args = append(args, "-config", configPath)
}
return fmt.Sprintf(`[Unit]
@@ -64,6 +68,7 @@ WantedBy=multi-user.target
// Uninstall 禁用服务、删除 unit 文件并重载 systemd。
func (linuxManager) Uninstall(cfg config.Config) error {
// 服务可能已经停止或未启用,忽略 disable 错误以继续清理 unit 文件。
_ = exec.Command("systemctl", "disable", "--now", cfg.Service.Name).Run()
if err := os.Remove("/etc/systemd/system/" + cfg.Service.Name + ".service"); err != nil && !os.IsNotExist(err) {
return err

View File

@@ -21,13 +21,16 @@ func newManager() Manager {
func (windowsManager) Install(executable string, cfg config.Config, opts InstallOptions) error {
args := []string{`"` + executable + `"`, "run"}
if opts.ConfigPath != "" {
// -config 被写入 binPath,确保 SCM 启动的 run 子命令读取指定配置。
args = append(args, "-config", `"`+opts.ConfigPath+`"`)
}
// sc.exe 的 binPath= 参数要求等号后单独一个参数,因此这里保持分段传参。
return exec.Command("sc.exe", "create", cfg.Service.Name, "binPath=", strings.Join(args, " "), "DisplayName=", cfg.Service.DisplayName, "start=", "auto").Run()
}
// Uninstall 停止并删除已配置的 Windows 服务。
func (windowsManager) Uninstall(cfg config.Config) error {
// 服务可能未运行,忽略 stop 错误并继续删除服务注册。
_ = exec.Command("sc.exe", "stop", cfg.Service.Name).Run()
return exec.Command("sc.exe", "delete", cfg.Service.Name).Run()
}