审计发现 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 通过
310 lines
7.6 KiB
Go
310 lines
7.6 KiB
Go
package services
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"sort"
|
|
"strings"
|
|
"time"
|
|
|
|
"lokistack/models"
|
|
"lokistack/repository"
|
|
)
|
|
|
|
const (
|
|
// maxAuditLogs 审计日志条数上限。JSON DB 是全量读进内存、全量写盘,
|
|
// 不设上限的话审计表会把内存和落盘时间一起拖垮。
|
|
maxAuditLogs = 20000
|
|
// auditRetention 审计日志保留天数(合规常见要求 90 天)
|
|
auditRetention = 90 * 24 * time.Hour
|
|
)
|
|
|
|
// RecordAudit 写入一条审计日志。
|
|
//
|
|
// 并发安全:直接拿 db 锁追加,与其它业务写入同一把锁,避免 RequestSave 时丢更新。
|
|
// 裁剪:超过条数上限或保留期时从最早开始删。
|
|
func RecordAudit(entry models.AuditLog) {
|
|
db := repository.GetDB()
|
|
if db == nil {
|
|
return
|
|
}
|
|
db.Lock()
|
|
defer db.Unlock()
|
|
|
|
if entry.CreatedAt.IsZero() {
|
|
entry.CreatedAt = time.Now()
|
|
}
|
|
// 单字段长度保护:UA/Detail 可能来自客户端,不能无限制落盘
|
|
entry.UserAgent = truncateRunes(entry.UserAgent, 200)
|
|
entry.Detail = truncateRunes(entry.Detail, 500)
|
|
entry.Before = truncateRunes(entry.Before, 1000)
|
|
entry.After = truncateRunes(entry.After, 1000)
|
|
entry.Error = truncateRunes(entry.Error, 500)
|
|
entry.ResourceID = truncateRunes(entry.ResourceID, 128)
|
|
|
|
nextID := uint(1)
|
|
for _, a := range db.AuditLogs {
|
|
if a.ID >= nextID {
|
|
nextID = a.ID + 1
|
|
}
|
|
}
|
|
entry.ID = nextID
|
|
db.AuditLogs = append(db.AuditLogs, entry)
|
|
|
|
pruneAuditLocked(db)
|
|
db.RequestSave()
|
|
}
|
|
|
|
// pruneAuditLocked 裁剪审计日志(调用方必须已持锁)。
|
|
// 从头部(最早)开始丢,直到满足条数与保留期两条约束。
|
|
func pruneAuditLocked(db *repository.JsonDB) {
|
|
logs := db.AuditLogs
|
|
cut := 0
|
|
deadline := time.Now().Add(-auditRetention)
|
|
|
|
// 1) 先按保留期裁
|
|
for cut < len(logs) && logs[cut].CreatedAt.Before(deadline) {
|
|
cut++
|
|
}
|
|
// 2) 再按条数上限裁(保留最新的 maxAuditLogs 条)
|
|
if remain := len(logs) - cut; remain > maxAuditLogs {
|
|
cut += remain - maxAuditLogs
|
|
}
|
|
if cut > 0 {
|
|
db.AuditLogs = append([]models.AuditLog{}, logs[cut:]...)
|
|
}
|
|
}
|
|
|
|
// ListAuditLogs 分页查询审计日志(按时间倒序)。
|
|
func ListAuditLogs(q models.AuditQuery) ([]models.AuditLog, int64) {
|
|
db := repository.GetDB()
|
|
if db == nil {
|
|
return nil, 0
|
|
}
|
|
db.RLock()
|
|
all := db.AuditLogs
|
|
db.RUnlock()
|
|
|
|
matched := make([]models.AuditLog, 0, len(all))
|
|
for _, a := range all {
|
|
if q.Username != "" && !strings.Contains(strings.ToLower(a.Username), strings.ToLower(q.Username)) {
|
|
continue
|
|
}
|
|
if q.Module != "" && a.Module != q.Module {
|
|
continue
|
|
}
|
|
if q.Action != "" && a.Action != q.Action {
|
|
continue
|
|
}
|
|
if q.ResourceID != "" && !strings.Contains(a.ResourceID, q.ResourceID) {
|
|
continue
|
|
}
|
|
switch q.Status {
|
|
case 1:
|
|
if a.Status < 200 || a.Status >= 300 {
|
|
continue
|
|
}
|
|
case 2:
|
|
if a.Status < 400 {
|
|
continue
|
|
}
|
|
}
|
|
if q.StartTime != nil && a.CreatedAt.Before(*q.StartTime) {
|
|
continue
|
|
}
|
|
if q.EndTime != nil && a.CreatedAt.After(*q.EndTime) {
|
|
continue
|
|
}
|
|
matched = append(matched, a)
|
|
}
|
|
|
|
// 时间倒序
|
|
sort.Slice(matched, func(i, j int) bool { return matched[i].CreatedAt.After(matched[j].CreatedAt) })
|
|
|
|
total := int64(len(matched))
|
|
if q.PageSize <= 0 {
|
|
q.PageSize = 20
|
|
}
|
|
if q.Page <= 0 {
|
|
q.Page = 1
|
|
}
|
|
start := (q.Page - 1) * q.PageSize
|
|
if start >= len(matched) {
|
|
return []models.AuditLog{}, total
|
|
}
|
|
end := start + q.PageSize
|
|
if end > len(matched) {
|
|
end = len(matched)
|
|
}
|
|
return matched[start:end], total
|
|
}
|
|
|
|
// GetAuditLog 取单条(详情弹窗用)。
|
|
func GetAuditLog(id uint) (*models.AuditLog, error) {
|
|
db := repository.GetDB()
|
|
if db == nil {
|
|
return nil, fmt.Errorf("数据库未初始化")
|
|
}
|
|
db.RLock()
|
|
defer db.RUnlock()
|
|
for i := range db.AuditLogs {
|
|
if db.AuditLogs[i].ID == id {
|
|
entry := db.AuditLogs[i]
|
|
return &entry, nil
|
|
}
|
|
}
|
|
return nil, fmt.Errorf("审计记录不存在")
|
|
}
|
|
|
|
// AuditStatistics 统计卡片数据。
|
|
func AuditStatistics() models.AuditStats {
|
|
db := repository.GetDB()
|
|
stats := models.AuditStats{}
|
|
if db == nil {
|
|
return stats
|
|
}
|
|
db.RLock()
|
|
logs := db.AuditLogs
|
|
db.RUnlock()
|
|
|
|
now := time.Now()
|
|
todayStart := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
|
|
weekStart := todayStart.AddDate(0, 0, -6)
|
|
|
|
moduleCount := map[string]int64{}
|
|
userCount := map[string]int64{}
|
|
for _, a := range logs {
|
|
stats.TotalCount++
|
|
if a.CreatedAt.After(todayStart) {
|
|
stats.TodayCount++
|
|
}
|
|
if a.CreatedAt.After(weekStart) {
|
|
stats.WeekCount++
|
|
}
|
|
if a.Status >= 400 {
|
|
stats.FailCount++
|
|
}
|
|
moduleCount[a.Module]++
|
|
if a.Username != "" {
|
|
userCount[a.Username]++
|
|
}
|
|
}
|
|
stats.TopModules = topN(moduleCount, 5)
|
|
stats.TopUsers = topN(userCount, 5)
|
|
return stats
|
|
}
|
|
|
|
func topN(m map[string]int64, n int) []models.AuditCount {
|
|
out := make([]models.AuditCount, 0, len(m))
|
|
for k, v := range m {
|
|
out = append(out, models.AuditCount{Name: k, Count: v})
|
|
}
|
|
sort.Slice(out, func(i, j int) bool {
|
|
if out[i].Count == out[j].Count {
|
|
return out[i].Name < out[j].Name
|
|
}
|
|
return out[i].Count > out[j].Count
|
|
})
|
|
if len(out) > n {
|
|
out = out[:n]
|
|
}
|
|
return out
|
|
}
|
|
|
|
// ───────────────────────── 脱敏 / 摘要 ─────────────────────────
|
|
|
|
// auditSensitiveKeys 这些字段一律不进审计(只留「已修改」的痕迹)。
|
|
var auditSensitiveKeys = map[string]bool{
|
|
"password": true, "oldpassword": true, "newpassword": true,
|
|
"secretkey": true, "accesskey": true, "secretaccesskey": true,
|
|
"privatekey": true, "token": true, "accesstoken": true, "refreshtoken": true,
|
|
"encryptionkey": true, "jwtsecret": true,
|
|
}
|
|
|
|
// MaskAuditPayload 把请求体里的敏感值替换成 ***,返回脱敏后的 JSON 字符串。
|
|
// 解析失败时返回 "<非 JSON 请求体>",避免把表单里的密码原样落盘。
|
|
func MaskAuditPayload(body []byte, maxLen int) string {
|
|
if len(body) == 0 {
|
|
return ""
|
|
}
|
|
var v interface{}
|
|
if err := json.Unmarshal(body, &v); err != nil {
|
|
return "<非 JSON 请求体,已省略>"
|
|
}
|
|
masked := maskValue(v)
|
|
out, err := json.Marshal(masked)
|
|
if err != nil {
|
|
return ""
|
|
}
|
|
return truncateRunes(string(out), maxLen)
|
|
}
|
|
|
|
func maskValue(v interface{}) interface{} {
|
|
switch t := v.(type) {
|
|
case map[string]interface{}:
|
|
out := make(map[string]interface{}, len(t))
|
|
for k, val := range t {
|
|
if auditSensitiveKeys[strings.ToLower(k)] {
|
|
if s, ok := val.(string); ok && s == "" {
|
|
out[k] = ""
|
|
} else {
|
|
out[k] = "***"
|
|
}
|
|
continue
|
|
}
|
|
out[k] = maskValue(val)
|
|
}
|
|
return out
|
|
case []interface{}:
|
|
out := make([]interface{}, len(t))
|
|
for i, val := range t {
|
|
out[i] = maskValue(val)
|
|
}
|
|
return out
|
|
default:
|
|
return v
|
|
}
|
|
}
|
|
|
|
// AuditDiff 生成「变更前后」摘要,只保留真正变化的字段。
|
|
// prev/next 传脱敏后的 JSON 字符串;解析失败时返回空(不硬编码原文)。
|
|
func AuditDiff(prev, next string) (string, string) {
|
|
var a, b map[string]interface{}
|
|
if prev == "" || next == "" || json.Unmarshal([]byte(prev), &a) != nil || json.Unmarshal([]byte(next), &b) != nil {
|
|
return "", ""
|
|
}
|
|
before := map[string]interface{}{}
|
|
after := map[string]interface{}{}
|
|
for k, nv := range b {
|
|
ov, existed := a[k]
|
|
if !existed || fmt.Sprint(ov) != fmt.Sprint(nv) {
|
|
if existed {
|
|
before[k] = ov
|
|
}
|
|
after[k] = nv
|
|
}
|
|
}
|
|
for k, ov := range a {
|
|
if _, ok := b[k]; !ok {
|
|
before[k] = ov
|
|
}
|
|
}
|
|
if len(after) == 0 && len(before) == 0 {
|
|
return "", ""
|
|
}
|
|
bs, _ := json.Marshal(before)
|
|
as, _ := json.Marshal(after)
|
|
return truncateRunes(string(bs), 1000), truncateRunes(string(as), 1000)
|
|
}
|
|
|
|
func truncateRunes(s string, n int) string {
|
|
if n <= 0 {
|
|
return s
|
|
}
|
|
r := []rune(s)
|
|
if len(r) <= n {
|
|
return s
|
|
}
|
|
return string(r[:n]) + "…"
|
|
}
|