diff --git a/models/actions/run.go b/models/actions/run.go index 732fb48bb9a61..f87667a3b3dad 100644 --- a/models/actions/run.go +++ b/models/actions/run.go @@ -46,6 +46,8 @@ type ActionRun struct { TriggerEvent string // the trigger event defined in the `on` configuration of the triggered workflow Status Status `xorm:"index"` Version int `xorm:"version default 0"` // Status could be updated concomitantly, so an optimistic lock is needed + ConcurrencyGroup string + ConcurrencyCancel bool // Started and Stopped is used for recording last run time, if rerun happened, they will be reset to 0 Started timeutil.TimeStamp Stopped timeutil.TimeStamp @@ -195,13 +197,20 @@ func updateRepoRunsNumbers(ctx context.Context, repo *repo_model.Repository) err // It's useful when a new run is triggered, and all previous runs needn't be continued anymore. func CancelPreviousJobs(ctx context.Context, repoID int64, ref, workflowID string, event webhook_module.HookEventType) error { // Find all runs in the specified repository, reference, and workflow with non-final status - runs, total, err := db.FindAndCount[ActionRun](ctx, FindRunOptions{ + opts := &FindRunOptions{ RepoID: repoID, Ref: ref, WorkflowID: workflowID, TriggerEvent: event, Status: []Status{StatusRunning, StatusWaiting, StatusBlocked}, - }) + } + return CancelPreviousJobsWithOpts(ctx, opts) +} + +// CancelPreviousJobs cancels all previous jobs with opts +func CancelPreviousJobsWithOpts(ctx context.Context, opts *FindRunOptions) error { + // Find all runs by opts + runs, total, err := db.FindAndCount[ActionRun](ctx, opts) if err != nil { return err } @@ -221,42 +230,49 @@ func CancelPreviousJobs(ctx context.Context, repoID int64, ref, workflowID strin return err } - // Iterate over each job and attempt to cancel it. - for _, job := range jobs { - // Skip jobs that are already in a terminal state (completed, cancelled, etc.). - status := job.Status - if status.IsDone() { - continue - } + if err := CancelJobs(ctx, jobs); err != nil { + return err + } + } - // If the job has no associated task (probably an error), set its status to 'Cancelled' and stop it. - if job.TaskID == 0 { - job.Status = StatusCancelled - job.Stopped = timeutil.TimeStampNow() + // Return nil to indicate successful cancellation of all running and waiting jobs. + return nil +} - // Update the job's status and stopped time in the database. - n, err := UpdateRunJob(ctx, job, builder.Eq{"task_id": 0}, "status", "stopped") - if err != nil { - return err - } +func CancelJobs(ctx context.Context, jobs []*ActionRunJob) error { + // Iterate over each job and attempt to cancel it. + for _, job := range jobs { + // Skip jobs that are already in a terminal state (completed, cancelled, etc.). + status := job.Status + if status.IsDone() { + continue + } - // If the update affected 0 rows, it means the job has changed in the meantime, so we need to try again. - if n == 0 { - return fmt.Errorf("job has changed, try again") - } + // If the job has no associated task (probably an error), set its status to 'Cancelled' and stop it. + if job.TaskID == 0 { + job.Status = StatusCancelled + job.Stopped = timeutil.TimeStampNow() - // Continue with the next job. - continue + // Update the job's status and stopped time in the database. + n, err := UpdateRunJob(ctx, job, builder.Eq{"task_id": 0}, "status", "stopped") + if err != nil { + return err } - // If the job has an associated task, try to stop the task, effectively cancelling the job. - if err := StopTask(ctx, job.TaskID, StatusCancelled); err != nil { - return err + // If the update affected 0 rows, it means the job has changed in the meantime, so we need to try again. + if n == 0 { + return fmt.Errorf("job has changed, try again") } + + // Continue with the next job. + continue } - } - // Return nil to indicate successful cancellation of all running and waiting jobs. + // If the job has an associated task, try to stop the task, effectively cancelling the job. + if err := StopTask(ctx, job.TaskID, StatusCancelled); err != nil { + return err + } + } return nil } @@ -276,6 +292,32 @@ func InsertRun(ctx context.Context, run *ActionRun, jobs []*jobparser.SingleWork run.Index = index run.Title, _ = util.SplitStringAtByteN(run.Title, 255) + blockedByWorkflowConcurrency := false + if len(run.ConcurrencyGroup) > 0 { + if run.ConcurrencyCancel { + if err := CancelPreviousJobsWithOpts(ctx, &FindRunOptions{ + RepoID: run.RepoID, + ConcurrencyGroup: run.ConcurrencyGroup, + Status: []Status{StatusRunning, StatusWaiting, StatusBlocked}, + }); err != nil { + return err + } + } else { + waitingConcurrentRunsNum, err := db.Count[ActionRun](ctx, &FindRunOptions{ + RepoID: run.RepoID, + ConcurrencyGroup: run.ConcurrencyGroup, + Status: []Status{StatusWaiting}, + }) + if err != nil { + return err + } + blockedByWorkflowConcurrency = waitingConcurrentRunsNum > 0 + } + } + if blockedByWorkflowConcurrency { + run.Status = StatusBlocked + } + if err := db.Insert(ctx, run); err != nil { return err } @@ -302,13 +344,13 @@ func InsertRun(ctx context.Context, run *ActionRun, jobs []*jobparser.SingleWork } payload, _ := v.Marshal() status := StatusWaiting - if len(needs) > 0 || run.NeedApproval { + if len(needs) > 0 || run.NeedApproval || blockedByWorkflowConcurrency { status = StatusBlocked } else { hasWaiting = true } job.Name, _ = util.SplitStringAtByteN(job.Name, 255) - runJobs = append(runJobs, &ActionRunJob{ + runJob := &ActionRunJob{ RunID: run.ID, RepoID: run.RepoID, OwnerID: run.OwnerID, @@ -320,7 +362,12 @@ func InsertRun(ctx context.Context, run *ActionRun, jobs []*jobparser.SingleWork Needs: needs, RunsOn: job.RunsOn(), Status: status, - }) + } + if job.RawConcurrency != nil { + runJob.RawConcurrencyGroup = job.RawConcurrency.Group + runJob.RawConcurrencyCancel = job.RawConcurrency.CancelInProgress + } + runJobs = append(runJobs, runJob) } if err := db.Insert(ctx, runJobs); err != nil { return err diff --git a/models/actions/run_job.go b/models/actions/run_job.go index 4b8664077dca9..9be29eb8f27eb 100644 --- a/models/actions/run_job.go +++ b/models/actions/run_job.go @@ -33,10 +33,16 @@ type ActionRunJob struct { RunsOn []string `xorm:"JSON TEXT"` TaskID int64 // the latest task of the job Status Status `xorm:"index"` - Started timeutil.TimeStamp - Stopped timeutil.TimeStamp - Created timeutil.TimeStamp `xorm:"created"` - Updated timeutil.TimeStamp `xorm:"updated index"` + + RawConcurrencyGroup string // raw concurrency.group + RawConcurrencyCancel string // raw concurrency.cancel-in-progress + ConcurrencyGroup string // interpolated concurrency.group + ConcurrencyCancel bool // interpolated concurrency.cancel-in-progress + + Started timeutil.TimeStamp + Stopped timeutil.TimeStamp + Created timeutil.TimeStamp `xorm:"created"` + Updated timeutil.TimeStamp `xorm:"updated index"` } func init() { diff --git a/models/actions/run_job_list.go b/models/actions/run_job_list.go index 6c5d3b3252ebf..6b808b5abd888 100644 --- a/models/actions/run_job_list.go +++ b/models/actions/run_job_list.go @@ -48,12 +48,13 @@ func (jobs ActionJobList) LoadAttributes(ctx context.Context, withRepo bool) err type FindRunJobOptions struct { db.ListOptions - RunID int64 - RepoID int64 - OwnerID int64 - CommitSHA string - Statuses []Status - UpdatedBefore timeutil.TimeStamp + RunID int64 + RepoID int64 + OwnerID int64 + CommitSHA string + Statuses []Status + UpdatedBefore timeutil.TimeStamp + ConcurrencyGroup string } func (opts FindRunJobOptions) ToConds() builder.Cond { @@ -76,5 +77,8 @@ func (opts FindRunJobOptions) ToConds() builder.Cond { if opts.UpdatedBefore > 0 { cond = cond.And(builder.Lt{"updated": opts.UpdatedBefore}) } + if opts.ConcurrencyGroup != "" { + cond = cond.And(builder.Eq{"concurrency_group": opts.ConcurrencyGroup}) + } return cond } diff --git a/models/actions/run_list.go b/models/actions/run_list.go index 4046c7d369436..d30d1d46ce38e 100644 --- a/models/actions/run_list.go +++ b/models/actions/run_list.go @@ -63,14 +63,16 @@ func (runs RunList) LoadRepos(ctx context.Context) error { type FindRunOptions struct { db.ListOptions - RepoID int64 - OwnerID int64 - WorkflowID string - Ref string // the commit/tag/… that caused this workflow - TriggerUserID int64 - TriggerEvent webhook_module.HookEventType - Approved bool // not util.OptionalBool, it works only when it's true - Status []Status + RepoID int64 + OwnerID int64 + WorkflowID string + Ref string // the commit/tag/… that caused this workflow + TriggerUserID int64 + TriggerEvent webhook_module.HookEventType + Approved bool // not util.OptionalBool, it works only when it's true + Status []Status + SortType string + ConcurrencyGroup string } func (opts FindRunOptions) ToConds() builder.Cond { @@ -99,11 +101,21 @@ func (opts FindRunOptions) ToConds() builder.Cond { if opts.TriggerEvent != "" { cond = cond.And(builder.Eq{"trigger_event": opts.TriggerEvent}) } + if len(opts.ConcurrencyGroup) > 0 { + cond = cond.And(builder.Eq{"concurrency_group": opts.ConcurrencyGroup}) + } return cond } func (opts FindRunOptions) ToOrders() string { - return "`id` DESC" + switch opts.SortType { + case "oldest": + return "created ASC" + case "newest": + return "created DESC" + default: + return "`id` DESC" + } } type StatusInfo struct { diff --git a/models/migrations/migrations.go b/models/migrations/migrations.go index 52d10c4fe83a5..61495ef486088 100644 --- a/models/migrations/migrations.go +++ b/models/migrations/migrations.go @@ -369,6 +369,7 @@ func prepareMigrationTasks() []*migration { newMigration(309, "Improve Notification table indices", v1_23.ImproveNotificationTableIndices), newMigration(310, "Add Priority to ProtectedBranch", v1_23.AddPriorityToProtectedBranch), newMigration(311, "Add TimeEstimate to Issue table", v1_23.AddTimeEstimateColumnToIssueTable), + // TODO: AddActionsConcurrency } return preparedMigrations } diff --git a/models/migrations/v1_23/v312.go b/models/migrations/v1_23/v312.go new file mode 100644 index 0000000000000..8f81817f20045 --- /dev/null +++ b/models/migrations/v1_23/v312.go @@ -0,0 +1,28 @@ +// Copyright 2024 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package v1_23 //nolint + +import ( + "xorm.io/xorm" +) + +func AddActionsConcurrency(x *xorm.Engine) error { + type ActionRun struct { + ConcurrencyGroup string + ConcurrencyCancel bool + } + + if err := x.Sync(new(ActionRun)); err != nil { + return err + } + + type ActionRunJob struct { + RawConcurrencyGroup string + RawConcurrencyCancel string + ConcurrencyGroup string + ConcurrencyCancel bool + } + + return x.Sync(new(ActionRunJob)) +} diff --git a/modules/actions/workflows.go b/modules/actions/workflows.go index 0d2b0dd9194d9..01291a2a5f8f1 100644 --- a/modules/actions/workflows.go +++ b/modules/actions/workflows.go @@ -21,9 +21,10 @@ import ( ) type DetectedWorkflow struct { - EntryName string - TriggerEvent *jobparser.Event - Content []byte + EntryName string + TriggerEvent *jobparser.Event + Content []byte + RawConcurrency *model.RawConcurrency } func init() { @@ -95,6 +96,14 @@ func GetEventsFromContent(content []byte) ([]*jobparser.Event, error) { return events, nil } +func GetConcurrencyFromContent(content []byte) (*model.RawConcurrency, error) { + workflow, err := model.ReadWorkflow(bytes.NewReader(content)) + if err != nil { + return nil, err + } + return workflow.RawConcurrency, nil +} + func DetectWorkflows( gitRepo *git.Repository, commit *git.Commit, @@ -121,6 +130,11 @@ func DetectWorkflows( log.Warn("ignore invalid workflow %q: %v", entry.Name(), err) continue } + concurrency, err := GetConcurrencyFromContent(content) + if err != nil { + log.Warn("ignore workflow with invalid concurrency %q: %v", entry.Name(), err) + continue + } for _, evt := range events { log.Trace("detect workflow %q for event %#v matching %q", entry.Name(), evt, triggedEvent) if evt.IsSchedule() { @@ -134,9 +148,10 @@ func DetectWorkflows( } } else if detectMatched(gitRepo, commit, triggedEvent, payload, evt) { dwf := &DetectedWorkflow{ - EntryName: entry.Name(), - TriggerEvent: evt, - Content: content, + EntryName: entry.Name(), + TriggerEvent: evt, + Content: content, + RawConcurrency: concurrency, } workflows = append(workflows, dwf) } diff --git a/routers/api/actions/runner/utils.go b/routers/api/actions/runner/utils.go index ff6ec5bd54c62..fd9370050484c 100644 --- a/routers/api/actions/runner/utils.go +++ b/routers/api/actions/runner/utils.go @@ -8,14 +8,8 @@ import ( "fmt" actions_model "code.gitea.io/gitea/models/actions" - "code.gitea.io/gitea/models/db" secret_model "code.gitea.io/gitea/models/secret" - actions_module "code.gitea.io/gitea/modules/actions" - "code.gitea.io/gitea/modules/container" - "code.gitea.io/gitea/modules/git" - "code.gitea.io/gitea/modules/json" "code.gitea.io/gitea/modules/log" - "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/services/actions" runnerv1 "code.gitea.io/actions-proto-go/runner/v1" @@ -65,82 +59,16 @@ func pickTask(ctx context.Context, runner *actions_model.ActionRunner) (*runnerv } func generateTaskContext(t *actions_model.ActionTask) *structpb.Struct { - event := map[string]any{} - _ = json.Unmarshal([]byte(t.Job.Run.EventPayload), &event) - - // TriggerEvent is added in https://github.com/go-gitea/gitea/pull/25229 - // This fallback is for the old ActionRun that doesn't have the TriggerEvent field - // and should be removed in 1.22 - eventName := t.Job.Run.TriggerEvent - if eventName == "" { - eventName = t.Job.Run.Event.Event() - } - - baseRef := "" - headRef := "" - ref := t.Job.Run.Ref - sha := t.Job.Run.CommitSHA - if pullPayload, err := t.Job.Run.GetPullRequestEventPayload(); err == nil && pullPayload.PullRequest != nil && pullPayload.PullRequest.Base != nil && pullPayload.PullRequest.Head != nil { - baseRef = pullPayload.PullRequest.Base.Ref - headRef = pullPayload.PullRequest.Head.Ref - - // if the TriggerEvent is pull_request_target, ref and sha need to be set according to the base of pull request - // In GitHub's documentation, ref should be the branch or tag that triggered workflow. But when the TriggerEvent is pull_request_target, - // the ref will be the base branch. - if t.Job.Run.TriggerEvent == actions_module.GithubEventPullRequestTarget { - ref = git.BranchPrefix + pullPayload.PullRequest.Base.Name - sha = pullPayload.PullRequest.Base.Sha - } - } - - refName := git.RefName(ref) - giteaRuntimeToken, err := actions.CreateAuthorizationToken(t.ID, t.Job.RunID, t.JobID) if err != nil { log.Error("actions.CreateAuthorizationToken failed: %v", err) } - taskContext, err := structpb.NewStruct(map[string]any{ - // standard contexts, see https://docs.github.com/en/actions/learn-github-actions/contexts#github-context - "action": "", // string, The name of the action currently running, or the id of a step. GitHub removes special characters, and uses the name __run when the current step runs a script without an id. If you use the same action more than once in the same job, the name will include a suffix with the sequence number with underscore before it. For example, the first script you run will have the name __run, and the second script will be named __run_2. Similarly, the second invocation of actions/checkout will be actionscheckout2. - "action_path": "", // string, The path where an action is located. This property is only supported in composite actions. You can use this path to access files located in the same repository as the action. - "action_ref": "", // string, For a step executing an action, this is the ref of the action being executed. For example, v2. - "action_repository": "", // string, For a step executing an action, this is the owner and repository name of the action. For example, actions/checkout. - "action_status": "", // string, For a composite action, the current result of the composite action. - "actor": t.Job.Run.TriggerUser.Name, // string, The username of the user that triggered the initial workflow run. If the workflow run is a re-run, this value may differ from github.triggering_actor. Any workflow re-runs will use the privileges of github.actor, even if the actor initiating the re-run (github.triggering_actor) has different privileges. - "api_url": setting.AppURL + "api/v1", // string, The URL of the GitHub REST API. - "base_ref": baseRef, // string, The base_ref or target branch of the pull request in a workflow run. This property is only available when the event that triggers a workflow run is either pull_request or pull_request_target. - "env": "", // string, Path on the runner to the file that sets environment variables from workflow commands. This file is unique to the current step and is a different file for each step in a job. For more information, see "Workflow commands for GitHub Actions." - "event": event, // object, The full event webhook payload. You can access individual properties of the event using this context. This object is identical to the webhook payload of the event that triggered the workflow run, and is different for each event. The webhooks for each GitHub Actions event is linked in "Events that trigger workflows." For example, for a workflow run triggered by the push event, this object contains the contents of the push webhook payload. - "event_name": eventName, // string, The name of the event that triggered the workflow run. - "event_path": "", // string, The path to the file on the runner that contains the full event webhook payload. - "graphql_url": "", // string, The URL of the GitHub GraphQL API. - "head_ref": headRef, // string, The head_ref or source branch of the pull request in a workflow run. This property is only available when the event that triggers a workflow run is either pull_request or pull_request_target. - "job": fmt.Sprint(t.JobID), // string, The job_id of the current job. - "ref": ref, // string, The fully-formed ref of the branch or tag that triggered the workflow run. For workflows triggered by push, this is the branch or tag ref that was pushed. For workflows triggered by pull_request, this is the pull request merge branch. For workflows triggered by release, this is the release tag created. For other triggers, this is the branch or tag ref that triggered the workflow run. This is only set if a branch or tag is available for the event type. The ref given is fully-formed, meaning that for branches the format is refs/heads/, for pull requests it is refs/pull//merge, and for tags it is refs/tags/. For example, refs/heads/feature-branch-1. - "ref_name": refName.ShortName(), // string, The short ref name of the branch or tag that triggered the workflow run. This value matches the branch or tag name shown on GitHub. For example, feature-branch-1. - "ref_protected": false, // boolean, true if branch protections are configured for the ref that triggered the workflow run. - "ref_type": refName.RefType(), // string, The type of ref that triggered the workflow run. Valid values are branch or tag. - "path": "", // string, Path on the runner to the file that sets system PATH variables from workflow commands. This file is unique to the current step and is a different file for each step in a job. For more information, see "Workflow commands for GitHub Actions." - "repository": t.Job.Run.Repo.OwnerName + "/" + t.Job.Run.Repo.Name, // string, The owner and repository name. For example, Codertocat/Hello-World. - "repository_owner": t.Job.Run.Repo.OwnerName, // string, The repository owner's name. For example, Codertocat. - "repositoryUrl": t.Job.Run.Repo.HTMLURL(), // string, The Git URL to the repository. For example, git://github.com/codertocat/hello-world.git. - "retention_days": "", // string, The number of days that workflow run logs and artifacts are kept. - "run_id": fmt.Sprint(t.Job.RunID), // string, A unique number for each workflow run within a repository. This number does not change if you re-run the workflow run. - "run_number": fmt.Sprint(t.Job.Run.Index), // string, A unique number for each run of a particular workflow in a repository. This number begins at 1 for the workflow's first run, and increments with each new run. This number does not change if you re-run the workflow run. - "run_attempt": fmt.Sprint(t.Job.Attempt), // string, A unique number for each attempt of a particular workflow run in a repository. This number begins at 1 for the workflow run's first attempt, and increments with each re-run. - "secret_source": "Actions", // string, The source of a secret used in a workflow. Possible values are None, Actions, Dependabot, or Codespaces. - "server_url": setting.AppURL, // string, The URL of the GitHub server. For example: https://github.com. - "sha": sha, // string, The commit SHA that triggered the workflow. The value of this commit SHA depends on the event that triggered the workflow. For more information, see "Events that trigger workflows." For example, ffac537e6cbbf934b08745a378932722df287a53. - "token": t.Token, // string, A token to authenticate on behalf of the GitHub App installed on your repository. This is functionally equivalent to the GITHUB_TOKEN secret. For more information, see "Automatic token authentication." - "triggering_actor": "", // string, The username of the user that initiated the workflow run. If the workflow run is a re-run, this value may differ from github.actor. Any workflow re-runs will use the privileges of github.actor, even if the actor initiating the re-run (github.triggering_actor) has different privileges. - "workflow": t.Job.Run.WorkflowID, // string, The name of the workflow. If the workflow file doesn't specify a name, the value of this property is the full path of the workflow file in the repository. - "workspace": "", // string, The default working directory on the runner for steps, and the default location of your repository when using the checkout action. - - // additional contexts - "gitea_default_actions_url": setting.Actions.DefaultActionsURL.URL(), - "gitea_runtime_token": giteaRuntimeToken, - }) + ghCtx := actions.GenerateGitContext(t.Job.Run, t.Job) + ghCtx["token"] = t.Token + ghCtx["gitea_runtime_token"] = giteaRuntimeToken + + taskContext, err := structpb.NewStruct(ghCtx) if err != nil { log.Error("structpb.NewStruct failed: %v", err) } @@ -149,39 +77,16 @@ func generateTaskContext(t *actions_model.ActionTask) *structpb.Struct { } func findTaskNeeds(ctx context.Context, task *actions_model.ActionTask) (map[string]*runnerv1.TaskNeed, error) { - if err := task.LoadAttributes(ctx); err != nil { - return nil, fmt.Errorf("LoadAttributes: %w", err) - } - if len(task.Job.Needs) == 0 { - return nil, nil - } - needs := container.SetOf(task.Job.Needs...) - - jobs, err := db.Find[actions_model.ActionRunJob](ctx, actions_model.FindRunJobOptions{RunID: task.Job.RunID}) + taskNeeds, err := actions.FindTaskNeeds(ctx, task) if err != nil { - return nil, fmt.Errorf("FindRunJobs: %w", err) + return nil, err } - ret := make(map[string]*runnerv1.TaskNeed, len(needs)) - for _, job := range jobs { - if !needs.Contains(job.JobID) { - continue - } - if job.TaskID == 0 || !job.Status.IsDone() { - // it shouldn't happen, or the job has been rerun - continue - } - outputs := make(map[string]string) - got, err := actions_model.FindTaskOutputByTaskID(ctx, job.TaskID) - if err != nil { - return nil, fmt.Errorf("FindTaskOutputByTaskID: %w", err) - } - for _, v := range got { - outputs[v.OutputKey] = v.OutputValue - } - ret[job.JobID] = &runnerv1.TaskNeed{ - Outputs: outputs, - Result: runnerv1.Result(job.Status), + ret := make(map[string]*runnerv1.TaskNeed, len(taskNeeds)) + for jobID, taskNeed := range taskNeeds { + ret[jobID] = &runnerv1.TaskNeed{ + Outputs: taskNeed.Outputs, + Result: runnerv1.Result(taskNeed.Result), } } diff --git a/routers/web/repo/actions/view.go b/routers/web/repo/actions/view.go index 73c6e54fbf50a..5502e201aed1b 100644 --- a/routers/web/repo/actions/view.go +++ b/routers/web/repo/actions/view.go @@ -546,6 +546,7 @@ func Approve(ctx *context_module.Context) { } for _, job := range jobs { if len(job.Needs) == 0 && job.Status.IsBlocked() { + // TODO: check concurrency job.Status = actions_model.StatusWaiting _, err := actions_model.UpdateRunJob(ctx, job, nil, "status") if err != nil { diff --git a/services/actions/job_emitter.go b/services/actions/job_emitter.go index 1f859fcf70506..bfb1edc258e87 100644 --- a/services/actions/job_emitter.go +++ b/services/actions/job_emitter.go @@ -4,6 +4,7 @@ package actions import ( + "bytes" "context" "errors" "fmt" @@ -11,9 +12,11 @@ import ( actions_model "code.gitea.io/gitea/models/actions" "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/modules/graceful" + "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/queue" "github.com/nektos/act/pkg/jobparser" + act_model "github.com/nektos/act/pkg/model" "xorm.io/builder" ) @@ -37,25 +40,73 @@ func jobEmitterQueueHandler(items ...*jobUpdate) []*jobUpdate { ctx := graceful.GetManager().ShutdownContext() var ret []*jobUpdate for _, update := range items { - if err := checkJobsOfRun(ctx, update.RunID); err != nil { + if err := checkJobsByRunID(ctx, update.RunID); err != nil { ret = append(ret, update) } } return ret } -func checkJobsOfRun(ctx context.Context, runID int64) error { - jobs, err := db.Find[actions_model.ActionRunJob](ctx, actions_model.FindRunJobOptions{RunID: runID}) +func checkJobsByRunID(ctx context.Context, runID int64) error { + run, exist, err := db.GetByID[actions_model.ActionRun](ctx, runID) + if err != nil { + return fmt.Errorf("get action run: %w", err) + } + if !exist { + return fmt.Errorf("action run %d does not exist", runID) + } + + return db.WithTx(ctx, func(ctx context.Context) error { + // check jobs of the current run + if err := checkJobsOfRun(ctx, run); err != nil { + return err + } + + // check jobs by the concurrency group of the run + if len(run.ConcurrencyGroup) == 0 { + return nil + } + concurrentActionRuns, err := db.Find[actions_model.ActionRun](ctx, &actions_model.FindRunOptions{ + RepoID: run.RepoID, + ConcurrencyGroup: run.ConcurrencyGroup, + Status: []actions_model.Status{ + actions_model.StatusBlocked, + }, + SortType: "oldest", + }) + if err != nil { + return fmt.Errorf("find action run with concurrency group %s: %w", run.ConcurrencyGroup, err) + } + for _, cRun := range concurrentActionRuns { + if cRun.NeedApproval { + continue + } + if err := checkJobsOfRun(ctx, cRun); err != nil { + return err + } + break // only run one blocked action run with the same concurrency group + } + return nil + }) +} + +func checkJobsOfRun(ctx context.Context, run *actions_model.ActionRun) error { + jobs, err := db.Find[actions_model.ActionRunJob](ctx, actions_model.FindRunJobOptions{RunID: run.ID}) if err != nil { return err } + + vars, err := actions_model.GetVariablesOfRun(ctx, run) + if err != nil { + return fmt.Errorf("get run %d variables: %w", run.ID, err) + } + if err := db.WithTx(ctx, func(ctx context.Context) error { - idToJobs := make(map[string][]*actions_model.ActionRunJob, len(jobs)) for _, job := range jobs { - idToJobs[job.JobID] = append(idToJobs[job.JobID], job) + job.Run = run } - updates := newJobStatusResolver(jobs).Resolve() + updates := newJobStatusResolver(jobs, vars).Resolve(ctx) for _, job := range jobs { if status, ok := updates[job.ID]; ok { job.Status = status @@ -78,9 +129,10 @@ type jobStatusResolver struct { statuses map[int64]actions_model.Status needs map[int64][]int64 jobMap map[int64]*actions_model.ActionRunJob + vars map[string]string } -func newJobStatusResolver(jobs actions_model.ActionJobList) *jobStatusResolver { +func newJobStatusResolver(jobs actions_model.ActionJobList, vars map[string]string) *jobStatusResolver { idToJobs := make(map[string][]*actions_model.ActionRunJob, len(jobs)) jobMap := make(map[int64]*actions_model.ActionRunJob) for _, job := range jobs { @@ -102,13 +154,14 @@ func newJobStatusResolver(jobs actions_model.ActionJobList) *jobStatusResolver { statuses: statuses, needs: needs, jobMap: jobMap, + vars: vars, } } -func (r *jobStatusResolver) Resolve() map[int64]actions_model.Status { +func (r *jobStatusResolver) Resolve(ctx context.Context) map[int64]actions_model.Status { ret := map[int64]actions_model.Status{} for i := 0; i < len(r.statuses); i++ { - updated := r.resolve() + updated := r.resolve(ctx) if len(updated) == 0 { return ret } @@ -120,7 +173,7 @@ func (r *jobStatusResolver) Resolve() map[int64]actions_model.Status { return ret } -func (r *jobStatusResolver) resolve() map[int64]actions_model.Status { +func (r *jobStatusResolver) resolve(ctx context.Context) map[int64]actions_model.Status { ret := map[int64]actions_model.Status{} for id, status := range r.statuses { if status != actions_model.StatusBlocked { @@ -137,6 +190,17 @@ func (r *jobStatusResolver) resolve() map[int64]actions_model.Status { } } if allDone { + // check concurrency + blockedByJobConcurrency, err := checkJobConcurrency(ctx, r.jobMap[id], r.vars) + if err != nil { + log.Error("Check run %d job %d concurrency: %v. This job will stay blocked.") + continue + } + + if blockedByJobConcurrency { + continue + } + if allSucceed { ret[id] = actions_model.StatusWaiting } else { @@ -160,3 +224,85 @@ func (r *jobStatusResolver) resolve() map[int64]actions_model.Status { } return ret } + +func checkJobConcurrency(ctx context.Context, actionRunJob *actions_model.ActionRunJob, vars map[string]string) (bool, error) { + if len(actionRunJob.RawConcurrencyGroup) == 0 { + return false, nil + } + + run := actionRunJob.Run + + if len(actionRunJob.ConcurrencyGroup) == 0 { + rawConcurrency := &act_model.RawConcurrency{ + Group: actionRunJob.RawConcurrencyGroup, + CancelInProgress: actionRunJob.RawConcurrencyCancel, + } + + gitCtx := jobparser.ToGitContext(GenerateGitContext(run, actionRunJob)) + + actWorkflow, err := act_model.ReadWorkflow(bytes.NewReader(actionRunJob.WorkflowPayload)) + if err != nil { + return false, fmt.Errorf("read workflow: %w", err) + } + actJob := actWorkflow.GetJob(actionRunJob.JobID) + + task, err := actions_model.GetTaskByID(ctx, actionRunJob.TaskID) + if err != nil { + return false, fmt.Errorf("get task by id: %w", err) + } + taskNeeds, err := FindTaskNeeds(ctx, task) + if err != nil { + return false, fmt.Errorf("find task needs: %w", err) + } + + jobResults := make(map[string]*jobparser.JobResult, len(taskNeeds)) + for jobID, taskNeed := range taskNeeds { + jobResult := &jobparser.JobResult{ + Result: taskNeed.Result.String(), + Outputs: taskNeed.Outputs, + } + jobResults[jobID] = jobResult + } + + actionRunJob.ConcurrencyGroup, actionRunJob.ConcurrencyCancel = jobparser.InterpolatJobConcurrency(rawConcurrency, actJob, gitCtx, vars, jobResults) + if _, err := actions_model.UpdateRunJob(ctx, &actions_model.ActionRunJob{ + ID: actionRunJob.ID, + ConcurrencyGroup: actionRunJob.ConcurrencyGroup, + ConcurrencyCancel: actionRunJob.ConcurrencyCancel, + }, nil); err != nil { + return false, fmt.Errorf("update run job: %w", err) + } + } + + if actionRunJob.ConcurrencyCancel { + // cancel previous jobs in the same concurrency group + previousJobs, err := db.Find[actions_model.ActionRunJob](ctx, actions_model.FindRunJobOptions{ + RepoID: actionRunJob.RepoID, + ConcurrencyGroup: actionRunJob.ConcurrencyGroup, + Statuses: []actions_model.Status{ + actions_model.StatusRunning, + actions_model.StatusWaiting, + actions_model.StatusBlocked, + }, + }) + if err != nil { + return false, fmt.Errorf("find previous jobs: %w", err) + } + if err := actions_model.CancelJobs(ctx, previousJobs); err != nil { + return false, fmt.Errorf("cancel previous jobs: %w", err) + } + // we have cancelled all previous jobs, so this job does not need to be blocked + return false, nil + } + + waitingConcurrentJobsNum, err := db.Count[actions_model.ActionRunJob](ctx, actions_model.FindRunJobOptions{ + RepoID: actionRunJob.RepoID, + ConcurrencyGroup: actionRunJob.ConcurrencyGroup, + Statuses: []actions_model.Status{actions_model.StatusWaiting}, + }) + if err != nil { + return false, fmt.Errorf("count waiting jobs: %w", err) + } + + return waitingConcurrentJobsNum > 0, nil +} diff --git a/services/actions/job_emitter_test.go b/services/actions/job_emitter_test.go index 58c2dc3b242bb..5fe9c59dc32d9 100644 --- a/services/actions/job_emitter_test.go +++ b/services/actions/job_emitter_test.go @@ -4,6 +4,7 @@ package actions import ( + "context" "testing" actions_model "code.gitea.io/gitea/models/actions" @@ -129,8 +130,8 @@ jobs: } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - r := newJobStatusResolver(tt.jobs) - assert.Equal(t, tt.want, r.Resolve()) + r := newJobStatusResolver(tt.jobs, nil) + assert.Equal(t, tt.want, r.Resolve(context.Background())) }) } } diff --git a/services/actions/notifier_helper.go b/services/actions/notifier_helper.go index 323c6a76e422c..1c43341bf7996 100644 --- a/services/actions/notifier_helper.go +++ b/services/actions/notifier_helper.go @@ -332,26 +332,22 @@ func handleWorkflows( continue } + // check workflow concurrency + if dwf.RawConcurrency != nil { + wfGitCtx := jobparser.ToGitContext(GenerateGitContext(run, nil)) + wfConcurrencyGroup, wfConcurrencyCancel := jobparser.InterpolateWorkflowConcurrency(dwf.RawConcurrency, wfGitCtx, vars) + if len(wfConcurrencyGroup) > 0 { + run.ConcurrencyGroup = wfConcurrencyGroup + run.ConcurrencyCancel = wfConcurrencyCancel + } + } + jobs, err := jobparser.Parse(dwf.Content, jobparser.WithVars(vars)) if err != nil { log.Error("jobparser.Parse: %v", err) continue } - // cancel running jobs if the event is push or pull_request_sync - if run.Event == webhook_module.HookEventPush || - run.Event == webhook_module.HookEventPullRequestSync { - if err := actions_model.CancelPreviousJobs( - ctx, - run.RepoID, - run.Ref, - run.WorkflowID, - run.Event, - ); err != nil { - log.Error("CancelPreviousJobs: %v", err) - } - } - if err := actions_model.InsertRun(ctx, run, jobs); err != nil { log.Error("InsertRun: %v", err) continue diff --git a/services/actions/utils.go b/services/actions/utils.go new file mode 100644 index 0000000000000..3c3f61c6043ce --- /dev/null +++ b/services/actions/utils.go @@ -0,0 +1,144 @@ +// Copyright 2024 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package actions + +import ( + "context" + "fmt" + + actions_model "code.gitea.io/gitea/models/actions" + "code.gitea.io/gitea/models/db" + actions_module "code.gitea.io/gitea/modules/actions" + "code.gitea.io/gitea/modules/container" + "code.gitea.io/gitea/modules/git" + "code.gitea.io/gitea/modules/json" + "code.gitea.io/gitea/modules/setting" +) + +// GenerateGitContext generate the git context without token and gitea_runtime_token +// job can be nil when generating context for interpolating workflow-level expressions +func GenerateGitContext(run *actions_model.ActionRun, job *actions_model.ActionRunJob) map[string]any { + event := map[string]any{} + _ = json.Unmarshal([]byte(run.EventPayload), &event) + + // TriggerEvent is added in https://github.com/go-gitea/gitea/pull/25229 + // This fallback is for the old ActionRun that doesn't have the TriggerEvent field + // and should be removed in 1.22 + eventName := run.TriggerEvent + if eventName == "" { + eventName = run.Event.Event() + } + + baseRef := "" + headRef := "" + ref := run.Ref + sha := run.CommitSHA + if pullPayload, err := run.GetPullRequestEventPayload(); err == nil && pullPayload.PullRequest != nil && pullPayload.PullRequest.Base != nil && pullPayload.PullRequest.Head != nil { + baseRef = pullPayload.PullRequest.Base.Ref + headRef = pullPayload.PullRequest.Head.Ref + + // if the TriggerEvent is pull_request_target, ref and sha need to be set according to the base of pull request + // In GitHub's documentation, ref should be the branch or tag that triggered workflow. But when the TriggerEvent is pull_request_target, + // the ref will be the base branch. + if run.TriggerEvent == actions_module.GithubEventPullRequestTarget { + ref = git.BranchPrefix + pullPayload.PullRequest.Base.Name + sha = pullPayload.PullRequest.Base.Sha + } + } + + refName := git.RefName(ref) + + gitContext := map[string]any{ + // standard contexts, see https://docs.github.com/en/actions/learn-github-actions/contexts#github-context + "action": "", // string, The name of the action currently running, or the id of a step. GitHub removes special characters, and uses the name __run when the current step runs a script without an id. If you use the same action more than once in the same job, the name will include a suffix with the sequence number with underscore before it. For example, the first script you run will have the name __run, and the second script will be named __run_2. Similarly, the second invocation of actions/checkout will be actionscheckout2. + "action_path": "", // string, The path where an action is located. This property is only supported in composite actions. You can use this path to access files located in the same repository as the action. + "action_ref": "", // string, For a step executing an action, this is the ref of the action being executed. For example, v2. + "action_repository": "", // string, For a step executing an action, this is the owner and repository name of the action. For example, actions/checkout. + "action_status": "", // string, For a composite action, the current result of the composite action. + "actor": run.TriggerUser.Name, // string, The username of the user that triggered the initial workflow run. If the workflow run is a re-run, this value may differ from github.triggering_actor. Any workflow re-runs will use the privileges of github.actor, even if the actor initiating the re-run (github.triggering_actor) has different privileges. + "api_url": setting.AppURL + "api/v1", // string, The URL of the GitHub REST API. + "base_ref": baseRef, // string, The base_ref or target branch of the pull request in a workflow run. This property is only available when the event that triggers a workflow run is either pull_request or pull_request_target. + "env": "", // string, Path on the runner to the file that sets environment variables from workflow commands. This file is unique to the current step and is a different file for each step in a job. For more information, see "Workflow commands for GitHub Actions." + "event": event, // object, The full event webhook payload. You can access individual properties of the event using this context. This object is identical to the webhook payload of the event that triggered the workflow run, and is different for each event. The webhooks for each GitHub Actions event is linked in "Events that trigger workflows." For example, for a workflow run triggered by the push event, this object contains the contents of the push webhook payload. + "event_name": eventName, // string, The name of the event that triggered the workflow run. + "event_path": "", // string, The path to the file on the runner that contains the full event webhook payload. + "graphql_url": "", // string, The URL of the GitHub GraphQL API. + "head_ref": headRef, // string, The head_ref or source branch of the pull request in a workflow run. This property is only available when the event that triggers a workflow run is either pull_request or pull_request_target. + "job": "", // string, The job_id of the current job. + "ref": ref, // string, The fully-formed ref of the branch or tag that triggered the workflow run. For workflows triggered by push, this is the branch or tag ref that was pushed. For workflows triggered by pull_request, this is the pull request merge branch. For workflows triggered by release, this is the release tag created. For other triggers, this is the branch or tag ref that triggered the workflow run. This is only set if a branch or tag is available for the event type. The ref given is fully-formed, meaning that for branches the format is refs/heads/, for pull requests it is refs/pull//merge, and for tags it is refs/tags/. For example, refs/heads/feature-branch-1. + "ref_name": refName.ShortName(), // string, The short ref name of the branch or tag that triggered the workflow run. This value matches the branch or tag name shown on GitHub. For example, feature-branch-1. + "ref_protected": false, // boolean, true if branch protections are configured for the ref that triggered the workflow run. + "ref_type": refName.RefType(), // string, The type of ref that triggered the workflow run. Valid values are branch or tag. + "path": "", // string, Path on the runner to the file that sets system PATH variables from workflow commands. This file is unique to the current step and is a different file for each step in a job. For more information, see "Workflow commands for GitHub Actions." + "repository": run.Repo.OwnerName + "/" + run.Repo.Name, // string, The owner and repository name. For example, Codertocat/Hello-World. + "repository_owner": run.Repo.OwnerName, // string, The repository owner's name. For example, Codertocat. + "repositoryUrl": run.Repo.HTMLURL(), // string, The Git URL to the repository. For example, git://github.com/codertocat/hello-world.git. + "retention_days": "", // string, The number of days that workflow run logs and artifacts are kept. + "run_id": "", // string, A unique number for each workflow run within a repository. This number does not change if you re-run the workflow run. + "run_number": fmt.Sprint(run.Index), // string, A unique number for each run of a particular workflow in a repository. This number begins at 1 for the workflow's first run, and increments with each new run. This number does not change if you re-run the workflow run. + "run_attempt": "", // string, A unique number for each attempt of a particular workflow run in a repository. This number begins at 1 for the workflow run's first attempt, and increments with each re-run. + "secret_source": "Actions", // string, The source of a secret used in a workflow. Possible values are None, Actions, Dependabot, or Codespaces. + "server_url": setting.AppURL, // string, The URL of the GitHub server. For example: https://github.com. + "sha": sha, // string, The commit SHA that triggered the workflow. The value of this commit SHA depends on the event that triggered the workflow. For more information, see "Events that trigger workflows." For example, ffac537e6cbbf934b08745a378932722df287a53. + "triggering_actor": "", // string, The username of the user that initiated the workflow run. If the workflow run is a re-run, this value may differ from github.actor. Any workflow re-runs will use the privileges of github.actor, even if the actor initiating the re-run (github.triggering_actor) has different privileges. + "workflow": run.WorkflowID, // string, The name of the workflow. If the workflow file doesn't specify a name, the value of this property is the full path of the workflow file in the repository. + "workspace": "", // string, The default working directory on the runner for steps, and the default location of your repository when using the checkout action. + + // additional contexts + "gitea_default_actions_url": setting.Actions.DefaultActionsURL.URL(), + } + + if job != nil { + gitContext["job"] = job.JobID + gitContext["run_id"] = job.RunID + gitContext["run_attempt"] = job.Attempt + } + + return gitContext +} + +type TaskNeed struct { + Result actions_model.Status + Outputs map[string]string +} + +func FindTaskNeeds(ctx context.Context, task *actions_model.ActionTask) (map[string]*TaskNeed, error) { + if err := task.LoadAttributes(ctx); err != nil { + return nil, fmt.Errorf("LoadAttributes: %w", err) + } + if len(task.Job.Needs) == 0 { + return nil, nil + } + needs := container.SetOf(task.Job.Needs...) + + jobs, err := db.Find[actions_model.ActionRunJob](ctx, actions_model.FindRunJobOptions{RunID: task.Job.RunID}) + if err != nil { + return nil, fmt.Errorf("FindRunJobs: %w", err) + } + + ret := make(map[string]*TaskNeed, len(needs)) + for _, job := range jobs { + if !needs.Contains(job.JobID) { + continue + } + if job.TaskID == 0 || !job.Status.IsDone() { + // it shouldn't happen, or the job has been rerun + continue + } + outputs := make(map[string]string) + got, err := actions_model.FindTaskOutputByTaskID(ctx, job.TaskID) + if err != nil { + return nil, fmt.Errorf("FindTaskOutputByTaskID: %w", err) + } + for _, v := range got { + outputs[v.OutputKey] = v.OutputValue + } + ret[job.JobID] = &TaskNeed{ + Outputs: outputs, + Result: job.Status, + } + } + + return ret, nil +}