task.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // Package task hosts the scheduled jobs ported from sdf-serve. The daily
  2. // log auto-archive job moves oldest audit logs into MinIO when they exceed
  3. // the archive_threshold configured in t_config.
  4. package task
  5. import (
  6. "context"
  7. "udeServer/internal/audit"
  8. "udeServer/internal/log"
  9. "udeServer/internal/svc"
  10. "github.com/robfig/cron/v3"
  11. )
  12. // StartScheduler registers and starts the cron scheduler.
  13. func StartScheduler(ctx *svc.ServiceContext) {
  14. c := cron.New()
  15. // 每天 00:30 执行自动归档
  16. _, err := c.AddFunc("30 0 * * *", func() {
  17. log.RecordInfo(context.Background(), "[Ude-Task]开始自动归档日志!")
  18. LogAutoArchive(ctx)
  19. })
  20. if err != nil {
  21. log.RecordError(context.Background(), err)
  22. }
  23. log.RecordInfo(context.Background(), "定时任务启动中...")
  24. c.Start()
  25. }
  26. // LogAutoArchive archives oldest logs while they exceed the threshold.
  27. func LogAutoArchive(svcCtx *svc.ServiceContext) {
  28. ctx := context.Background()
  29. threshold := svcCtx.LogConfigManager.ArchiveThreshold
  30. if threshold <= 0 {
  31. log.RecordInfo(ctx, "[Task-LogArchive]归档阈值未配置(t_config.archive_threshold),跳过自动归档!")
  32. return
  33. }
  34. if svcCtx.MinioClient == nil {
  35. log.RecordWarn(ctx, "[Task-LogArchive]MinIO客户端未加载(检查t_config的file_*配置),跳过自动归档!")
  36. return
  37. }
  38. archiveName := "system_auto_archive"
  39. for {
  40. list, err := svcCtx.SystemLogModel.FindAllWithLimit(ctx, int(threshold))
  41. if err != nil {
  42. log.RecordError(ctx, err)
  43. return
  44. }
  45. if int64(len(list)) < threshold {
  46. log.RecordInfo(ctx, "[Task-LogArchive]当前日志%d条,未到达归档阈值%d,跳过自动归档!", len(list), threshold)
  47. break
  48. }
  49. _, err = audit.ArchiveLogsToStorageAndRecord(ctx, list, archiveName, threshold, audit.AutoArchive, svcCtx.MinioClient, svcCtx.DB)
  50. if err != nil {
  51. log.RecordError(ctx, err)
  52. return
  53. }
  54. log.RecordInfo(ctx, "[Task-LogArchive]自动归档:%d条日志成功!", len(list))
  55. }
  56. }