✨ 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

@@ -12,6 +12,7 @@ import (
"mfd-monitor-agent/internal/status"
)
// defaultRetryDelay 是单次上报失败后重试前等待的默认时长。
const defaultRetryDelay = 2 * time.Second
// Provider 提供用于外发上报的缓存 HostStatus。
@@ -35,6 +36,7 @@ func NewClient(endpoint string, timeout time.Duration) *Client {
}
// Report 将一份 HostStatus 以 JSON POST 上报;非 2xx 响应作为错误返回。
// 请求超时由 Client 内部的 http.Client.Timeout 控制。
func (c *Client) Report(snapshot status.HostStatus) error {
body, err := json.Marshal(snapshot)
if err != nil {
@@ -70,11 +72,14 @@ func runWithRetryDelay(ctx context.Context, provider Provider, client *Client, i
case <-ctx.Done():
return
case <-ticker.C:
// 上报只读取缓存,避免与 HTTP 查询之外再触发一轮昂贵采集。
snapshot, ok := provider.Get()
if !ok {
// 首次快照未就绪时跳过本轮,上报循环继续等待下一周期。
continue
}
if err := reportWithRetry(ctx, client, snapshot, retryDelay); err != nil {
// 上报失败只写日志,不影响本地 HTTP 服务与后续采集。
logger.Warn("status report failed", "error", err)
}
}
@@ -87,6 +92,7 @@ func reportWithRetry(ctx context.Context, client *Client, snapshot status.HostSt
if err == nil {
return nil
}
// 重试等待受 ctx 控制,agent 退出时不会被固定退避时间拖住。
select {
case <-ctx.Done():
return ctx.Err()