// 审计日志按保留天数清理 — 操作审计 / 登录日志 / 终端会话 / 会话命令 // Logan.Li package auditcleaner import ( "encoding/json" "fmt" "time" "ezops/model" "gorm.io/gorm" ) // Result 单次清理统计 // Logan.Li type Result struct { RetentionDays int `json:"retention_days"` CutoffTime time.Time `json:"cutoff_time"` AuditLogs int64 `json:"audit_logs"` LoginLogs int64 `json:"login_logs"` TerminalSessions int64 `json:"terminal_sessions"` SessionCommands int64 `json:"session_commands"` Total int64 `json:"total"` } // SummaryJSON 生成可持久化的摘要 JSON // Logan.Li func (r Result) SummaryJSON() string { b, _ := json.Marshal(r) return string(b) } // GetRetentionDays 读取当前保留天数,无配置时默认 180 天 // Logan.Li func GetRetentionDays(db *gorm.DB) int { var s model.AuditSettings if err := db.First(&s).Error; err != nil || s.RetentionDays <= 0 { return 180 } return s.RetentionDays } // Run 删除 cutoff 之前的审计相关记录 // Logan.Li func Run(db *gorm.DB, retentionDays int) (Result, error) { if !model.IsValidRetentionDays(retentionDays) { return Result{}, fmt.Errorf("无效的保留天数: %d", retentionDays) } cutoff := time.Now().AddDate(0, 0, -retentionDays) res := Result{RetentionDays: retentionDays, CutoffTime: cutoff} if r := db.Where("created_at < ?", cutoff).Delete(&model.SessionCommand{}); r.Error != nil { return res, r.Error } else { res.SessionCommands = r.RowsAffected } if r := db.Where("start_time < ?", cutoff).Delete(&model.TerminalSession{}); r.Error != nil { return res, r.Error } else { res.TerminalSessions = r.RowsAffected } if r := db.Where("login_at < ?", cutoff).Delete(&model.LoginLog{}); r.Error != nil { return res, r.Error } else { res.LoginLogs = r.RowsAffected } if r := db.Where("created_at < ?", cutoff).Delete(&model.AuditLog{}); r.Error != nil { return res, r.Error } else { res.AuditLogs = r.RowsAffected } res.Total = res.AuditLogs + res.LoginLogs + res.TerminalSessions + res.SessionCommands return res, nil } // RunFromSettings 按库中配置执行清理 // Logan.Li func RunFromSettings(db *gorm.DB) (Result, error) { return Run(db, GetRetentionDays(db)) }