fix: 修复Agent指标时区查询

- 统一Agent报告存储与查询的UTC时间边界
- 修复监控大屏、历史图表及离线判断取不到最新数据
- 增加UTC与UTC+8场景回归测试
This commit is contained in:
Logan.Li committed 2026-07-25 16:17:47 +08:00
1 parent d9106dde6e
commit 7bc416d22a
6 files changed
+83 -9

No files matched your search

+8 -3
View File
@@ -64,6 +64,8 @@ func (h *AgentHandler) ReceiveReport(c *gin.Context) {
reportTime = t
}
}
// Agent 上报时间统一存储为 UTC,避免 SQLite 按带时区文本比较时误判。 // Logan.Li
reportTime = reportTime.UTC()
matchedServer, matchIP, assetMatched := h.resolveAgentAsset(req.Hostname, req.IP, c.ClientIP())
canonicalHostname := req.Hostname
@@ -260,7 +262,8 @@ func (h *AgentHandler) writeHotMetric(c *gin.Context, key string, value float64,
// GET /api/v1/agent/latest
func (h *AgentHandler) GetLatestReports(c *gin.Context) {
var results []model.AgentLatestResponse
threeMinAgo := time.Now().Add(-3 * time.Minute)
// 查询边界与 Agent 上报的 UTC 时间保持一致。 // Logan.Li
threeMinAgo := time.Now().UTC().Add(-3 * time.Minute)
// 以 servers 表为主,LEFT JOIN 最近 3 分钟内的 Agent 上报
// 未装 Agent 的主机也会显示(agent_status='not_installed'),打破"不显示→无法安装"的循环
h.db.Raw(`
@@ -394,7 +397,8 @@ func (h *AgentHandler) GetHostHistory(c *gin.Context) {
}
var reports []model.AgentReport
h.db.Where("hostname = ? AND report_time >= ? AND report_time <= ?", hostname, since, until).
// SQLite 会按时间文本比较,查询边界需统一转换为 UTC。 // Logan.Li
h.db.Where("hostname = ? AND report_time >= ? AND report_time <= ?", hostname, since.UTC(), until.UTC()).
Order("report_time ASC").
Find(&reports)
@@ -479,7 +483,8 @@ func (h *AgentHandler) aggregateFromReports(req model.AggregateReq) (int64, erro
for _, iv := range intervals {
lookback := iv.duration * 200
since := time.Now().Add(-lookback)
// 本地 SQLite 模式下使用 UTC 边界查询 Agent 报告。 // Logan.Li
since := time.Now().UTC().Add(-lookback)
var reports []model.AgentReport
if err := h.db.Where("hostname = ? AND report_time >= ?", req.Hostname, since).
Order("report_time ASC").Find(&reports).Error; err != nil {