perf(analysis): 分析页按索引/内容分层,告警默认阈值抬高

=== 1. 分析页"一直转圈/请求超时(40000ms)"的真实原因 ===
三个问题叠加,逐个量化:

a) 首屏用空 namespace 发查询
   页面初始 namespace='',等策略返回前就发出 `{namespace=~".+"}` 全集群查询,
   策略到位后又查一次 → 一次访问跑两遍。
   → 加 namespaceReady 门控:解析完再发(effectiveSourceId)。

b) histogram 索引查询和内容查询抢同一个信号量
   /logs/histogram 首选 index/volume_range(毫秒级),但仍要先抢重型令牌,
   而令牌被 4 条 count_over_time(各 14~29s)占满 → 排队/429/超时。
   → 索引路径**不再占用重型令牌**(15s 独立超时),只有回退到
     count_over_time 时才抢令牌。实测各跨度(15m/1h/6h/24h)均 0s。

c) 重查询条数过多
   原来 4 条全局 count_over_time(total/error/warn)+ 2 条 by-app,
   串行 1~2 分钟。现在只留 2 条 by-app:
     - 全局总量已由 histogram(索引)提供
     - 全局 error 由 errByApp 序列求和得出
     - 全局 warn 放弃(优先级最低却要 20s)
   实测 by-app 单条 26s,两条串行 ~52s;主图 0s 先出。

d) 日报 7 天 count_over_time(2.6TB 扫描)必然失败
   → 改走 /logs/histogram(索引)按自然日聚合,只出"每日总量",
     应用维度交给下方 Top 应用表格(有自己的时间范围)。
   实测 7 天跨度毫秒级。

=== 2. 告警默认阈值抬高(告警疲劳治理)===
验证时用 `{namespace="astralx"}` + 阈值 0 触发了一次:
15 分钟命中 3051 万条 —— 阈值 0 等于把告警变成日志流复读机。

新基线(15 分钟窗口,冷却统一 120 分钟):
    致命日志 FATAL           0 → 10
    Go panic                 0 → 10
    JVM OutOfMemoryError     0 → 5
    StackOverflowError       0 → 5
    应用错误激增             1000 → 50000(改名,原"error > 1000"名不副实)
    ingress-nginx 5xx         100 → 500
    ingress-nginx 4xx        1000 → 5000
    数据库连接失败             50 → 200

迁移只改"仍等于旧默认值"的规则,用户手动调过的阈值不动。
设计原则写进 seed 注释:绝不用 threshold 0;宁可少报也不要让人对告警脱敏;
绝对阈值不跨环境通用,大集群必须按 app/namespace 收窄。

=== 实测(v6-1028-2218 / 0bf66199de66)===
  规则 8 条,阈值=0 的规则数 0,冷却全部 120m
  histogram astralx(15m/1h/6h/24h): 0s
  by-app metrics astralx 15m: 26s,正常返回数据
This commit is contained in:
opsx committed 2026-10-28 22:20:19 +00:00
1 parent 95dcd9408c
commit fa7ddd67c1
6 files changed
+161 -77

No files matched your search

