Skip to content

Commit 687c118

Browse files
wolfogresilverwind
andauthored
Clear up old Actions logs (#31735)
Part of #24256. Clear up old action logs to free up storage space. Users will see a message indicating that the log has been cleared if they view old tasks. <img width="1361" alt="image" src="https://github.com/user-attachments/assets/9f0f3a3a-bc5a-402f-90ca-49282d196c22"> Docs: https://gitea.com/gitea/docs/pulls/40 --------- Co-authored-by: silverwind <[email protected]>
1 parent e367835 commit 687c118

File tree

9 files changed

+128
-17
lines changed

9 files changed

+128
-17
lines changed

custom/conf/app.example.ini

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2684,6 +2684,8 @@ LEVEL = Info
26842684
;;
26852685
;; Default platform to get action plugins, `github` for `https://github.com`, `self` for the current Gitea instance.
26862686
;DEFAULT_ACTIONS_URL = github
2687+
;; Logs retention time in days. Old logs will be deleted after this period.
2688+
;LOG_RETENTION_DAYS = 365
26872689
;; Default artifact retention time in days. Artifacts could have their own retention periods by setting the `retention-days` option in `actions/upload-artifact` step.
26882690
;ARTIFACT_RETENTION_DAYS = 90
26892691
;; Timeout to stop the task which have running status, but haven't been updated for a long time

models/actions/task.go

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ type ActionTask struct {
3535
RunnerID int64 `xorm:"index"`
3636
Status Status `xorm:"index"`
3737
Started timeutil.TimeStamp `xorm:"index"`
38-
Stopped timeutil.TimeStamp
38+
Stopped timeutil.TimeStamp `xorm:"index(stopped_log_expired)"`
3939

4040
RepoID int64 `xorm:"index"`
4141
OwnerID int64 `xorm:"index"`
@@ -51,8 +51,8 @@ type ActionTask struct {
5151
LogInStorage bool // read log from database or from storage
5252
LogLength int64 // lines count
5353
LogSize int64 // blob size
54-
LogIndexes LogIndexes `xorm:"LONGBLOB"` // line number to offset
55-
LogExpired bool // files that are too old will be deleted
54+
LogIndexes LogIndexes `xorm:"LONGBLOB"` // line number to offset
55+
LogExpired bool `xorm:"index(stopped_log_expired)"` // files that are too old will be deleted
5656

5757
Created timeutil.TimeStamp `xorm:"created"`
5858
Updated timeutil.TimeStamp `xorm:"updated index"`
@@ -470,6 +470,16 @@ func StopTask(ctx context.Context, taskID int64, status Status) error {
470470
return nil
471471
}
472472

473+
func FindOldTasksToExpire(ctx context.Context, olderThan timeutil.TimeStamp, limit int) ([]*ActionTask, error) {
474+
e := db.GetEngine(ctx)
475+
476+
tasks := make([]*ActionTask, 0, limit)
477+
// Check "stopped > 0" to avoid deleting tasks that are still running
478+
return tasks, e.Where("stopped > 0 AND stopped < ? AND log_expired = ?", olderThan, false).
479+
Limit(limit).
480+
Find(&tasks)
481+
}
482+
473483
func isSubset(set, subset []string) bool {
474484
m := make(container.Set[string], len(set))
475485
for _, v := range set {

models/migrations/migrations.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -595,6 +595,8 @@ var migrations = []Migration{
595595
NewMigration("Add force-push branch protection support", v1_23.AddForcePushBranchProtection),
596596
// v301 -> v302
597597
NewMigration("Add skip_secondary_authorization option to oauth2 application table", v1_23.AddSkipSecondaryAuthColumnToOAuth2ApplicationTable),
598+
// v302 -> v303
599+
NewMigration("Add index to action_task stopped log_expired", v1_23.AddIndexToActionTaskStoppedLogExpired),
598600
}
599601

600602
// GetCurrentDBVersion returns the current db version

models/migrations/v1_23/v302.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
// Copyright 2024 The Gitea Authors. All rights reserved.
2+
// SPDX-License-Identifier: MIT
3+
4+
package v1_23 //nolint
5+
6+
import (
7+
"code.gitea.io/gitea/modules/timeutil"
8+
9+
"xorm.io/xorm"
10+
)
11+
12+
func AddIndexToActionTaskStoppedLogExpired(x *xorm.Engine) error {
13+
type ActionTask struct {
14+
Stopped timeutil.TimeStamp `xorm:"index(stopped_log_expired)"`
15+
LogExpired bool `xorm:"index(stopped_log_expired)"`
16+
}
17+
return x.Sync(new(ActionTask))
18+
}

modules/setting/actions.go

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,11 @@ import (
1414
// Actions settings
1515
var (
1616
Actions = struct {
17-
LogStorage *Storage // how the created logs should be stored
18-
ArtifactStorage *Storage // how the created artifacts should be stored
19-
ArtifactRetentionDays int64 `ini:"ARTIFACT_RETENTION_DAYS"`
2017
Enabled bool
18+
LogStorage *Storage // how the created logs should be stored
19+
LogRetentionDays int64 `ini:"LOG_RETENTION_DAYS"`
20+
ArtifactStorage *Storage // how the created artifacts should be stored
21+
ArtifactRetentionDays int64 `ini:"ARTIFACT_RETENTION_DAYS"`
2122
DefaultActionsURL defaultActionsURL `ini:"DEFAULT_ACTIONS_URL"`
2223
ZombieTaskTimeout time.Duration `ini:"ZOMBIE_TASK_TIMEOUT"`
2324
EndlessTaskTimeout time.Duration `ini:"ENDLESS_TASK_TIMEOUT"`
@@ -78,10 +79,17 @@ func loadActionsFrom(rootCfg ConfigProvider) error {
7879
if err != nil {
7980
return err
8081
}
82+
// default to 1 year
83+
if Actions.LogRetentionDays <= 0 {
84+
Actions.LogRetentionDays = 365
85+
}
8186

8287
actionsSec, _ := rootCfg.GetSection("actions.artifacts")
8388

8489
Actions.ArtifactStorage, err = getStorage(rootCfg, "actions_artifacts", "", actionsSec)
90+
if err != nil {
91+
return err
92+
}
8593

8694
// default to 90 days in Github Actions
8795
if Actions.ArtifactRetentionDays <= 0 {
@@ -92,5 +100,5 @@ func loadActionsFrom(rootCfg ConfigProvider) error {
92100
Actions.EndlessTaskTimeout = sec.Key("ENDLESS_TASK_TIMEOUT").MustDuration(3 * time.Hour)
93101
Actions.AbandonedJobTimeout = sec.Key("ABANDONED_JOB_TIMEOUT").MustDuration(24 * time.Hour)
94102

95-
return err
103+
return nil
96104
}

options/locale/locale_en-US.ini

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3679,6 +3679,7 @@ runs.no_workflows.quick_start = Don't know how to start with Gitea Actions? See
36793679
runs.no_workflows.documentation = For more information on Gitea Actions, see <a target="_blank" rel="noopener noreferrer" href="%s">the documentation</a>.
36803680
runs.no_runs = The workflow has no runs yet.
36813681
runs.empty_commit_message = (empty commit message)
3682+
runs.expire_log_message = Logs have been purged because they were too old.
36823683
36833684
workflow.disable = Disable Workflow
36843685
workflow.disable_success = Workflow '%s' disabled successfully.

routers/web/repo/actions/view.go

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,27 @@ func ViewPost(ctx *context_module.Context) {
222222

223223
step := steps[cursor.Step]
224224

225+
// if task log is expired, return a consistent log line
226+
if task.LogExpired {
227+
if cursor.Cursor == 0 {
228+
resp.Logs.StepsLog = append(resp.Logs.StepsLog, &ViewStepLog{
229+
Step: cursor.Step,
230+
Cursor: 1,
231+
Lines: []*ViewStepLogLine{
232+
{
233+
Index: 1,
234+
Message: ctx.Locale.TrString("actions.runs.expire_log_message"),
235+
// Timestamp doesn't mean anything when the log is expired.
236+
// Set it to the task's updated time since it's probably the time when the log has expired.
237+
Timestamp: float64(task.Updated.AsTime().UnixNano()) / float64(time.Second),
238+
},
239+
},
240+
Started: int64(step.Started),
241+
})
242+
}
243+
continue
244+
}
245+
225246
logLines := make([]*ViewStepLogLine, 0) // marshal to '[]' instead fo 'null' in json
226247

227248
index := step.LogIndex + cursor.Cursor

services/actions/cleanup.go

Lines changed: 58 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,18 +5,30 @@ package actions
55

66
import (
77
"context"
8+
"fmt"
9+
"time"
810

9-
"code.gitea.io/gitea/models/actions"
11+
actions_model "code.gitea.io/gitea/models/actions"
12+
actions_module "code.gitea.io/gitea/modules/actions"
1013
"code.gitea.io/gitea/modules/log"
14+
"code.gitea.io/gitea/modules/setting"
1115
"code.gitea.io/gitea/modules/storage"
16+
"code.gitea.io/gitea/modules/timeutil"
1217
)
1318

1419
// Cleanup removes expired actions logs, data and artifacts
15-
func Cleanup(taskCtx context.Context) error {
16-
// TODO: clean up expired actions logs
17-
20+
func Cleanup(ctx context.Context) error {
1821
// clean up expired artifacts
19-
return CleanupArtifacts(taskCtx)
22+
if err := CleanupArtifacts(ctx); err != nil {
23+
return fmt.Errorf("cleanup artifacts: %w", err)
24+
}
25+
26+
// clean up old logs
27+
if err := CleanupLogs(ctx); err != nil {
28+
return fmt.Errorf("cleanup logs: %w", err)
29+
}
30+
31+
return nil
2032
}
2133

2234
// CleanupArtifacts removes expired add need-deleted artifacts and set records expired status
@@ -28,13 +40,13 @@ func CleanupArtifacts(taskCtx context.Context) error {
2840
}
2941

3042
func cleanExpiredArtifacts(taskCtx context.Context) error {
31-
artifacts, err := actions.ListNeedExpiredArtifacts(taskCtx)
43+
artifacts, err := actions_model.ListNeedExpiredArtifacts(taskCtx)
3244
if err != nil {
3345
return err
3446
}
3547
log.Info("Found %d expired artifacts", len(artifacts))
3648
for _, artifact := range artifacts {
37-
if err := actions.SetArtifactExpired(taskCtx, artifact.ID); err != nil {
49+
if err := actions_model.SetArtifactExpired(taskCtx, artifact.ID); err != nil {
3850
log.Error("Cannot set artifact %d expired: %v", artifact.ID, err)
3951
continue
4052
}
@@ -52,13 +64,13 @@ const deleteArtifactBatchSize = 100
5264

5365
func cleanNeedDeleteArtifacts(taskCtx context.Context) error {
5466
for {
55-
artifacts, err := actions.ListPendingDeleteArtifacts(taskCtx, deleteArtifactBatchSize)
67+
artifacts, err := actions_model.ListPendingDeleteArtifacts(taskCtx, deleteArtifactBatchSize)
5668
if err != nil {
5769
return err
5870
}
5971
log.Info("Found %d artifacts pending deletion", len(artifacts))
6072
for _, artifact := range artifacts {
61-
if err := actions.SetArtifactDeleted(taskCtx, artifact.ID); err != nil {
73+
if err := actions_model.SetArtifactDeleted(taskCtx, artifact.ID); err != nil {
6274
log.Error("Cannot set artifact %d deleted: %v", artifact.ID, err)
6375
continue
6476
}
@@ -75,3 +87,40 @@ func cleanNeedDeleteArtifacts(taskCtx context.Context) error {
7587
}
7688
return nil
7789
}
90+
91+
const deleteLogBatchSize = 100
92+
93+
// CleanupLogs removes logs which are older than the configured retention time
94+
func CleanupLogs(ctx context.Context) error {
95+
olderThan := timeutil.TimeStampNow().AddDuration(-time.Duration(setting.Actions.LogRetentionDays) * 24 * time.Hour)
96+
97+
count := 0
98+
for {
99+
tasks, err := actions_model.FindOldTasksToExpire(ctx, olderThan, deleteLogBatchSize)
100+
if err != nil {
101+
return fmt.Errorf("find old tasks: %w", err)
102+
}
103+
for _, task := range tasks {
104+
if err := actions_module.RemoveLogs(ctx, task.LogInStorage, task.LogFilename); err != nil {
105+
log.Error("Failed to remove log %s (in storage %v) of task %v: %v", task.LogFilename, task.LogInStorage, task.ID, err)
106+
// do not return error here, continue to next task
107+
continue
108+
}
109+
task.LogIndexes = nil // clear log indexes since it's a heavy field
110+
task.LogExpired = true
111+
if err := actions_model.UpdateTask(ctx, task, "log_indexes", "log_expired"); err != nil {
112+
log.Error("Failed to update task %v: %v", task.ID, err)
113+
// do not return error here, continue to next task
114+
continue
115+
}
116+
count++
117+
log.Trace("Removed log %s of task %v", task.LogFilename, task.ID)
118+
}
119+
if len(tasks) < deleteLogBatchSize {
120+
break
121+
}
122+
}
123+
124+
log.Info("Removed %d logs", count)
125+
return nil
126+
}

services/cron/tasks_actions.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ func registerScheduleTasks() {
6868
func registerActionsCleanup() {
6969
RegisterTaskFatal("cleanup_actions", &BaseConfig{
7070
Enabled: true,
71-
RunAtStart: true,
71+
RunAtStart: false,
7272
Schedule: "@midnight",
7373
}, func(ctx context.Context, _ *user_model.User, _ Config) error {
7474
return actions_service.Cleanup(ctx)

0 commit comments

Comments
 (0)