审计发现 5 处硬伤(/metrics 空壳、零备份、prod 双副本数据分裂、零审计、资源偏紧),
本轮全部落地。
=== P0-1 真实 /metrics(原来是空壳)===
原实现只返回一行注释 `# LokiStack Metrics`,注释却写着"可被 Prometheus 抓取",
平台挂了/DB 写不进去/告警引擎卡死都只能靠用户反馈。
现接入 prometheus/client_golang,四层指标:
HTTP : lokistack_http_requests_total / _duration_seconds / _in_flight_requests
存储 : lokistack_db_size_bytes / _db_save_duration_seconds / _db_save_total / _db_records
业务 : lokistack_deployments{status,mode} / lokistack_collectors{status,type,run_mode}
后台任务: lokistack_alert_evaluations_total / _duration_seconds / lokistack_loki_queries_total
+ go_* / process_*(GoCollector、ProcessCollector)
关键点:path 标签用 c.FullPath() 路由模板,不用原始 URL —— 否则 117 个 Deployment
会把 Prometheus 基数炸掉。指标定义下沉 pkg/metrics 叶子包,避开
services ↔ repository 循环依赖。
=== P0-2 备份与恢复(原来 0 处代码)===
平台全部状态在 /app/data/opsxloki.json(51KB)+ kubeconfigs/ + known_hosts/,
DB 丢了 = 失去"这些资源是谁建的"的映射,从此无法管理/卸载/升级在跑的 Loki。
CLI : lokistack backup --output <path> / restore <pkg> / self-check / version
API : GET /system/backup(下载)/ POST /system/restore(校验暂存)/
POST /system/restore/apply(确认应用)/ GET /system/backups
K8s : kubernetes/pdb-backup.yaml —— 每日 03:30 CronJob,保留最近 7 份
安全设计:
- manifest.json 记录 ENCRYPTION_KEY 的 sha256 前 16 位**指纹**,用于恢复时
校验"这把钥匙能不能解开这份备份",不泄露密钥本身
- 恢复分两步(校验暂存 → 确认应用),应用前自动把当前 DB 备份为
opsxloki.json.before-restore.<时间戳>
- 包内不含明文密钥(kubeconfig 本就是加密态)
=== P0-3 prod compose 双副本 → 单副本 ===
lokistack-1 / lokistack-2 各挂独立数据卷 + nginx 轮询 = 数据分裂:
页面刷新两次可能看到不同结果,写操作只落一个副本。不是高可用。
已改单实例(nginx 仅做反代),文件顶部与 nginx.conf 都写明原因。
=== P0-4 操作审计日志(借鉴 /usr/local/src/aiops 的字段口径)===
aiops 是每个 controller 各写 recordXxxAudit();本平台有 60+ 写接口,
逐个埋点必然漏,漏掉的那个恰好最危险(删集群、改存储凭证)。
改为 **gin 中间件统一记录** + handler 通过 SetAudit 补充业务语义:
models/audit.go : 字段对齐 aiops,另加 Method/Path/Before/After
services/audit.go : 写入 + 90 天/2 万条自动裁剪 + 脱敏 + diff 生成
middleware/audit.go : 自动识别 module/action/resource,跳过只读接口
controllers/audit.go: 列表/详情/统计(仅 admin)
敏感字段(password/secretKey/privateKey/token)写入前统一替换为 ***。
=== P1 稳定性 ===
- 平台资源 1C/1Gi → 4C/4Gi 限(500m/512Mi 请求):JSON DB 全量读写 +
每分钟告警评估 + 批量发布并发,1Gi 会 OOM
- terminationGracePeriodSeconds: 30 —— 收到 SIGTERM 要等 DB 完整落盘,
否则 kubelet SIGKILL 会把 JSON 写一半(全库丢失)
- liveness timeoutSeconds 10s(默认 1s 写盘时会被误杀)
- PDB minAvailable: 0 —— 让 kubectl drain 正确等待重建,不卡维护
- DB schemaVersion + migrateSchema() 版本递进迁移(原先加字段全靠零值兜底)
- scripts/release.sh —— 不可变 tag <版本>-<日期>-<commit> + IfNotPresent,
根治 latest 并发构建互相覆盖导致的静默回滚(本项目已实际踩过)
- PVC 保持 30Gi(按长期增长预留,云盘单价低,不做在线扩容)
=== P2 易用性 ===
- 一键自检 GET /system/self-check + 仪表盘自检卡:真实探活 Loki /ready、
集群凭据解密、磁盘空间、主机状态、近 24h 失败操作
- 审计日志页 /audit:统计卡 + 用户名/模块/结果筛选 + 变更前后 diff 弹窗
- 菜单收敛 13 → 7(页内 tab 切换,URL 全部不变):
资源接入 = 集群 + 主机 + 存储
日志服务 = Loki 实例 + 采集器
日志 = 查询 + 分析
系统管理 = 用户 + 审计 + 设置
新增 GroupTabs 组件 + meta.group/groupKey,侧栏按分组去重并正确高亮
测试:go vet 通过、go test 全绿、tsc 通过
176 lines
5.1 KiB
Go
176 lines
5.1 KiB
Go
// Package metrics 定义 LokiStack 自身的 Prometheus 指标体系。
|
||
//
|
||
// 为什么单独成包:这些指标要同时被 repository(DB 落盘耗时)和
|
||
// services(业务计数)以及 middleware(HTTP)使用,
|
||
// 而 services 依赖 repository —— 指标定义必须放在最底层,否则循环依赖。
|
||
package metrics
|
||
|
||
import (
|
||
"net/http"
|
||
"runtime"
|
||
"strconv"
|
||
"sync"
|
||
|
||
"github.com/prometheus/client_golang/prometheus"
|
||
"github.com/prometheus/client_golang/prometheus/collectors"
|
||
"github.com/prometheus/client_golang/prometheus/promhttp"
|
||
)
|
||
|
||
var (
|
||
// HTTP 层
|
||
HTTPRequestsTotal = prometheus.NewCounterVec(
|
||
prometheus.CounterOpts{
|
||
Name: "lokistack_http_requests_total",
|
||
Help: "HTTP 请求总数(按方法/路由模板/状态码)",
|
||
},
|
||
[]string{"method", "path", "status"},
|
||
)
|
||
HTTPRequestDuration = prometheus.NewHistogramVec(
|
||
prometheus.HistogramOpts{
|
||
Name: "lokistack_http_request_duration_seconds",
|
||
Help: "HTTP 请求耗时分布",
|
||
Buckets: []float64{0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30},
|
||
},
|
||
[]string{"method", "path"},
|
||
)
|
||
HTTPInFlight = prometheus.NewGauge(
|
||
prometheus.GaugeOpts{
|
||
Name: "lokistack_http_in_flight_requests",
|
||
Help: "当前正在处理的请求数",
|
||
},
|
||
)
|
||
|
||
// 存储层(JSON DB 是平台最大风险点:全量读内存、全量写盘)
|
||
DBSizeBytes = prometheus.NewGauge(
|
||
prometheus.GaugeOpts{
|
||
Name: "lokistack_db_size_bytes",
|
||
Help: "JSON 数据库文件大小",
|
||
},
|
||
)
|
||
DBSaveDuration = prometheus.NewHistogram(
|
||
prometheus.HistogramOpts{
|
||
Name: "lokistack_db_save_duration_seconds",
|
||
Help: "数据库落盘耗时",
|
||
Buckets: []float64{0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1, 3, 5, 10},
|
||
},
|
||
)
|
||
DBSaveTotal = prometheus.NewCounterVec(
|
||
prometheus.CounterOpts{
|
||
Name: "lokistack_db_save_total",
|
||
Help: "数据库保存次数(按结果)",
|
||
},
|
||
[]string{"result"},
|
||
)
|
||
DBRecordsTotal = prometheus.NewGaugeVec(
|
||
prometheus.GaugeOpts{
|
||
Name: "lokistack_db_records",
|
||
Help: "各集合的记录数",
|
||
},
|
||
[]string{"collection"},
|
||
)
|
||
|
||
// 业务层
|
||
DeploymentsTotal = prometheus.NewGaugeVec(
|
||
prometheus.GaugeOpts{
|
||
Name: "lokistack_deployments",
|
||
Help: "Loki 部署数(按状态/运行模式)",
|
||
},
|
||
[]string{"status", "mode"},
|
||
)
|
||
CollectorsTotal = prometheus.NewGaugeVec(
|
||
prometheus.GaugeOpts{
|
||
Name: "lokistack_collectors",
|
||
Help: "采集器数(按状态/类型/托管方式)",
|
||
},
|
||
[]string{"status", "type", "run_mode"},
|
||
)
|
||
|
||
// 后台任务层
|
||
AlertEvaluationsTotal = prometheus.NewCounterVec(
|
||
prometheus.CounterOpts{
|
||
Name: "lokistack_alert_evaluations_total",
|
||
Help: "告警规则评估次数(按结果)",
|
||
},
|
||
[]string{"result"},
|
||
)
|
||
AlertEvaluationDuration = prometheus.NewHistogram(
|
||
prometheus.HistogramOpts{
|
||
Name: "lokistack_alert_evaluation_duration_seconds",
|
||
Help: "单轮告警评估耗时",
|
||
Buckets: []float64{0.01, 0.05, 0.1, 0.5, 1, 3, 5, 10, 30},
|
||
},
|
||
)
|
||
LokiQueriesTotal = prometheus.NewCounterVec(
|
||
prometheus.CounterOpts{
|
||
Name: "lokistack_loki_queries_total",
|
||
Help: "对后端 Loki 的查询次数(按结果)",
|
||
},
|
||
[]string{"result"},
|
||
)
|
||
|
||
BuildInfo = prometheus.NewGaugeVec(
|
||
prometheus.GaugeOpts{
|
||
Name: "lokistack_build_info",
|
||
Help: "构建信息(恒为 1,标签里带版本与 Go 版本)",
|
||
},
|
||
[]string{"version", "go_version"},
|
||
)
|
||
|
||
once sync.Once
|
||
)
|
||
|
||
// Register 注册全部指标(幂等)。version 一般传 main.version。
|
||
func Register(version string) {
|
||
once.Do(func() {
|
||
prometheus.MustRegister(
|
||
HTTPRequestsTotal, HTTPRequestDuration, HTTPInFlight,
|
||
DBSizeBytes, DBSaveDuration, DBSaveTotal, DBRecordsTotal,
|
||
DeploymentsTotal, CollectorsTotal,
|
||
AlertEvaluationsTotal, AlertEvaluationDuration, LokiQueriesTotal,
|
||
BuildInfo,
|
||
collectors.NewGoCollector(),
|
||
collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}),
|
||
)
|
||
BuildInfo.WithLabelValues(version, runtime.Version()).Set(1)
|
||
})
|
||
}
|
||
|
||
// Handler 返回 Prometheus 抓取端点。
|
||
func Handler() http.Handler { return promhttp.Handler() }
|
||
|
||
// ── 埋点辅助(各层直接调) ──
|
||
|
||
// ObserveHTTP 记录一次 HTTP 请求。pathLabel 必须是路由模板,不能用原始 URL。
|
||
func ObserveHTTP(method, pathLabel string, status int, seconds float64) {
|
||
HTTPRequestsTotal.WithLabelValues(method, pathLabel, strconv.Itoa(status)).Inc()
|
||
HTTPRequestDuration.WithLabelValues(method, pathLabel).Observe(seconds)
|
||
}
|
||
|
||
// IncInFlight / DecInFlight 在途请求计数。
|
||
func IncInFlight() { HTTPInFlight.Inc() }
|
||
func DecInFlight() { HTTPInFlight.Dec() }
|
||
|
||
// ObserveDBSave 记录一次落盘结果。
|
||
func ObserveDBSave(seconds float64, ok bool) {
|
||
DBSaveDuration.Observe(seconds)
|
||
DBSaveTotal.WithLabelValues(resultLabel(ok)).Inc()
|
||
}
|
||
|
||
// ObserveAlertEvaluation 记录一轮告警评估。
|
||
func ObserveAlertEvaluation(seconds float64, ok bool) {
|
||
AlertEvaluationDuration.Observe(seconds)
|
||
AlertEvaluationsTotal.WithLabelValues(resultLabel(ok)).Inc()
|
||
}
|
||
|
||
// ObserveLokiQuery 记录一次后端 Loki 查询。
|
||
func ObserveLokiQuery(ok bool) {
|
||
LokiQueriesTotal.WithLabelValues(resultLabel(ok)).Inc()
|
||
}
|
||
|
||
func resultLabel(ok bool) string {
|
||
if ok {
|
||
return "success"
|
||
}
|
||
return "error"
|
||
}
|