package seed // 内置告警规则 — 新环境开箱即用的通用日志告警(参照运维告警脚本的两类模式): // 致命类(出现即报):FATAL / panic / OutOfMemoryError / StackOverflowError // 突增类(超阈值才报):应用 error 过多 / ingress-nginx 4xx / 5xx // 绑定数据源:部署成功自动注册的 LogSource(managed)。 // 规则默认不启用(通知通道由管理员后期在设置页配置后再开启),ChannelIDs 留空。 import ( "time" "lokistack/models" "lokistack/repository" ) type builtinRule struct { name string query string windowMin int threshold int cooldown int } // 阈值设计原则(踩过坑,写清楚免得后来人再调回 0): // // 1. **绝不用 threshold: 0** // 0 表示"命中一条就报"。日志平台里一条 FATAL 或一个 error 关键字 // 在高峰期每秒就有几百条,阈值 0 等于把告警变成日志流的复读机 // (实测某环境 15 分钟 3051 万条 → 一直报警)。 // 2. 默认阈值按 **15 分钟窗口 + 大集群基线** 取, // 宁可漏报一点,也不要让运维对告警脱敏——告警疲劳比漏报更致命。 // 3. cooldown 统一 ≥ 120 分钟:同一问题 2 小时内只提醒一次。 // 4. 绝对阈值天然不跨环境通用,大集群(如 300GB/天)必须按 app/namespace // 收窄查询,否则任何阈值都会被常态流量击穿。这一点在 UI 上有提示。 // // ensurePlaceholderChannel 返回一个可挂靠的通道 ID: // 已有通道取第一个;没有则建一个禁用的占位通道。 func ensurePlaceholderChannel(db *repository.JsonDB) uint { db.Lock() defer db.Unlock() if len(db.NotifyChannels) > 0 { return db.NotifyChannels[0].ID } next := uint(0) for _, ch := range db.NotifyChannels { if ch.ID > next { next = ch.ID } } id := next + 1 db.NotifyChannels = append(db.NotifyChannels, models.NotifyChannel{ ID: id, Name: "默认通知通道(待配置 Webhook)", Enabled: false, CreatedAt: time.Now(), UpdatedAt: time.Now(), }) return id } // channelIDsFor 把单个通道 ID 包成切片;0 表示没有可用通道(保持空)。 func channelIDsFor(id uint) []uint { if id == 0 { return nil } return []uint{id} } var builtinRules = []builtinRule{ // —— 致命类:这类日志本该极少出现,但也不能一条就报 —— {name: "致命日志 FATAL", query: `{namespace=~".+"} |= "FATAL"`, windowMin: 15, threshold: 10, cooldown: 120}, {name: "Go panic", query: `{namespace=~".+"} |= "panic:"`, windowMin: 15, threshold: 10, cooldown: 120}, {name: "JVM OutOfMemoryError", query: `{namespace=~".+"} |~ "(^|[^a-zA-Z])OutOfMemoryError"`, windowMin: 15, threshold: 5, cooldown: 120}, {name: "StackOverflowError", query: `{namespace=~".+"} |= "StackOverflowError"`, windowMin: 15, threshold: 5, cooldown: 120}, // 注意:这里**只放日志类告警**。 // 「节点 NotReady」「容器 OOMKilled」属于基础设施指标监控(kube-state-metrics / // Prometheus)的职责,用日志去匹配这些字符串既不可靠(日志没开或轮转就漏), // 又与日志平台的定位混淆。这类告警请交给 Prometheus + Alertmanager。 // —— 突增类:只有明显高于常态才报 —— {name: "应用错误激增(error > 5万)", query: `{namespace=~".+"} |~ "(?i)\berror\b"`, windowMin: 15, threshold: 50000, cooldown: 120}, {name: "ingress-nginx 5xx 错误", query: `{app=~"ingress-nginx|nginx-ingress-controller"} |~ " (50[0-4]|5[2-9][0-9]) "`, windowMin: 15, threshold: 500, cooldown: 120}, {name: "ingress-nginx 4xx 激增", query: `{app=~"ingress-nginx|nginx-ingress-controller"} |~ " 4[0-9][0-9] "`, windowMin: 15, threshold: 5000, cooldown: 120}, {name: "数据库连接失败", query: `{namespace=~".+"} |~ "(?i)(connection refused|connection reset by peer|too many connections)"`, windowMin: 15, threshold: 200, cooldown: 120}, } // seedBuiltinAlertRules 为每个平台管理的 LogSource(managed=true)补齐内置规则: // 首次部署 Loki 后即有一套可直接启用的告警模板;通知通道留空,管理员配置后启用。 // SeedAlertRules 补齐内置告警规则(幂等;公开给启动与部署成功两处调用) func SeedAlertRules() { db := repository.GetDB() db.RLock() type srcRef struct { id uint name string } var sources []srcRef for i := range db.LogSources { if db.LogSources[i].Managed { sources = append(sources, srcRef{id: db.LogSources[i].ID, name: db.LogSources[i].Name}) } } // 已有规则(按 name)跳过 existing := map[string]bool{} for i := range db.AlertRules { existing[db.AlertRules[i].Name] = true } db.RUnlock() if len(sources) == 0 { return } // 绑定第一个 managed 数据源(通常是唯一部署) target := sources[0] // 内置规则一律挂到默认通知通道。 // 首次部署没有任何通道时,这里建一个**禁用**的占位通道(Webhook 留空): // - 规则不会变成"孤儿"(发送历史会明确写"通道未投递"而不是静默) // - 管理员填好 Webhook 再启用即可,不必逐条给规则关联通道 // - 之所以不放"已启用 + 空地址":那样每次命中都会投递失败刷屏 // 这里直接操作 db 而不调 services,避免 seed ↔ services 的包循环依赖。 defaultChannelID := ensurePlaceholderChannel(db) newID := db.NextID("alertRules") db.Lock() defer db.Unlock() for _, r := range builtinRules { if existing[r.name] { continue } newID++ db.AlertRules = append(db.AlertRules, models.AlertRule{ ID: newID, Name: r.name, SourceID: target.id, Query: r.query, WindowMin: r.windowMin, Threshold: r.threshold, Enabled: false, CooldownMin: r.cooldown, ChannelIDs: channelIDsFor(defaultChannelID), CreatedAt: time.Now(), UpdatedAt: time.Now(), }) } db.RequestSave() }