Skip to content

Commit 93de7ea

Browse files
committed
Update.
1 parent 91d2a8b commit 93de7ea

4 files changed

Lines changed: 65 additions & 43 deletions

File tree

db/badger_init.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -310,15 +310,15 @@ func startBadgerDBMaintenanceTasks() {
310310

311311
// 例如定期清理过期的监控历史记录
312312
go func() {
313-
ticker := time.NewTicker(24 * time.Hour)
313+
ticker := time.NewTicker(6 * time.Hour) // 改为每6小时清理一次
314314
defer ticker.Stop()
315315

316316
for {
317317
select {
318318
case <-ticker.C:
319-
// 清理7天前的监控历史记录,减少数据库大小
319+
// 清理3天前的监控历史记录,减少数据库大小
320320
monitorHistoryOps := NewMonitorHistoryOps(DB)
321-
count, err := monitorHistoryOps.CleanupOldMonitorHistories(7 * 24 * time.Hour)
321+
count, err := monitorHistoryOps.CleanupOldMonitorHistories(3 * 24 * time.Hour)
322322
if err != nil {
323323
log.Printf("清理过期监控历史记录失败: %v", err)
324324
} else if count > 0 {

service/singleton/alertsentinel.go

Lines changed: 40 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ var (
3131
alertsStore map[uint64]map[uint64][][]interface{} // [alert_id][server_id] -> 对应事件规则的检查结果
3232
alertsPrevState map[uint64]map[uint64]uint // [alert_id][server_id] -> 对应事件规则的上一次事件状态
3333
AlertsCycleTransferStatsStore map[uint64]*model.CycleTransferStats // [alert_id] -> 对应事件规则的周期流量统计
34+
serverLastOnlineTime map[uint64]time.Time // [server_id] -> 服务器离线前的最后在线时间(用于恢复通知计算离线时长)
3435
)
3536

3637
// addCycleTransferStatsInfo 向AlertsCycleTransferStatsStore中添加周期流量事件统计信息
@@ -72,6 +73,7 @@ func AlertSentinelStart() {
7273
alertsStore = make(map[uint64]map[uint64][][]interface{})
7374
alertsPrevState = make(map[uint64]map[uint64]uint)
7475
AlertsCycleTransferStatsStore = make(map[uint64]*model.CycleTransferStats)
76+
serverLastOnlineTime = make(map[uint64]time.Time)
7577
AlertsLock.Lock()
7678
defer func() {
7779
if r := recover(); r != nil {
@@ -496,6 +498,20 @@ func checkStatus() {
496498
alertsPrevStateCopy[alert.ID][server.ID] = _RuleCheckFail
497499
log.Printf("[事件]\n%s\n规则:%s %s", server.Name, alert.Name, *NotificationMuteLabel.ServerIncident(alert.ID, server.ID))
498500

501+
// 记录最后在线时间(用于恢复通知计算真实离线时长)
502+
if isOfflineAlert {
503+
if _, exists := serverLastOnlineTime[server.ID]; !exists {
504+
// 保存服务器离线前的最后在线时间
505+
if !server.LastOnline.IsZero() {
506+
serverLastOnlineTime[server.ID] = server.LastOnline
507+
} else if !server.LastActive.IsZero() {
508+
serverLastOnlineTime[server.ID] = server.LastActive
509+
} else {
510+
serverLastOnlineTime[server.ID] = time.Now()
511+
}
512+
}
513+
}
514+
499515
// 生成详细的通知消息
500516
message := generateDetailedAlertMessage(alert, server, alertsStoreCopy[alert.ID][server.ID])
501517

@@ -693,11 +709,8 @@ func formatBytes(bytes uint64) string {
693709
func generateDetailedAlertMessage(alert *model.AlertRule, server *model.Server, checkResultsHistory [][]interface{}) string {
694710
now := time.Now()
695711

696-
// 基础通知信息
697-
message := fmt.Sprintf("#%s"+"\n"+"[%s]"+"\n"+"%s[%s]"+"\n"+"服务器ID: %d"+"\n"+"通知时间: %s"+"\n",
698-
Localizer.MustLocalize(&i18n.LocalizeConfig{
699-
MessageID: "Notify",
700-
}),
712+
// 基础通知信息(移除了#探针通知前缀)
713+
message := fmt.Sprintf("[%s]"+"\n"+"%s[%s]"+"\n"+"服务器ID: %d"+"\n"+"通知时间: %s"+"\n",
701714
Localizer.MustLocalize(&i18n.LocalizeConfig{
702715
MessageID: "Incident",
703716
}),
@@ -793,7 +806,7 @@ func generateDetailedAlertMessage(alert *model.AlertRule, server *model.Server,
793806
offlineDuration = time.Hour
794807
}
795808

796-
message += fmt.Sprintf("• 服务器离线: 最后在线时间 %s (离线时长: %s)\n",
809+
message += fmt.Sprintf("• 服务器离线: 最后在线时间 %s\n• 已离线时长: %s\n",
797810
lastSeenTime.Format("2006-01-02 15:04:05"),
798811
formatDuration(offlineDuration))
799812
default:
@@ -1058,11 +1071,8 @@ func cleanupAlertMemoryDataAsync() {
10581071
func generateDetailedRecoveryMessage(alert *model.AlertRule, server *model.Server) string {
10591072
now := time.Now()
10601073

1061-
// 基础恢复信息
1062-
message := fmt.Sprintf("#%s"+"\n"+"[%s]"+"\n"+"%s[%s]"+"\n"+"服务器ID: %d"+"\n"+"恢复时间: %s"+"\n",
1063-
Localizer.MustLocalize(&i18n.LocalizeConfig{
1064-
MessageID: "Notify",
1065-
}),
1074+
// 基础恢复信息(移除了#探针通知前缀)
1075+
message := fmt.Sprintf("[%s]"+"\n"+"%s[%s]"+"\n"+"服务器ID: %d"+"\n"+"恢复时间: %s"+"\n",
10661076
Localizer.MustLocalize(&i18n.LocalizeConfig{
10671077
MessageID: "Resolved",
10681078
}),
@@ -1083,30 +1093,30 @@ func generateDetailedRecoveryMessage(alert *model.AlertRule, server *model.Serve
10831093
}
10841094

10851095
if hasOfflineRule {
1086-
// 修复恢复消息中的离线时长计算
1087-
var lastSeenTime time.Time
1096+
// 使用记录的最后在线时间来计算真实的离线时长
1097+
var lastOnlineTime time.Time
10881098
var offlineDuration time.Duration
10891099

1090-
// 优先使用LastOnline字段(这是服务器最后一次在线的准确时间)
1091-
if !server.LastOnline.IsZero() {
1092-
lastSeenTime = server.LastOnline
1093-
offlineDuration = now.Sub(lastSeenTime)
1094-
} else if !server.LastActive.IsZero() {
1095-
// 如果没有LastOnline,使用LastActive,但需要考虑离线超时时间
1096-
lastSeenTime = server.LastActive
1097-
// 减去离线检测的超时时间(3分钟),得到更准确的离线时长
1098-
offlineDuration = now.Sub(lastSeenTime) - (3 * time.Minute)
1099-
if offlineDuration < 0 {
1100-
offlineDuration = now.Sub(lastSeenTime)
1101-
}
1100+
// 优先使用记录的最后在线时间(与事件通知中显示的一致)
1101+
if recordedTime, exists := serverLastOnlineTime[server.ID]; exists {
1102+
lastOnlineTime = recordedTime
1103+
offlineDuration = now.Sub(lastOnlineTime)
1104+
// 清除记录的最后在线时间
1105+
delete(serverLastOnlineTime, server.ID)
11021106
} else {
1103-
// 如果都没有,说明服务器从未上线过
1104-
lastSeenTime = now.Add(-time.Hour) // 默认1小时前
1105-
offlineDuration = time.Hour
1107+
// 如果没有记录,使用当前服务器的状态作为备选
1108+
if !server.LastOnline.IsZero() {
1109+
lastOnlineTime = server.LastOnline
1110+
} else if !server.LastActive.IsZero() {
1111+
lastOnlineTime = server.LastActive
1112+
} else {
1113+
lastOnlineTime = now.Add(-time.Hour)
1114+
}
1115+
offlineDuration = now.Sub(lastOnlineTime)
11061116
}
11071117

1108-
message += fmt.Sprintf("• 服务器已恢复上线: 上次离线时间 %s (离线时长: %s)\n",
1109-
lastSeenTime.Format("2006-01-02 15:04:05"),
1118+
message += fmt.Sprintf("• 服务器已恢复上线: 上次离线时间 %s\n离线时长: %s\n",
1119+
lastOnlineTime.Format("2006-01-02 15:04:05"),
11101120
formatDuration(offlineDuration))
11111121
} else {
11121122
message += "• 服务器监控指标已恢复正常\n"

service/singleton/crontask.go

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -25,23 +25,35 @@ func InitCronTask() {
2525
// 添加基础的系统定时任务 - 修复重复任务注册问题
2626
// 每天凌晨3点清理累计流量数据(已废弃,保留为空函数)
2727
if _, err := Cron.AddFunc("0 0 3 * * *", func() {
28-
CleanCumulativeTransferData(7) // 改为7天,保持与监控历史一致
28+
CleanCumulativeTransferData(3) // 改为3天,与监控历史保持一致
2929
}); err != nil {
3030
panic(err)
3131
}
3232

33-
// 每天的3:30 对 监控记录 和 流量记录 进行清理(7天前数据
33+
// 每天的3:30 对 监控记录 和 流量记录 进行清理(3天前数据
3434
if _, err := Cron.AddFunc("0 30 3 * * *", func() {
3535
count, err := CleanMonitorHistory() // 处理返回值
3636
if err != nil {
3737
log.Printf("清理监控历史记录失败: %v", err)
38-
} else if Conf.Debug {
38+
} else if count > 0 {
3939
log.Printf("清理监控历史记录成功,共清理 %d 条记录", count)
4040
}
4141
}); err != nil {
4242
panic(err)
4343
}
4444

45+
// 每6小时清理一次监控历史记录,避免数据积累过多
46+
if _, err := Cron.AddFunc("0 0 */6 * * *", func() {
47+
count, err := CleanMonitorHistory()
48+
if err != nil {
49+
log.Printf("定时清理监控历史记录失败: %v", err)
50+
} else if count > 0 {
51+
log.Printf("定时清理监控历史记录完成,共清理 %d 条记录", count)
52+
}
53+
}); err != nil {
54+
panic(err)
55+
}
56+
4557
// 每1小时对流量记录进行打点 - 只注册一次
4658
if _, err := Cron.AddFunc("0 0 */1 * * *", RecordTransferHourlyUsage); err != nil {
4759
panic(err)
@@ -168,7 +180,7 @@ func loadCronTasksFromBadgerDB() {
168180
// 注册计划任务到cron调度器
169181
crons[i].CronJobID, taskErr = Cron.AddFunc(crons[i].Scheduler, CronTrigger(*crons[i]))
170182
if taskErr == nil {
171-
Crons[crons[i].ID] = crons[i] // 注意:crons[i] 已经是指针类型
183+
Crons[crons[i].ID] = crons[i] // 注意:crons[i] 已经是指针类型
172184
log.Printf("成功注册定时任务: %s (ID: %d, 调度: %s, 推送成功通知: %t)",
173185
crons[i].Name, crons[i].ID, crons[i].Scheduler, crons[i].PushSuccessful)
174186
} else {
@@ -226,21 +238,21 @@ func SendTriggerTasks(taskIDs []uint64, triggerServer uint64) {
226238
}
227239

228240
func CronTrigger(cr model.Cron, triggerServer ...uint64) func() {
229-
taskID := cr.ID // 只保存任务ID,不保存整个任务对象
241+
taskID := cr.ID // 只保存任务ID,不保存整个任务对象
230242
return func() {
231243
// 动态获取最新的任务对象,而不是使用闭包捕获的旧对象
232244
CronLock.RLock()
233245
currentCr := Crons[taskID]
234246
CronLock.RUnlock()
235-
247+
236248
if currentCr == nil {
237249
log.Printf("警告:找不到任务ID=%d的配置,跳过执行", taskID)
238250
return
239251
}
240-
252+
241253
// 使用最新的任务对象
242254
cr = *currentCr
243-
255+
244256
crIgnoreMap := make(map[uint64]bool)
245257
for j := 0; j < len(cr.Servers); j++ {
246258
crIgnoreMap[cr.Servers[j]] = true

service/singleton/singleton.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -700,7 +700,7 @@ func CleanMonitorHistory() (int64, error) {
700700
if db.DB != nil {
701701
// 使用BadgerDB的MonitorHistoryOps清理过期数据
702702
monitorOps := db.NewMonitorHistoryOps(db.DB)
703-
maxAge := 7 * 24 * time.Hour // 修改为7天,减少数据库大小
703+
maxAge := 3 * 24 * time.Hour // 修改为3天,减少数据库大小
704704
count, err := monitorOps.CleanupOldMonitorHistories(maxAge)
705705
if err != nil {
706706
log.Printf("BadgerDB监控历史清理失败: %v", err)
@@ -741,7 +741,7 @@ func CleanMonitorHistory() (int64, error) {
741741
err := executeWithoutLock(func() error {
742742
batchSize := 25 // 增加批次大小到25(从20增加)
743743
maxRetries := 3 // 减少重试次数,更快失败
744-
cutoffDate := time.Now().AddDate(0, 0, -7) // 修改为7天,减少数据库大小和内存占用
744+
cutoffDate := time.Now().AddDate(0, 0, -3) // 修改为3天,减少数据库大小和内存占用
745745
safetyBuffer := time.Now().Add(-6 * time.Hour) // 添加6小时安全缓冲区,避免误删新数据
746746

747747
// 使用非事务方式分批清理,避免长时间事务锁定

0 commit comments

Comments
 (0)