mirror of
https://github.com/go-gitea/gitea.git
synced 2026-08-11 06:46:20 +00:00
feat(actions): Add Actions API endpoints for workflow run management and logs (#35382)
Implements the missing REST API endpoints for Actions workflow run
management:
1. `POST /actions/runs/{run}/cancel` cancels a run and its jobs, `409`
when it already finished
1. `POST /actions/runs/{run}/approve` approves a run awaiting approval,
idempotent, `409` when it never awaited one
1. `GET /actions/runs/{run}/logs` downloads the latest attempt's job
logs as a zip archive
`ActionWorkflowRun` gains `created_at`, `updated_at` and the `jobs_url`,
`logs_url`, `artifacts_url`, `cancel_url` and `rerun_url` fields, and
now always emits `conclusion` and `head_branch`.
Cancellation is shared with the web handler in `services/actions`.
Fixes https://github.com/go-gitea/gitea/issues/35176
Fixes https://github.com/go-gitea/gitea/issues/36554
---------
Co-authored-by: Claude Sonnet 4.6 <claude-sonnet-4-6@anthropic.com>
Co-authored-by: OpenCode Agent <opencode@rossgolder.com>
Co-authored-by: Nicolas <bircni@icloud.com>
Co-authored-by: silverwind <me@silverwind.io>
Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
This commit is contained in:
@@ -1362,8 +1362,13 @@ func Routes() *web.Router {
|
||||
m.Delete("", reqToken(), reqRepoWriter(unit.TypeActions), repo.DeleteActionRun)
|
||||
m.Post("/rerun", reqToken(), reqRepoWriter(unit.TypeActions), repo.RerunWorkflowRun)
|
||||
m.Post("/rerun-failed-jobs", reqToken(), reqRepoWriter(unit.TypeActions), repo.RerunFailedWorkflowRun)
|
||||
m.Get("/jobs", repo.ListWorkflowRunJobs)
|
||||
m.Post("/jobs/{job_id}/rerun", reqToken(), reqRepoWriter(unit.TypeActions), repo.RerunWorkflowJob)
|
||||
m.Post("/cancel", reqToken(), reqRepoWriter(unit.TypeActions), repo.CancelWorkflowRun)
|
||||
m.Post("/approve", reqToken(), reqRepoWriter(unit.TypeActions), repo.ApproveWorkflowRun)
|
||||
m.Group("/jobs", func() {
|
||||
m.Get("", repo.ListWorkflowRunJobs)
|
||||
m.Post("/{job_id}/rerun", reqToken(), reqRepoWriter(unit.TypeActions), repo.RerunWorkflowJob)
|
||||
})
|
||||
m.Get("/logs", reqToken(), repo.GetWorkflowRunLogs)
|
||||
m.Get("/artifacts", repo.GetArtifactsOfRun)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1291,7 +1291,7 @@ func getCurrentRepoActionRunJobsByID(ctx *context.APIContext) (*actions_model.Ac
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
jobs, err := actions_model.GetLatestAttemptJobsByRepoAndRunID(ctx, run.RepoID, run.ID)
|
||||
jobs, err := actions_model.GetLatestAttemptJobsByRun(ctx, run)
|
||||
if err != nil {
|
||||
ctx.APIErrorInternal(err)
|
||||
return nil, nil
|
||||
@@ -1315,6 +1315,16 @@ func getCurrentRepoActionRunAttemptByNumber(ctx *context.APIContext) (*actions_m
|
||||
return run, attempt
|
||||
}
|
||||
|
||||
func respondRepoActionWorkflowRun(ctx *context.APIContext, run *actions_model.ActionRun) {
|
||||
run.Repo = ctx.Repo.Repository
|
||||
convertedRun, err := convert.ToActionWorkflowRun(ctx, run, nil, false)
|
||||
if err != nil {
|
||||
ctx.APIErrorInternal(err)
|
||||
return
|
||||
}
|
||||
ctx.JSON(http.StatusOK, convertedRun)
|
||||
}
|
||||
|
||||
// GetWorkflowRun Gets a specific workflow run.
|
||||
func GetWorkflowRun(ctx *context.APIContext) {
|
||||
// swagger:operation GET /repos/{owner}/{repo}/actions/runs/{run} repository GetWorkflowRun
|
||||
@@ -1351,12 +1361,7 @@ func GetWorkflowRun(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
convertedRun, err := convert.ToActionWorkflowRun(ctx, run, nil, false)
|
||||
if err != nil {
|
||||
ctx.APIErrorInternal(err)
|
||||
return
|
||||
}
|
||||
ctx.JSON(http.StatusOK, convertedRun)
|
||||
respondRepoActionWorkflowRun(ctx, run)
|
||||
}
|
||||
|
||||
// GetWorkflowRunAttempt Gets a specific workflow run attempt.
|
||||
|
||||
@@ -4,8 +4,11 @@
|
||||
package repo
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
actions_model "gitea.dev/models/actions"
|
||||
"gitea.dev/routers/common"
|
||||
actions_service "gitea.dev/services/actions"
|
||||
"gitea.dev/services/context"
|
||||
)
|
||||
|
||||
@@ -45,13 +48,157 @@ func DownloadActionsRunJobLogs(ctx *context.APIContext) {
|
||||
ctx.APIErrorAuto(err)
|
||||
return
|
||||
}
|
||||
if err = curJob.LoadRepo(ctx); err != nil {
|
||||
ctx.APIErrorInternal(err)
|
||||
return
|
||||
}
|
||||
|
||||
err = common.DownloadActionsRunJobLogs(ctx.Base, ctx.Repo.Repository, curJob)
|
||||
if err != nil {
|
||||
ctx.APIErrorAuto(err)
|
||||
}
|
||||
}
|
||||
|
||||
func CancelWorkflowRun(ctx *context.APIContext) {
|
||||
// swagger:operation POST /repos/{owner}/{repo}/actions/runs/{run}/cancel repository cancelWorkflowRun
|
||||
// ---
|
||||
// summary: Cancel a workflow run and its jobs
|
||||
// produces:
|
||||
// - application/json
|
||||
// parameters:
|
||||
// - name: owner
|
||||
// in: path
|
||||
// description: owner of the repo
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: repo
|
||||
// in: path
|
||||
// description: name of the repository
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: run
|
||||
// in: path
|
||||
// description: run ID
|
||||
// type: integer
|
||||
// required: true
|
||||
// responses:
|
||||
// "200":
|
||||
// "$ref": "#/responses/WorkflowRun"
|
||||
// "400":
|
||||
// "$ref": "#/responses/error"
|
||||
// "403":
|
||||
// "$ref": "#/responses/forbidden"
|
||||
// "404":
|
||||
// "$ref": "#/responses/notFound"
|
||||
// "409":
|
||||
// "$ref": "#/responses/conflict"
|
||||
|
||||
run, jobs := getCurrentRepoActionRunJobsByID(ctx)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
|
||||
// Cancelling a finished run would change nothing, so report a conflict instead of a false success.
|
||||
if run.Status.IsDone() {
|
||||
ctx.APIError(http.StatusConflict, "run is already completed")
|
||||
return
|
||||
}
|
||||
|
||||
run, err := actions_service.CancelRun(ctx, run, jobs)
|
||||
if err != nil {
|
||||
ctx.APIErrorAuto(err)
|
||||
return
|
||||
}
|
||||
respondRepoActionWorkflowRun(ctx, run)
|
||||
}
|
||||
|
||||
func ApproveWorkflowRun(ctx *context.APIContext) {
|
||||
// swagger:operation POST /repos/{owner}/{repo}/actions/runs/{run}/approve repository approveWorkflowRun
|
||||
// ---
|
||||
// summary: Approve a workflow run that requires approval
|
||||
// produces:
|
||||
// - application/json
|
||||
// parameters:
|
||||
// - name: owner
|
||||
// in: path
|
||||
// description: owner of the repo
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: repo
|
||||
// in: path
|
||||
// description: name of the repository
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: run
|
||||
// in: path
|
||||
// description: run ID
|
||||
// type: integer
|
||||
// required: true
|
||||
// responses:
|
||||
// "200":
|
||||
// "$ref": "#/responses/WorkflowRun"
|
||||
// "400":
|
||||
// "$ref": "#/responses/error"
|
||||
// "403":
|
||||
// "$ref": "#/responses/forbidden"
|
||||
// "404":
|
||||
// "$ref": "#/responses/notFound"
|
||||
// "409":
|
||||
// "$ref": "#/responses/conflict"
|
||||
|
||||
run := getCurrentRepoActionRunByID(ctx)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
|
||||
if !run.NeedApproval {
|
||||
// Approving twice is idempotent, but a run that never awaited approval gets 409 rather
|
||||
// than GitHub's 403, which would be indistinguishable from a permission denial.
|
||||
if run.ApprovedBy == 0 {
|
||||
ctx.APIError(http.StatusConflict, "run does not require approval")
|
||||
return
|
||||
}
|
||||
respondRepoActionWorkflowRun(ctx, run)
|
||||
return
|
||||
}
|
||||
|
||||
approvedRuns, err := actions_service.ApproveRuns(ctx, ctx.Repo.Repository, ctx.Doer, []int64{run.ID})
|
||||
if err != nil {
|
||||
ctx.APIErrorAuto(err)
|
||||
return
|
||||
}
|
||||
respondRepoActionWorkflowRun(ctx, approvedRuns[0])
|
||||
}
|
||||
|
||||
func GetWorkflowRunLogs(ctx *context.APIContext) {
|
||||
// swagger:operation GET /repos/{owner}/{repo}/actions/runs/{run}/logs repository getWorkflowRunLogs
|
||||
// ---
|
||||
// summary: Download workflow run logs as archive
|
||||
// produces:
|
||||
// - application/zip
|
||||
// parameters:
|
||||
// - name: owner
|
||||
// in: path
|
||||
// description: owner of the repo
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: repo
|
||||
// in: path
|
||||
// description: name of the repository
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: run
|
||||
// in: path
|
||||
// description: run ID
|
||||
// type: integer
|
||||
// required: true
|
||||
// responses:
|
||||
// "200":
|
||||
// description: Logs archive
|
||||
// "404":
|
||||
// "$ref": "#/responses/notFound"
|
||||
|
||||
run := getCurrentRepoActionRunByID(ctx)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
|
||||
if err := common.DownloadActionsRunAllJobLogs(ctx.Base, run); err != nil {
|
||||
ctx.APIErrorAuto(err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -205,7 +205,6 @@ func ListRuns(ctx *context.APIContext, ownerID, repoID int64, workflowID string)
|
||||
}
|
||||
|
||||
res := new(api.ActionWorkflowRunsResponse)
|
||||
res.TotalCount = total
|
||||
|
||||
runList := actions_model.RunList(runs)
|
||||
if err := runList.LoadTriggerUser(ctx); err != nil {
|
||||
@@ -225,16 +224,23 @@ func ListRuns(ctx *context.APIContext, ownerID, repoID int64, workflowID string)
|
||||
return
|
||||
}
|
||||
|
||||
res.Entries = make([]*api.ActionWorkflowRun, len(runs))
|
||||
for i := range runs {
|
||||
res.Entries = make([]*api.ActionWorkflowRun, 0, len(runs))
|
||||
for _, run := range runs {
|
||||
if run.Repo == nil {
|
||||
// Orphaned row: drop it rather than failing the page, so total stays an upper bound
|
||||
// until "doctor check --run check-db-consistency" removes it.
|
||||
total--
|
||||
continue
|
||||
}
|
||||
// TODO: load run attempts in batch
|
||||
convertedRun, err := convert.ToActionWorkflowRun(ctx, runs[i], nil, excludePullRequests)
|
||||
convertedRun, err := convert.ToActionWorkflowRun(ctx, run, nil, excludePullRequests)
|
||||
if err != nil {
|
||||
ctx.APIErrorInternal(err)
|
||||
return
|
||||
}
|
||||
res.Entries[i] = convertedRun
|
||||
res.Entries = append(res.Entries, convertedRun)
|
||||
}
|
||||
res.TotalCount = total
|
||||
ctx.SetLinkHeader(total, listOptions.PageSize)
|
||||
ctx.SetTotalCountHeader(total)
|
||||
ctx.JSON(http.StatusOK, &res)
|
||||
|
||||
+82
-24
@@ -4,68 +4,126 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"strings"
|
||||
|
||||
actions_model "gitea.dev/models/actions"
|
||||
repo_model "gitea.dev/models/repo"
|
||||
"gitea.dev/modules/actions"
|
||||
"gitea.dev/modules/container"
|
||||
"gitea.dev/modules/httplib"
|
||||
"gitea.dev/modules/log"
|
||||
"gitea.dev/modules/util"
|
||||
"gitea.dev/services/context"
|
||||
context_module "gitea.dev/services/context"
|
||||
)
|
||||
|
||||
func DownloadActionsRunJobLogsWithID(ctx *context.Base, ctxRepo *repo_model.Repository, runID, jobID int64) error {
|
||||
func openTaskLogs(ctx context.Context, task *actions_model.ActionTask) (io.ReadSeekCloser, error) {
|
||||
reader, err := actions.OpenLogs(ctx, task.LogInStorage, task.LogFilename)
|
||||
if errors.Is(err, fs.ErrNotExist) {
|
||||
// convert fs err to our own error type so that the API can return a 404 instead of a 500
|
||||
return nil, util.NewNotExistErrorf("unable to open task logs: %s", task.LogFilename)
|
||||
}
|
||||
return reader, err
|
||||
}
|
||||
|
||||
func DownloadActionsRunJobLogsWithID(ctx *context_module.Base, ctxRepo *repo_model.Repository, runID, jobID int64) error {
|
||||
job, err := actions_model.GetRunJobByRunAndID(ctx, runID, jobID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := job.LoadRepo(ctx); err != nil {
|
||||
return fmt.Errorf("LoadRepo: %w", err)
|
||||
}
|
||||
return DownloadActionsRunJobLogs(ctx, ctxRepo, job)
|
||||
}
|
||||
|
||||
func DownloadActionsRunJobLogs(ctx *context.Base, ctxRepo *repo_model.Repository, curJob *actions_model.ActionRunJob) error {
|
||||
if curJob.Repo.ID != ctxRepo.ID {
|
||||
return util.NewNotExistErrorf("job not found")
|
||||
// DownloadActionsRunAllJobLogs assumes the run was already resolved against the requesting repository.
|
||||
func DownloadActionsRunAllJobLogs(ctx *context_module.Base, run *actions_model.ActionRun) error {
|
||||
runJobs, err := actions_model.GetLatestAttemptJobsByRun(ctx, run)
|
||||
if err != nil {
|
||||
return fmt.Errorf("GetLatestAttemptJobsByRun: %w", err)
|
||||
}
|
||||
|
||||
taskID := curJob.EffectiveTaskID()
|
||||
if taskID == 0 {
|
||||
return util.NewNotExistErrorf("job not started")
|
||||
tasks, err := actions_model.GetTasksMapByIDs(ctx, container.FilterSlice(runJobs, func(job *actions_model.ActionRunJob) (int64, bool) {
|
||||
taskID := job.EffectiveTaskID()
|
||||
return taskID, taskID != 0
|
||||
}))
|
||||
if err != nil {
|
||||
return fmt.Errorf("GetTasksMapByIDs: %w", err)
|
||||
}
|
||||
|
||||
// Delay the headers until the first log opens, afterwards a failure can no longer reach
|
||||
// the client, so the remaining entries are best-effort.
|
||||
var zipWriter *zip.Writer
|
||||
for _, job := range runJobs {
|
||||
task := tasks[job.EffectiveTaskID()]
|
||||
if task == nil || task.LogExpired {
|
||||
continue
|
||||
}
|
||||
|
||||
reader, err := openTaskLogs(ctx, task)
|
||||
if err != nil {
|
||||
log.Error("Failed to open logs of job %d: %v", job.ID, err)
|
||||
continue
|
||||
}
|
||||
|
||||
if zipWriter == nil {
|
||||
ctx.SetServeHeaders(context_module.ServeHeaderOptions{
|
||||
Filename: util.FileNameJoinFields(util.PathBaseStem(run.WorkflowID), "run", run.ID, "logs", ".zip"),
|
||||
ContentType: "application/zip",
|
||||
ContentDisposition: httplib.ContentDispositionAttachment,
|
||||
})
|
||||
zipWriter = zip.NewWriter(ctx.Resp)
|
||||
}
|
||||
|
||||
zipFile, err := zipWriter.Create(util.FileNameJoinFields(util.PathBaseStem(run.WorkflowID), job.Name, task.ID, ".log"))
|
||||
if err == nil {
|
||||
_, err = io.Copy(zipFile, reader)
|
||||
}
|
||||
reader.Close()
|
||||
if err != nil {
|
||||
log.Error("Failed to add logs of job %d to zip: %v", job.ID, err)
|
||||
}
|
||||
}
|
||||
if zipWriter == nil {
|
||||
return util.NewNotExistErrorf("logs not found")
|
||||
}
|
||||
if err := zipWriter.Close(); err != nil {
|
||||
log.Error("Failed to finalize logs zip of run %d: %v", run.ID, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func DownloadActionsRunJobLogs(ctx *context_module.Base, ctxRepo *repo_model.Repository, curJob *actions_model.ActionRunJob) error {
|
||||
if curJob.RepoID != ctxRepo.ID {
|
||||
return util.NewNotExistErrorf("job not found")
|
||||
}
|
||||
|
||||
if err := curJob.LoadRun(ctx); err != nil {
|
||||
return fmt.Errorf("LoadRun: %w", err)
|
||||
}
|
||||
|
||||
taskID := curJob.EffectiveTaskID()
|
||||
if taskID == 0 {
|
||||
return util.NewNotExistErrorf("job not started")
|
||||
}
|
||||
task, err := actions_model.GetTaskByID(ctx, taskID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("GetTaskByID: %w", err)
|
||||
}
|
||||
|
||||
if task.LogExpired {
|
||||
return util.NewNotExistErrorf("logs have been cleaned up")
|
||||
}
|
||||
|
||||
reader, err := actions.OpenLogs(ctx, task.LogInStorage, task.LogFilename)
|
||||
reader, err := openTaskLogs(ctx, task)
|
||||
if err != nil {
|
||||
if errors.Is(err, fs.ErrNotExist) {
|
||||
return util.NewNotExistErrorf("logs not found")
|
||||
}
|
||||
return fmt.Errorf("OpenLogs: %w", err)
|
||||
return err
|
||||
}
|
||||
defer reader.Close()
|
||||
|
||||
workflowName := curJob.Run.WorkflowID
|
||||
if p := strings.Index(workflowName, "."); p > 0 {
|
||||
workflowName = workflowName[0:p]
|
||||
}
|
||||
ctx.ServeContent(reader, context.ServeHeaderOptions{
|
||||
Filename: fmt.Sprintf("%v-%v-%v.log", workflowName, curJob.Name, task.ID),
|
||||
ctx.ServeContent(reader, context_module.ServeHeaderOptions{
|
||||
Filename: util.FileNameJoinFields(util.PathBaseStem(curJob.Run.WorkflowID), curJob.Name, task.ID, ".log"),
|
||||
ContentLength: &task.LogSize,
|
||||
ContentType: "text/plain; charset=utf-8",
|
||||
ContentDisposition: httplib.ContentDispositionAttachment,
|
||||
|
||||
@@ -1050,27 +1050,10 @@ func Cancel(ctx *context_module.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
var updatedJobs []*actions_model.ActionRunJob
|
||||
|
||||
if err := db.WithTx(ctx, func(ctx context.Context) error {
|
||||
cancelledJobs, err := actions_model.CancelJobs(ctx, jobs)
|
||||
if err != nil {
|
||||
return fmt.Errorf("cancel jobs: %w", err)
|
||||
}
|
||||
updatedJobs = append(updatedJobs, cancelledJobs...)
|
||||
return nil
|
||||
}); err != nil {
|
||||
ctx.ServerError("StopTask", err)
|
||||
if _, err := actions_service.CancelRun(ctx, run, jobs); err != nil {
|
||||
ctx.ServerError("CancelRun", err)
|
||||
return
|
||||
}
|
||||
|
||||
actions_service.CreateCommitStatusForRunJobs(ctx, run, jobs...)
|
||||
actions_service.EmitJobsIfReadyByJobs(updatedJobs)
|
||||
|
||||
actions_service.NotifyWorkflowJobsStatusUpdate(ctx, updatedJobs...)
|
||||
if len(updatedJobs) > 0 {
|
||||
actions_service.NotifyWorkflowRunStatusUpdateWithReload(ctx, run.RepoID, run.ID)
|
||||
}
|
||||
ctx.JSONOK()
|
||||
}
|
||||
|
||||
@@ -1079,7 +1062,7 @@ func Approve(ctx *context_module.Context) {
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
if err := actions_service.ApproveRuns(ctx, ctx.Repo.Repository, ctx.Doer, []int64{run.ID}); err != nil {
|
||||
if _, err := actions_service.ApproveRuns(ctx, ctx.Repo.Repository, ctx.Doer, []int64{run.ID}); err != nil {
|
||||
ctx.NotFoundOrServerError("ApproveRuns", func(err error) bool {
|
||||
return errors.Is(err, util.ErrNotExist)
|
||||
}, err)
|
||||
@@ -1345,7 +1328,7 @@ func ApproveAllChecks(ctx *context_module.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
if err := actions_service.ApproveRuns(ctx, repo, ctx.Doer, runIDs); err != nil {
|
||||
if _, err := actions_service.ApproveRuns(ctx, repo, ctx.Doer, runIDs); err != nil {
|
||||
ctx.NotFoundOrServerError("ApproveRuns", func(err error) bool {
|
||||
return errors.Is(err, util.ErrNotExist)
|
||||
}, err)
|
||||
|
||||
Reference in New Issue
Block a user