+64 -6
View File
@@ -5,8 +5,8 @@ import (
"fmt"
"log"
"os"
"strings"
"path/filepath"
"strings"
"sync"
"time"
@@ -46,7 +46,7 @@ type JsonDB struct {
// (例如新增 ScrapeJobs 时老数据要手写兼容)。有了版本号,
// 以后的结构变更可以在 InitDB 里按版本号顺序迁移,可测、可回滚。
SchemaVersion int `json:"schemaVersion"`
sequences map[string]uint
sequences map[string]uint
// 防抖保存机制
saveTimer *time.Timer
@@ -62,6 +62,55 @@ func GetDB() *JsonDB {
return db
}
// alertThresholdUpgrade 记录"旧种子阈值 → 新基线"的映射。
//
// 只在规则阈值**仍等于旧默认值**时才升级,避免覆盖用户自己调过的值。
type alertThresholdUpgrade struct {
oldName string
newName string
oldThreshold int
newThreshold int
newCooldown int
}
var alertThresholdUpgrades = []alertThresholdUpgrade{
{oldName: "致命日志 FATAL", newName: "致命日志 FATAL", oldThreshold: 0, newThreshold: 10, newCooldown: 120},
{oldName: "Go panic", newName: "Go panic", oldThreshold: 0, newThreshold: 10, newCooldown: 120},
{oldName: "JVM OutOfMemoryError", newName: "JVM OutOfMemoryError", oldThreshold: 0, newThreshold: 5, newCooldown: 120},
{oldName: "StackOverflowError", newName: "StackOverflowError", oldThreshold: 0, newThreshold: 5, newCooldown: 120},
{oldName: "应用错误过多(error > 1000)", newName: "应用错误激增(error > 5万)", oldThreshold: 1000, newThreshold: 50000, newCooldown: 120},
{oldName: "ingress-nginx 5xx 错误", newName: "ingress-nginx 5xx 错误", oldThreshold: 100, newThreshold: 500, newCooldown: 120},
{oldName: "ingress-nginx 4xx 激增", newName: "ingress-nginx 4xx 激增", oldThreshold: 1000, newThreshold: 5000, newCooldown: 120},
{oldName: "数据库连接失败", newName: "数据库连接失败", oldThreshold: 50, newThreshold: 200, newCooldown: 120},
}
// raiseLegacyAlertThresholds 抬高仍是旧默认值的告警阈值与冷却时间。
func (d *JsonDB) raiseLegacyAlertThresholds() {
byName := map[string]alertThresholdUpgrade{}
for _, u := range alertThresholdUpgrades {
byName[u.oldName] = u
}
for i := range d.AlertRules {
rule := &d.AlertRules[i]
u, ok := byName[rule.Name]
if !ok {
continue
}
if rule.Threshold != u.oldThreshold {
// 用户已经手动调过,尊重用户设置
continue
}
old := rule.Threshold
rule.Threshold = u.newThreshold
rule.Name = u.newName
if rule.CooldownMin < u.newCooldown {
rule.CooldownMin = u.newCooldown
}
log.Printf("[schema] 告警规则 %q 阈值 %d → %d(冷却 %dm),降低告警频率",
u.newName, old, u.newThreshold, rule.CooldownMin)
}
}
// fixUnreachableLogSourceURLs 把数据源里 0.0.0.0 / [::] 的监听地址换成主机真实 IP。
//
// 平台进程不在被采集主机上,0.0.0.0 只在本机有意义,用它必然连不上。
@@ -109,9 +158,10 @@ func (d *JsonDB) fixUnreachableLogSourceURLs() {
//
// 背景:这些集合曾经都漏在 InitDB 的 sequences 重建之外,导致 NextID 每次
// 进程重启都从 1 开始,于是不同时期创建的对象会撞号。撞号后的表现各不相同:
// LogSource : 查询页数据源下拉选不动(两个 option 同 value)
// AlertRule : 规则列表出现两条同 id,编辑/删除操作命中错的那条
// NotifyChannel: 通知渠道覆盖错对象
//
// LogSource : 查询页数据源下拉选不动(两个 option 同 value)
// AlertRule : 规则列表出现两条同 id,编辑/删除操作命中错的那条
// NotifyChannel: 通知渠道覆盖错对象
func (d *JsonDB) dedupeCollectionIDs() {
d.dedupeLogSourceIDs()
d.dedupeAlertRuleIDs()
@@ -294,7 +344,7 @@ func (d *JsonDB) dedupeLogSourceIDs() {
//
// v0/v1(无字段)→ 1:新增 auditLogs / schemaVersion(老库走零值兜底即可,无需处理)
// v1 → 2:预留示例(如把 ScrapeJobs 从 logPath 拆分时,需按旧结构生成默认 job)
const CurrentSchemaVersion = 4
const CurrentSchemaVersion = 5
// migrateSchema 按版本号顺序迁移老库。返回是否发生了迁移(需要回写)。
func (d *JsonDB) migrateSchema() bool {
@@ -339,6 +389,14 @@ func (d *JsonDB) migrateSchema() bool {
// 前端表现为「命名空间/App 下拉永远加载中」。
d.fixUnreachableLogSourceURLs()
d.SchemaVersion = 4
case 4:
// v4 → v5:抬高内置告警规则的默认阈值。
//
// 旧种子里有 4 条 threshold=0(命中一条就报),另外几条绝对值也偏低:
// 实测某环境 15 分钟 3051 万条日志 → 告警永远在响,运维直接脱敏。
// 只改"仍等于旧默认值"的规则,用户手动调过的阈值不动。
d.raiseLegacyAlertThresholds()
d.SchemaVersion = 5
default:
// 防御:出现未知版本(比当前代码还新)时不乱动,避免降级把数据写坏
log.Printf("[schema] 数据库版本 %d 高于当前代码支持版本 %d,跳过迁移", d.SchemaVersion, CurrentSchemaVersion)
+21 -10
View File
@@ -20,21 +20,32 @@ type builtinRule struct {
cooldown int
}
// 阈值设计原则(踩过坑,写清楚免得后来人再调回 0):
//
// 1. **绝不用 threshold: 0**
// 0 表示"命中一条就报"。日志平台里一条 FATAL 或一个 error 关键字
// 在高峰期每秒就有几百条,阈值 0 等于把告警变成日志流的复读机
// (实测某环境 15 分钟 3051 万条 → 一直报警)。
// 2. 默认阈值按 **15 分钟窗口 + 大集群基线** 取,
// 宁可漏报一点,也不要让运维对告警脱敏——告警疲劳比漏报更致命。
// 3. cooldown 统一 ≥ 120 分钟:同一问题 2 小时内只提醒一次。
// 4. 绝对阈值天然不跨环境通用,大集群(如 300GB/天)必须按 app/namespace
// 收窄查询,否则任何阈值都会被常态流量击穿。这一点在 UI 上有提示。
var builtinRules = []builtinRule{
// —— 致命类:15 分钟内出现即报 ——
{name: "致命日志 FATAL", query: `{namespace=~".+"} |= "FATAL"`, windowMin: 15, threshold: 0, cooldown: 60},
{name: "Go panic", query: `{namespace=~".+"} |= "panic:"`, windowMin: 15, threshold: 0, cooldown: 60},
{name: "JVM OutOfMemoryError", query: `{namespace=~".+"} |~ "(^|[^a-zA-Z])OutOfMemoryError"`, windowMin: 15, threshold: 0, cooldown: 60},
{name: "StackOverflowError", query: `{namespace=~".+"} |= "StackOverflowError"`, windowMin: 15, threshold: 0, cooldown: 60},
// —— 致命类:这类日志本该极少出现,但也不能一条就报 ——
{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 > 1000)", query: `{namespace=~".+"} |~ "(?i)\berror\b"`, windowMin: 15, threshold: 1000, cooldown: 60},
{name: "ingress-nginx 5xx 错误", query: `{app=~"ingress-nginx|nginx-ingress-controller"} |~ " (50[0-4]|5[2-9][0-9]) `, windowMin: 15, threshold: 100, cooldown: 60},
{name: "ingress-nginx 4xx 激增", query: `{app=~"ingress-nginx|nginx-ingress-controller"} |~ " 4[0-9][0-9] "`, windowMin: 15, threshold: 1000, cooldown: 60},
{name: "数据库连接失败", query: `{namespace=~".+"} |~ "(?i)(connection refused|connection reset by peer|too many connections)"`, windowMin: 15, threshold: 50, cooldown: 60},
// —— 突增类:只有明显高于常态才报 ——
{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)补齐内置规则:
+19 -13
View File
@@ -468,35 +468,41 @@ func LokiHistogram(ctx context.Context, src *models.LogSource, query string, sta
return nil, fmt.Errorf("统计范围过大(%.1f 天),最多支持 %.0f 天;请缩小时间范围后重试",
float64(span)/float64(24*time.Hour), maxHistogramRange.Hours()/24)
}
// 并发护栏:拿不到令牌立刻返回,不排队(排队只会让用户等更久)
if !acquireHeavyQuery() {
return nil, ErrTooManyQueries
}
defer releaseHeavyQuery()
// 独立超时:Loki 侧再慢也不会超过 30s,防止单查询长期占用实例
ctx, cancel := context.WithTimeout(ctx, heavyQueryTimeout)
defer cancel()
step := pickHistogramStep(span)
// ── 首选:Loki 官方的 index/volume_range ──────────────────────────────
// 它只读 TSDB 索引里的 chunk 元数据(字节数),**不解码日志内容**。
// 实测同一条件 24 小时:count_over_time 53s 超时失败,volume_range 111ms。
// 返回单位是「字节」,所以 bucket 里带 unit=bytes,前端据此格式化为 KB/MB/GB。
//
// ⚠️ 这条路径**不占用重型查询令牌**:
// 索引查询本身是毫秒级的,如果和 count_over_time 之类要读 chunk 的查询抢
// 同一个信号量,就会出现"图表明明 0 秒能出,却因为别人在跑分析查询而排队
// 十秒、最后 429/超时"的怪现象(分析页实际踩过)。
q := url.Values{}
q.Set("query", query)
q.Set("start", strconv.FormatInt(start, 10))
q.Set("end", strconv.FormatInt(end, 10))
q.Set("step", step)
q.Set("limit", "50")
if body, status, err := lokiProxyGET(ctx, src, "/loki/api/v1/index/volume_range", q); err == nil && status < 400 {
idxCtx, idxCancel := context.WithTimeout(ctx, 15*time.Second)
if body, status, err := lokiProxyGET(idxCtx, src, "/loki/api/v1/index/volume_range", q); err == nil && status < 400 {
if buckets, ok := parseVolumeBuckets(body); ok {
idxCancel()
return buckets, nil
}
}
// 老版本 Loki 没有 volume_range(404/400)时回退到 count_over_time
return lokiHistogramByCount(ctx, src, query, step, start, end)
idxCancel()
// ── 回退:老版本 Loki 没有 volume_range 时才走 count_over_time ──
// 这条要真读 chunk,才需要抢重型令牌 + 长超时。
if !acquireHeavyQuery() {
return nil, ErrTooManyQueries
}
defer releaseHeavyQuery()
heavyCtx, cancel := context.WithTimeout(ctx, heavyQueryTimeout)
defer cancel()
return lokiHistogramByCount(heavyCtx, src, query, step, start, end)
}
// parseVolumeBuckets 解析 index/volume_range 的 matrix 响应。
@@ -160,15 +160,33 @@ export function useAnalysisMetrics({ sourceId, start, end, namespace }: Analysis
},
}))
// ── 第二步:错误/警告/app 维度仍需读日志内容,串行执行 ──
const [errorSeries, warnSeries, byAppSeries, errByAppSeries] = await runInBatches([
() => fetchRetry(`sum(count_over_time(${selector} |= "error"[$step]))`),
() => fetchRetry(`sum(count_over_time(${selector} |= "warn"[$step]))`),
// ── 第二步:app 维度仍需读日志内容,串行执行 ──
//
// 原来这里有 4 条重查询(全局 total / 全局 error / 全局 warn / by-app ×2),
// 每条在 astralx 上约 14~29 秒,串行下来一两分钟,用户只看到转圈。
// 现在只留 2 条 by-app 查询:
// - 全局总量已由上面的 histogram(索引)提供,不用再查
// - 全局 error 由 errByApp 各序列求和得出,不用再查
// - 全局 warn 直接放弃(优先级最低,却要花 20 秒;趋势图里留空而不是假装 0)
const [byAppSeries, errByAppSeries] = await runInBatches([
() => fetchRetry(`sum by (${appLabel}, namespace) (count_over_time(${selector}[$step]))`),
() => fetchRetry(`sum by (${appLabel}, namespace) (count_over_time(${selector} |= "error"[$step]))`),
])
if (version !== versionRef.current) return
// 由 by-app 序列反推全局 error / warn 曲线,省掉两条重查询
const sumByTimestamp = (series: MetricSeries[]) => {
const acc = new Map<string, number>()
for (const item of series) {
for (const point of item.points) {
acc.set(point.timestamp, (acc.get(point.timestamp) ?? 0) + point.value)
}
}
return [{ labels: {}, points: [...acc.entries()].map(([timestamp, value]) => ({ timestamp, value })) }] as MetricSeries[]
}
const errorSeries = sumByTimestamp(errByAppSeries)
const warnSeries: MetricSeries[] = []
// 应用聚合:统一到最长序列的时间桶上;跨命名空间求和
let times: string[] = []
for (const item of byAppSeries) if (item.points.length > times.length) times = item.points.map(point => point.timestamp)
@@ -56,55 +56,42 @@ export function useDailyVolume({ sourceId, namespace, appLabel }: {
setLoading(true)
setError('')
try {
const series = await logsApi.metrics(
{ sourceId, start: Number(ns(start)), end: Number(ns(end)), query: `sum by (${appLabel}, namespace) (count_over_time(${selector}[$step]))` },
// 走索引接口而不是 count_over_time。
//
// 原来这条查 7 天 × count_over_time,实测该环境约 370GB/天 → 要扫 2.6TB,
// 后端 90s 也跑不完,图表永远空/超时。
// /logs/histogram 内部用 index/volume_range,只读 chunk 元数据,
// 7 天跨度也是毫秒级;代价是**只能拿到总量,拿不到 per-app 拆分**
// (Loki 的索引接口不支持按任意 label 分组)。
// 因此这里展示"每日日志总量",应用维度交给下方的 Top 应用表格(它有单独的时间范围)。
const hist = await logsApi.histogram(
{ sourceId, query: selector, start: Number(ns(start)), end: Number(ns(end)) },
{ signal: controller.signal },
)
if (version !== versionRef.current) return
// 小时桶 → 本地日历日分桶(app × 天 累加,并记录各 app 落在哪个命名空间)
const perDay = days.map(() => new Map<string, { total: number; perNs: Map<string, number> }>())
const dayIndexOf = (timestamp: string) => {
const day = Math.floor(new Date(timestamp).getTime() / DAY_MS) * DAY_MS
return days.indexOf(day)
// 索引返回的是字节数,按本地自然日聚合
const dayBytes = days.map(() => 0)
for (const bucket of (hist || [])) {
const ts = String((bucket as { timestamp: string }).timestamp ?? '')
const value = Number((bucket as { count: number }).count ?? 0)
const day = Math.floor(new Date(ts).getTime() / DAY_MS) * DAY_MS
const index = days.indexOf(day)
if (index >= 0) dayBytes[index] += value
}
for (const item of series) {
const app = item.labels[appLabel] ?? ''
const nsLabel = item.labels.namespace ?? ''
for (const point of item.points) {
const index = dayIndexOf(point.timestamp)
if (index < 0) continue
const bucket = perDay[index]
const entry = bucket.get(app) ?? { total: 0, perNs: new Map<string, number>() }
entry.total += point.value
entry.perNs.set(nsLabel, (entry.perNs.get(nsLabel) ?? 0) + point.value)
bucket.set(app, entry)
}
}
const merged = new Map<string, { totals: number[]; total: number; perNs: Map<string, number> }>()
perDay.forEach((bucket, index) => {
for (const [app, entry] of bucket) {
const row = merged.get(app) ?? { totals: days.map(() => 0), total: 0, perNs: new Map<string, number>() }
row.totals[index] += entry.total
row.total += entry.total
for (const [nsName, count] of entry.perNs) row.perNs.set(nsName, (row.perNs.get(nsName) ?? 0) + count)
merged.set(app, row)
}
setData({
days: days.map(dayLabel),
apps: [{
app: '全部应用',
namespace: namespace || '',
totals: dayBytes,
total: dayBytes.reduce((sum, value) => sum + value, 0),
}],
})
const apps: DailyAppRow[] = [...merged.entries()]
.map(([app, row]) => ({
app,
namespace: [...row.perNs.entries()].sort((a, b) => b[1] - a[1])[0]?.[0] ?? '',
totals: row.totals,
total: row.total,
}))
.filter(row => row.total > 0)
.sort((a, b) => b.total - a.total)
.slice(0, 10)
setData({ days: days.map(dayLabel), apps })
return
} catch (err) {
if (version !== versionRef.current) return
if ((err as Error).name === 'AbortError') return
setError(err instanceof Error ? err.message : 'metrics failed')
if (version === versionRef.current) setError(err instanceof Error ? err.message : 'daily volume failed')
} finally {
if (version === versionRef.current) setLoading(false)
}
+6 -2
View File
@@ -112,9 +112,13 @@ const AnalysisPage = memo(function AnalysisPage() {
// hook 内部把空串当作 {namespace=~".+"}(全部),这里做哨兵转换
const scopedNamespace = namespace === ALL_NAMESPACES ? '' : namespace
const { data, loading, error, appLabel, refresh } = useAnalysisMetrics({ sourceId, start, end, namespace: scopedNamespace })
// 等命名空间解析完再发查询:
// 1) 避免首屏先用空 namespace 发一次 {namespace=~".+"} 的全集群查询(很贵)
// 2) 避免"查了两次"——策略返回后 namespace 变化会再查一次,前一次白跑
const effectiveSourceId = namespaceReady ? sourceId : 0
const { data, loading, error, appLabel, refresh } = useAnalysisMetrics({ sourceId: effectiveSourceId, start, end, namespace: scopedNamespace })
// 每日统计固定近 7 天,不随上方时间范围变化;错误就地展示,不影响主区
const daily = useDailyVolume({ sourceId, namespace: scopedNamespace, appLabel })
const daily = useDailyVolume({ sourceId: effectiveSourceId, namespace: scopedNamespace, appLabel })
// 非 admin:菜单不可见,直访时给明确提示(后端 AdminAuth 403 兜底)
if (!isAdmin) {