gitea源码

view.go 24KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864
  1. // Copyright 2022 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package actions
  4. import (
  5. "archive/zip"
  6. "compress/gzip"
  7. "context"
  8. "errors"
  9. "fmt"
  10. "html/template"
  11. "io"
  12. "net/http"
  13. "net/url"
  14. "strconv"
  15. "time"
  16. actions_model "code.gitea.io/gitea/models/actions"
  17. "code.gitea.io/gitea/models/db"
  18. git_model "code.gitea.io/gitea/models/git"
  19. repo_model "code.gitea.io/gitea/models/repo"
  20. "code.gitea.io/gitea/models/unit"
  21. "code.gitea.io/gitea/modules/actions"
  22. "code.gitea.io/gitea/modules/base"
  23. "code.gitea.io/gitea/modules/git"
  24. "code.gitea.io/gitea/modules/log"
  25. "code.gitea.io/gitea/modules/storage"
  26. "code.gitea.io/gitea/modules/templates"
  27. "code.gitea.io/gitea/modules/timeutil"
  28. "code.gitea.io/gitea/modules/util"
  29. "code.gitea.io/gitea/modules/web"
  30. "code.gitea.io/gitea/routers/common"
  31. actions_service "code.gitea.io/gitea/services/actions"
  32. context_module "code.gitea.io/gitea/services/context"
  33. notify_service "code.gitea.io/gitea/services/notify"
  34. "github.com/nektos/act/pkg/model"
  35. "xorm.io/builder"
  36. )
  37. func getRunIndex(ctx *context_module.Context) int64 {
  38. // if run param is "latest", get the latest run index
  39. if ctx.PathParam("run") == "latest" {
  40. if run, _ := actions_model.GetLatestRun(ctx, ctx.Repo.Repository.ID); run != nil {
  41. return run.Index
  42. }
  43. }
  44. return ctx.PathParamInt64("run")
  45. }
  46. func View(ctx *context_module.Context) {
  47. ctx.Data["PageIsActions"] = true
  48. runIndex := getRunIndex(ctx)
  49. jobIndex := ctx.PathParamInt64("job")
  50. ctx.Data["RunIndex"] = runIndex
  51. ctx.Data["JobIndex"] = jobIndex
  52. ctx.Data["ActionsURL"] = ctx.Repo.RepoLink + "/actions"
  53. if getRunJobs(ctx, runIndex, jobIndex); ctx.Written() {
  54. return
  55. }
  56. ctx.HTML(http.StatusOK, tplViewActions)
  57. }
  58. func ViewWorkflowFile(ctx *context_module.Context) {
  59. runIndex := getRunIndex(ctx)
  60. run, err := actions_model.GetRunByIndex(ctx, ctx.Repo.Repository.ID, runIndex)
  61. if err != nil {
  62. ctx.NotFoundOrServerError("GetRunByIndex", func(err error) bool {
  63. return errors.Is(err, util.ErrNotExist)
  64. }, err)
  65. return
  66. }
  67. commit, err := ctx.Repo.GitRepo.GetCommit(run.CommitSHA)
  68. if err != nil {
  69. ctx.NotFoundOrServerError("GetCommit", func(err error) bool {
  70. return errors.Is(err, util.ErrNotExist)
  71. }, err)
  72. return
  73. }
  74. rpath, entries, err := actions.ListWorkflows(commit)
  75. if err != nil {
  76. ctx.ServerError("ListWorkflows", err)
  77. return
  78. }
  79. for _, entry := range entries {
  80. if entry.Name() == run.WorkflowID {
  81. ctx.Redirect(fmt.Sprintf("%s/src/commit/%s/%s/%s", ctx.Repo.RepoLink, url.PathEscape(run.CommitSHA), util.PathEscapeSegments(rpath), util.PathEscapeSegments(run.WorkflowID)))
  82. return
  83. }
  84. }
  85. ctx.NotFound(nil)
  86. }
  87. type LogCursor struct {
  88. Step int `json:"step"`
  89. Cursor int64 `json:"cursor"`
  90. Expanded bool `json:"expanded"`
  91. }
  92. type ViewRequest struct {
  93. LogCursors []LogCursor `json:"logCursors"`
  94. }
  95. type ArtifactsViewItem struct {
  96. Name string `json:"name"`
  97. Size int64 `json:"size"`
  98. Status string `json:"status"`
  99. }
  100. type ViewResponse struct {
  101. Artifacts []*ArtifactsViewItem `json:"artifacts"`
  102. State struct {
  103. Run struct {
  104. Link string `json:"link"`
  105. Title string `json:"title"`
  106. TitleHTML template.HTML `json:"titleHTML"`
  107. Status string `json:"status"`
  108. CanCancel bool `json:"canCancel"`
  109. CanApprove bool `json:"canApprove"` // the run needs an approval and the doer has permission to approve
  110. CanRerun bool `json:"canRerun"`
  111. CanDeleteArtifact bool `json:"canDeleteArtifact"`
  112. Done bool `json:"done"`
  113. WorkflowID string `json:"workflowID"`
  114. WorkflowLink string `json:"workflowLink"`
  115. IsSchedule bool `json:"isSchedule"`
  116. Jobs []*ViewJob `json:"jobs"`
  117. Commit ViewCommit `json:"commit"`
  118. } `json:"run"`
  119. CurrentJob struct {
  120. Title string `json:"title"`
  121. Detail string `json:"detail"`
  122. Steps []*ViewJobStep `json:"steps"`
  123. } `json:"currentJob"`
  124. } `json:"state"`
  125. Logs struct {
  126. StepsLog []*ViewStepLog `json:"stepsLog"`
  127. } `json:"logs"`
  128. }
  129. type ViewJob struct {
  130. ID int64 `json:"id"`
  131. Name string `json:"name"`
  132. Status string `json:"status"`
  133. CanRerun bool `json:"canRerun"`
  134. Duration string `json:"duration"`
  135. }
  136. type ViewCommit struct {
  137. ShortSha string `json:"shortSHA"`
  138. Link string `json:"link"`
  139. Pusher ViewUser `json:"pusher"`
  140. Branch ViewBranch `json:"branch"`
  141. }
  142. type ViewUser struct {
  143. DisplayName string `json:"displayName"`
  144. Link string `json:"link"`
  145. }
  146. type ViewBranch struct {
  147. Name string `json:"name"`
  148. Link string `json:"link"`
  149. IsDeleted bool `json:"isDeleted"`
  150. }
  151. type ViewJobStep struct {
  152. Summary string `json:"summary"`
  153. Duration string `json:"duration"`
  154. Status string `json:"status"`
  155. }
  156. type ViewStepLog struct {
  157. Step int `json:"step"`
  158. Cursor int64 `json:"cursor"`
  159. Lines []*ViewStepLogLine `json:"lines"`
  160. Started int64 `json:"started"`
  161. }
  162. type ViewStepLogLine struct {
  163. Index int64 `json:"index"`
  164. Message string `json:"message"`
  165. Timestamp float64 `json:"timestamp"`
  166. }
  167. func getActionsViewArtifacts(ctx context.Context, repoID, runIndex int64) (artifactsViewItems []*ArtifactsViewItem, err error) {
  168. run, err := actions_model.GetRunByIndex(ctx, repoID, runIndex)
  169. if err != nil {
  170. return nil, err
  171. }
  172. artifacts, err := actions_model.ListUploadedArtifactsMeta(ctx, run.ID)
  173. if err != nil {
  174. return nil, err
  175. }
  176. for _, art := range artifacts {
  177. artifactsViewItems = append(artifactsViewItems, &ArtifactsViewItem{
  178. Name: art.ArtifactName,
  179. Size: art.FileSize,
  180. Status: util.Iif(art.Status == actions_model.ArtifactStatusExpired, "expired", "completed"),
  181. })
  182. }
  183. return artifactsViewItems, nil
  184. }
  185. func ViewPost(ctx *context_module.Context) {
  186. req := web.GetForm(ctx).(*ViewRequest)
  187. runIndex := getRunIndex(ctx)
  188. jobIndex := ctx.PathParamInt64("job")
  189. current, jobs := getRunJobs(ctx, runIndex, jobIndex)
  190. if ctx.Written() {
  191. return
  192. }
  193. run := current.Run
  194. if err := run.LoadAttributes(ctx); err != nil {
  195. ctx.ServerError("run.LoadAttributes", err)
  196. return
  197. }
  198. var err error
  199. resp := &ViewResponse{}
  200. resp.Artifacts, err = getActionsViewArtifacts(ctx, ctx.Repo.Repository.ID, runIndex)
  201. if err != nil {
  202. if !errors.Is(err, util.ErrNotExist) {
  203. ctx.ServerError("getActionsViewArtifacts", err)
  204. return
  205. }
  206. }
  207. // the title for the "run" is from the commit message
  208. resp.State.Run.Title = run.Title
  209. resp.State.Run.TitleHTML = templates.NewRenderUtils(ctx).RenderCommitMessage(run.Title, ctx.Repo.Repository)
  210. resp.State.Run.Link = run.Link()
  211. resp.State.Run.CanCancel = !run.Status.IsDone() && ctx.Repo.CanWrite(unit.TypeActions)
  212. resp.State.Run.CanApprove = run.NeedApproval && ctx.Repo.CanWrite(unit.TypeActions)
  213. resp.State.Run.CanRerun = run.Status.IsDone() && ctx.Repo.CanWrite(unit.TypeActions)
  214. resp.State.Run.CanDeleteArtifact = run.Status.IsDone() && ctx.Repo.CanWrite(unit.TypeActions)
  215. resp.State.Run.Done = run.Status.IsDone()
  216. resp.State.Run.WorkflowID = run.WorkflowID
  217. resp.State.Run.WorkflowLink = run.WorkflowLink()
  218. resp.State.Run.IsSchedule = run.IsSchedule()
  219. resp.State.Run.Jobs = make([]*ViewJob, 0, len(jobs)) // marshal to '[]' instead fo 'null' in json
  220. resp.State.Run.Status = run.Status.String()
  221. for _, v := range jobs {
  222. resp.State.Run.Jobs = append(resp.State.Run.Jobs, &ViewJob{
  223. ID: v.ID,
  224. Name: v.Name,
  225. Status: v.Status.String(),
  226. CanRerun: resp.State.Run.CanRerun,
  227. Duration: v.Duration().String(),
  228. })
  229. }
  230. pusher := ViewUser{
  231. DisplayName: run.TriggerUser.GetDisplayName(),
  232. Link: run.TriggerUser.HomeLink(),
  233. }
  234. branch := ViewBranch{
  235. Name: run.PrettyRef(),
  236. Link: run.RefLink(),
  237. }
  238. refName := git.RefName(run.Ref)
  239. if refName.IsBranch() {
  240. b, err := git_model.GetBranch(ctx, ctx.Repo.Repository.ID, refName.ShortName())
  241. if err != nil && !git_model.IsErrBranchNotExist(err) {
  242. log.Error("GetBranch: %v", err)
  243. } else if git_model.IsErrBranchNotExist(err) || (b != nil && b.IsDeleted) {
  244. branch.IsDeleted = true
  245. }
  246. }
  247. resp.State.Run.Commit = ViewCommit{
  248. ShortSha: base.ShortSha(run.CommitSHA),
  249. Link: fmt.Sprintf("%s/commit/%s", run.Repo.Link(), run.CommitSHA),
  250. Pusher: pusher,
  251. Branch: branch,
  252. }
  253. var task *actions_model.ActionTask
  254. if current.TaskID > 0 {
  255. var err error
  256. task, err = actions_model.GetTaskByID(ctx, current.TaskID)
  257. if err != nil {
  258. ctx.ServerError("actions_model.GetTaskByID", err)
  259. return
  260. }
  261. task.Job = current
  262. if err := task.LoadAttributes(ctx); err != nil {
  263. ctx.ServerError("task.LoadAttributes", err)
  264. return
  265. }
  266. }
  267. resp.State.CurrentJob.Title = current.Name
  268. resp.State.CurrentJob.Detail = current.Status.LocaleString(ctx.Locale)
  269. if run.NeedApproval {
  270. resp.State.CurrentJob.Detail = ctx.Locale.TrString("actions.need_approval_desc")
  271. }
  272. resp.State.CurrentJob.Steps = make([]*ViewJobStep, 0) // marshal to '[]' instead fo 'null' in json
  273. resp.Logs.StepsLog = make([]*ViewStepLog, 0) // marshal to '[]' instead fo 'null' in json
  274. if task != nil {
  275. steps, logs, err := convertToViewModel(ctx, req.LogCursors, task)
  276. if err != nil {
  277. ctx.ServerError("convertToViewModel", err)
  278. return
  279. }
  280. resp.State.CurrentJob.Steps = append(resp.State.CurrentJob.Steps, steps...)
  281. resp.Logs.StepsLog = append(resp.Logs.StepsLog, logs...)
  282. }
  283. ctx.JSON(http.StatusOK, resp)
  284. }
  285. func convertToViewModel(ctx *context_module.Context, cursors []LogCursor, task *actions_model.ActionTask) ([]*ViewJobStep, []*ViewStepLog, error) {
  286. var viewJobs []*ViewJobStep
  287. var logs []*ViewStepLog
  288. steps := actions.FullSteps(task)
  289. for _, v := range steps {
  290. viewJobs = append(viewJobs, &ViewJobStep{
  291. Summary: v.Name,
  292. Duration: v.Duration().String(),
  293. Status: v.Status.String(),
  294. })
  295. }
  296. for _, cursor := range cursors {
  297. if !cursor.Expanded {
  298. continue
  299. }
  300. step := steps[cursor.Step]
  301. // if task log is expired, return a consistent log line
  302. if task.LogExpired {
  303. if cursor.Cursor == 0 {
  304. logs = append(logs, &ViewStepLog{
  305. Step: cursor.Step,
  306. Cursor: 1,
  307. Lines: []*ViewStepLogLine{
  308. {
  309. Index: 1,
  310. Message: ctx.Locale.TrString("actions.runs.expire_log_message"),
  311. // Timestamp doesn't mean anything when the log is expired.
  312. // Set it to the task's updated time since it's probably the time when the log has expired.
  313. Timestamp: float64(task.Updated.AsTime().UnixNano()) / float64(time.Second),
  314. },
  315. },
  316. Started: int64(step.Started),
  317. })
  318. }
  319. continue
  320. }
  321. logLines := make([]*ViewStepLogLine, 0) // marshal to '[]' instead fo 'null' in json
  322. index := step.LogIndex + cursor.Cursor
  323. validCursor := cursor.Cursor >= 0 &&
  324. // !(cursor.Cursor < step.LogLength) when the frontend tries to fetch next line before it's ready.
  325. // So return the same cursor and empty lines to let the frontend retry.
  326. cursor.Cursor < step.LogLength &&
  327. // !(index < task.LogIndexes[index]) when task data is older than step data.
  328. // It can be fixed by making sure write/read tasks and steps in the same transaction,
  329. // but it's easier to just treat it as fetching the next line before it's ready.
  330. index < int64(len(task.LogIndexes))
  331. if validCursor {
  332. length := step.LogLength - cursor.Cursor
  333. offset := task.LogIndexes[index]
  334. logRows, err := actions.ReadLogs(ctx, task.LogInStorage, task.LogFilename, offset, length)
  335. if err != nil {
  336. return nil, nil, fmt.Errorf("actions.ReadLogs: %w", err)
  337. }
  338. for i, row := range logRows {
  339. logLines = append(logLines, &ViewStepLogLine{
  340. Index: cursor.Cursor + int64(i) + 1, // start at 1
  341. Message: row.Content,
  342. Timestamp: float64(row.Time.AsTime().UnixNano()) / float64(time.Second),
  343. })
  344. }
  345. }
  346. logs = append(logs, &ViewStepLog{
  347. Step: cursor.Step,
  348. Cursor: cursor.Cursor + int64(len(logLines)),
  349. Lines: logLines,
  350. Started: int64(step.Started),
  351. })
  352. }
  353. return viewJobs, logs, nil
  354. }
  355. // Rerun will rerun jobs in the given run
  356. // If jobIndexStr is a blank string, it means rerun all jobs
  357. func Rerun(ctx *context_module.Context) {
  358. runIndex := getRunIndex(ctx)
  359. jobIndexStr := ctx.PathParam("job")
  360. var jobIndex int64
  361. if jobIndexStr != "" {
  362. jobIndex, _ = strconv.ParseInt(jobIndexStr, 10, 64)
  363. }
  364. run, err := actions_model.GetRunByIndex(ctx, ctx.Repo.Repository.ID, runIndex)
  365. if err != nil {
  366. ctx.ServerError("GetRunByIndex", err)
  367. return
  368. }
  369. // can not rerun job when workflow is disabled
  370. cfgUnit := ctx.Repo.Repository.MustGetUnit(ctx, unit.TypeActions)
  371. cfg := cfgUnit.ActionsConfig()
  372. if cfg.IsWorkflowDisabled(run.WorkflowID) {
  373. ctx.JSONError(ctx.Locale.Tr("actions.workflow.disabled"))
  374. return
  375. }
  376. // reset run's start and stop time when it is done
  377. if run.Status.IsDone() {
  378. run.PreviousDuration = run.Duration()
  379. run.Started = 0
  380. run.Stopped = 0
  381. if err := actions_model.UpdateRun(ctx, run, "started", "stopped", "previous_duration"); err != nil {
  382. ctx.ServerError("UpdateRun", err)
  383. return
  384. }
  385. if err := run.LoadAttributes(ctx); err != nil {
  386. ctx.ServerError("run.LoadAttributes", err)
  387. return
  388. }
  389. notify_service.WorkflowRunStatusUpdate(ctx, run.Repo, run.TriggerUser, run)
  390. }
  391. job, jobs := getRunJobs(ctx, runIndex, jobIndex)
  392. if ctx.Written() {
  393. return
  394. }
  395. if jobIndexStr == "" { // rerun all jobs
  396. for _, j := range jobs {
  397. // if the job has needs, it should be set to "blocked" status to wait for other jobs
  398. shouldBlock := len(j.Needs) > 0
  399. if err := rerunJob(ctx, j, shouldBlock); err != nil {
  400. ctx.ServerError("RerunJob", err)
  401. return
  402. }
  403. }
  404. ctx.JSONOK()
  405. return
  406. }
  407. rerunJobs := actions_service.GetAllRerunJobs(job, jobs)
  408. for _, j := range rerunJobs {
  409. // jobs other than the specified one should be set to "blocked" status
  410. shouldBlock := j.JobID != job.JobID
  411. if err := rerunJob(ctx, j, shouldBlock); err != nil {
  412. ctx.ServerError("RerunJob", err)
  413. return
  414. }
  415. }
  416. ctx.JSONOK()
  417. }
  418. func rerunJob(ctx *context_module.Context, job *actions_model.ActionRunJob, shouldBlock bool) error {
  419. status := job.Status
  420. if !status.IsDone() || !job.Run.Status.IsDone() {
  421. return nil
  422. }
  423. job.TaskID = 0
  424. job.Status = actions_model.StatusWaiting
  425. if shouldBlock {
  426. job.Status = actions_model.StatusBlocked
  427. }
  428. job.Started = 0
  429. job.Stopped = 0
  430. if err := db.WithTx(ctx, func(ctx context.Context) error {
  431. _, err := actions_model.UpdateRunJob(ctx, job, builder.Eq{"status": status}, "task_id", "status", "started", "stopped")
  432. return err
  433. }); err != nil {
  434. return err
  435. }
  436. actions_service.CreateCommitStatus(ctx, job)
  437. notify_service.WorkflowJobStatusUpdate(ctx, job.Run.Repo, job.Run.TriggerUser, job, nil)
  438. return nil
  439. }
  440. func Logs(ctx *context_module.Context) {
  441. runIndex := getRunIndex(ctx)
  442. jobIndex := ctx.PathParamInt64("job")
  443. run, err := actions_model.GetRunByIndex(ctx, ctx.Repo.Repository.ID, runIndex)
  444. if err != nil {
  445. ctx.NotFoundOrServerError("GetRunByIndex", func(err error) bool {
  446. return errors.Is(err, util.ErrNotExist)
  447. }, err)
  448. return
  449. }
  450. if err = common.DownloadActionsRunJobLogsWithIndex(ctx.Base, ctx.Repo.Repository, run.ID, jobIndex); err != nil {
  451. ctx.NotFoundOrServerError("DownloadActionsRunJobLogsWithIndex", func(err error) bool {
  452. return errors.Is(err, util.ErrNotExist)
  453. }, err)
  454. }
  455. }
  456. func Cancel(ctx *context_module.Context) {
  457. runIndex := getRunIndex(ctx)
  458. _, jobs := getRunJobs(ctx, runIndex, -1)
  459. if ctx.Written() {
  460. return
  461. }
  462. var updatedjobs []*actions_model.ActionRunJob
  463. if err := db.WithTx(ctx, func(ctx context.Context) error {
  464. for _, job := range jobs {
  465. status := job.Status
  466. if status.IsDone() {
  467. continue
  468. }
  469. if job.TaskID == 0 {
  470. job.Status = actions_model.StatusCancelled
  471. job.Stopped = timeutil.TimeStampNow()
  472. n, err := actions_model.UpdateRunJob(ctx, job, builder.Eq{"task_id": 0}, "status", "stopped")
  473. if err != nil {
  474. return err
  475. }
  476. if n == 0 {
  477. return errors.New("job has changed, try again")
  478. }
  479. if n > 0 {
  480. updatedjobs = append(updatedjobs, job)
  481. }
  482. continue
  483. }
  484. if err := actions_model.StopTask(ctx, job.TaskID, actions_model.StatusCancelled); err != nil {
  485. return err
  486. }
  487. }
  488. return nil
  489. }); err != nil {
  490. ctx.ServerError("StopTask", err)
  491. return
  492. }
  493. actions_service.CreateCommitStatus(ctx, jobs...)
  494. for _, job := range updatedjobs {
  495. _ = job.LoadAttributes(ctx)
  496. notify_service.WorkflowJobStatusUpdate(ctx, job.Run.Repo, job.Run.TriggerUser, job, nil)
  497. }
  498. if len(updatedjobs) > 0 {
  499. job := updatedjobs[0]
  500. actions_service.NotifyWorkflowRunStatusUpdateWithReload(ctx, job)
  501. }
  502. ctx.JSONOK()
  503. }
  504. func Approve(ctx *context_module.Context) {
  505. runIndex := getRunIndex(ctx)
  506. current, jobs := getRunJobs(ctx, runIndex, -1)
  507. if ctx.Written() {
  508. return
  509. }
  510. run := current.Run
  511. doer := ctx.Doer
  512. var updatedjobs []*actions_model.ActionRunJob
  513. if err := db.WithTx(ctx, func(ctx context.Context) error {
  514. run.NeedApproval = false
  515. run.ApprovedBy = doer.ID
  516. if err := actions_model.UpdateRun(ctx, run, "need_approval", "approved_by"); err != nil {
  517. return err
  518. }
  519. for _, job := range jobs {
  520. if len(job.Needs) == 0 && job.Status.IsBlocked() {
  521. job.Status = actions_model.StatusWaiting
  522. n, err := actions_model.UpdateRunJob(ctx, job, nil, "status")
  523. if err != nil {
  524. return err
  525. }
  526. if n > 0 {
  527. updatedjobs = append(updatedjobs, job)
  528. }
  529. }
  530. }
  531. return nil
  532. }); err != nil {
  533. ctx.ServerError("UpdateRunJob", err)
  534. return
  535. }
  536. actions_service.CreateCommitStatus(ctx, jobs...)
  537. if len(updatedjobs) > 0 {
  538. job := updatedjobs[0]
  539. actions_service.NotifyWorkflowRunStatusUpdateWithReload(ctx, job)
  540. }
  541. for _, job := range updatedjobs {
  542. _ = job.LoadAttributes(ctx)
  543. notify_service.WorkflowJobStatusUpdate(ctx, job.Run.Repo, job.Run.TriggerUser, job, nil)
  544. }
  545. ctx.JSONOK()
  546. }
  547. func Delete(ctx *context_module.Context) {
  548. runIndex := getRunIndex(ctx)
  549. repoID := ctx.Repo.Repository.ID
  550. run, err := actions_model.GetRunByIndex(ctx, repoID, runIndex)
  551. if err != nil {
  552. if errors.Is(err, util.ErrNotExist) {
  553. ctx.JSONErrorNotFound()
  554. return
  555. }
  556. ctx.ServerError("GetRunByIndex", err)
  557. return
  558. }
  559. if !run.Status.IsDone() {
  560. ctx.JSONError(ctx.Tr("actions.runs.not_done"))
  561. return
  562. }
  563. if err := actions_service.DeleteRun(ctx, run); err != nil {
  564. ctx.ServerError("DeleteRun", err)
  565. return
  566. }
  567. ctx.JSONOK()
  568. }
  569. // getRunJobs gets the jobs of runIndex, and returns jobs[jobIndex], jobs.
  570. // Any error will be written to the ctx.
  571. // It never returns a nil job of an empty jobs, if the jobIndex is out of range, it will be treated as 0.
  572. func getRunJobs(ctx *context_module.Context, runIndex, jobIndex int64) (*actions_model.ActionRunJob, []*actions_model.ActionRunJob) {
  573. run, err := actions_model.GetRunByIndex(ctx, ctx.Repo.Repository.ID, runIndex)
  574. if err != nil {
  575. if errors.Is(err, util.ErrNotExist) {
  576. ctx.NotFound(nil)
  577. return nil, nil
  578. }
  579. ctx.ServerError("GetRunByIndex", err)
  580. return nil, nil
  581. }
  582. run.Repo = ctx.Repo.Repository
  583. jobs, err := actions_model.GetRunJobsByRunID(ctx, run.ID)
  584. if err != nil {
  585. ctx.ServerError("GetRunJobsByRunID", err)
  586. return nil, nil
  587. }
  588. if len(jobs) == 0 {
  589. ctx.NotFound(nil)
  590. return nil, nil
  591. }
  592. for _, v := range jobs {
  593. v.Run = run
  594. }
  595. if jobIndex >= 0 && jobIndex < int64(len(jobs)) {
  596. return jobs[jobIndex], jobs
  597. }
  598. return jobs[0], jobs
  599. }
  600. func ArtifactsDeleteView(ctx *context_module.Context) {
  601. runIndex := getRunIndex(ctx)
  602. artifactName := ctx.PathParam("artifact_name")
  603. run, err := actions_model.GetRunByIndex(ctx, ctx.Repo.Repository.ID, runIndex)
  604. if err != nil {
  605. ctx.NotFoundOrServerError("GetRunByIndex", func(err error) bool {
  606. return errors.Is(err, util.ErrNotExist)
  607. }, err)
  608. return
  609. }
  610. if err = actions_model.SetArtifactNeedDelete(ctx, run.ID, artifactName); err != nil {
  611. ctx.ServerError("SetArtifactNeedDelete", err)
  612. return
  613. }
  614. ctx.JSON(http.StatusOK, struct{}{})
  615. }
  616. func ArtifactsDownloadView(ctx *context_module.Context) {
  617. runIndex := getRunIndex(ctx)
  618. artifactName := ctx.PathParam("artifact_name")
  619. run, err := actions_model.GetRunByIndex(ctx, ctx.Repo.Repository.ID, runIndex)
  620. if err != nil {
  621. if errors.Is(err, util.ErrNotExist) {
  622. ctx.HTTPError(http.StatusNotFound, err.Error())
  623. return
  624. }
  625. ctx.ServerError("GetRunByIndex", err)
  626. return
  627. }
  628. artifacts, err := db.Find[actions_model.ActionArtifact](ctx, actions_model.FindArtifactsOptions{
  629. RunID: run.ID,
  630. ArtifactName: artifactName,
  631. })
  632. if err != nil {
  633. ctx.ServerError("FindArtifacts", err)
  634. return
  635. }
  636. if len(artifacts) == 0 {
  637. ctx.HTTPError(http.StatusNotFound, "artifact not found")
  638. return
  639. }
  640. // if artifacts status is not uploaded-confirmed, treat it as not found
  641. for _, art := range artifacts {
  642. if art.Status != actions_model.ArtifactStatusUploadConfirmed {
  643. ctx.HTTPError(http.StatusNotFound, "artifact not found")
  644. return
  645. }
  646. }
  647. ctx.Resp.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s.zip; filename*=UTF-8''%s.zip", url.PathEscape(artifactName), artifactName))
  648. if len(artifacts) == 1 && actions.IsArtifactV4(artifacts[0]) {
  649. err := actions.DownloadArtifactV4(ctx.Base, artifacts[0])
  650. if err != nil {
  651. ctx.ServerError("DownloadArtifactV4", err)
  652. return
  653. }
  654. return
  655. }
  656. // Artifacts using the v1-v3 backend are stored as multiple individual files per artifact on the backend
  657. // Those need to be zipped for download
  658. writer := zip.NewWriter(ctx.Resp)
  659. defer writer.Close()
  660. for _, art := range artifacts {
  661. f, err := storage.ActionsArtifacts.Open(art.StoragePath)
  662. if err != nil {
  663. ctx.ServerError("ActionsArtifacts.Open", err)
  664. return
  665. }
  666. var r io.ReadCloser
  667. if art.ContentEncoding == "gzip" {
  668. r, err = gzip.NewReader(f)
  669. if err != nil {
  670. ctx.ServerError("gzip.NewReader", err)
  671. return
  672. }
  673. } else {
  674. r = f
  675. }
  676. defer r.Close()
  677. w, err := writer.Create(art.ArtifactPath)
  678. if err != nil {
  679. ctx.ServerError("writer.Create", err)
  680. return
  681. }
  682. if _, err := io.Copy(w, r); err != nil {
  683. ctx.ServerError("io.Copy", err)
  684. return
  685. }
  686. }
  687. }
  688. func DisableWorkflowFile(ctx *context_module.Context) {
  689. disableOrEnableWorkflowFile(ctx, false)
  690. }
  691. func EnableWorkflowFile(ctx *context_module.Context) {
  692. disableOrEnableWorkflowFile(ctx, true)
  693. }
  694. func disableOrEnableWorkflowFile(ctx *context_module.Context, isEnable bool) {
  695. workflow := ctx.FormString("workflow")
  696. if len(workflow) == 0 {
  697. ctx.ServerError("workflow", nil)
  698. return
  699. }
  700. cfgUnit := ctx.Repo.Repository.MustGetUnit(ctx, unit.TypeActions)
  701. cfg := cfgUnit.ActionsConfig()
  702. if isEnable {
  703. cfg.EnableWorkflow(workflow)
  704. } else {
  705. cfg.DisableWorkflow(workflow)
  706. }
  707. if err := repo_model.UpdateRepoUnit(ctx, cfgUnit); err != nil {
  708. ctx.ServerError("UpdateRepoUnit", err)
  709. return
  710. }
  711. if isEnable {
  712. ctx.Flash.Success(ctx.Tr("actions.workflow.enable_success", workflow))
  713. } else {
  714. ctx.Flash.Success(ctx.Tr("actions.workflow.disable_success", workflow))
  715. }
  716. redirectURL := fmt.Sprintf("%s/actions?workflow=%s&actor=%s&status=%s", ctx.Repo.RepoLink, url.QueryEscape(workflow),
  717. url.QueryEscape(ctx.FormString("actor")), url.QueryEscape(ctx.FormString("status")))
  718. ctx.JSONRedirect(redirectURL)
  719. }
  720. func Run(ctx *context_module.Context) {
  721. redirectURL := fmt.Sprintf("%s/actions?workflow=%s&actor=%s&status=%s", ctx.Repo.RepoLink, url.QueryEscape(ctx.FormString("workflow")),
  722. url.QueryEscape(ctx.FormString("actor")), url.QueryEscape(ctx.FormString("status")))
  723. workflowID := ctx.FormString("workflow")
  724. if len(workflowID) == 0 {
  725. ctx.ServerError("workflow", nil)
  726. return
  727. }
  728. ref := ctx.FormString("ref")
  729. if len(ref) == 0 {
  730. ctx.ServerError("ref", nil)
  731. return
  732. }
  733. err := actions_service.DispatchActionWorkflow(ctx, ctx.Doer, ctx.Repo.Repository, ctx.Repo.GitRepo, workflowID, ref, func(workflowDispatch *model.WorkflowDispatch, inputs map[string]any) error {
  734. for name, config := range workflowDispatch.Inputs {
  735. value := ctx.Req.PostFormValue(name)
  736. if config.Type == "boolean" {
  737. inputs[name] = strconv.FormatBool(ctx.FormBool(name))
  738. } else if value != "" {
  739. inputs[name] = value
  740. } else {
  741. inputs[name] = config.Default
  742. }
  743. }
  744. return nil
  745. })
  746. if err != nil {
  747. if errLocale := util.ErrorAsLocale(err); errLocale != nil {
  748. ctx.Flash.Error(ctx.Tr(errLocale.TrKey, errLocale.TrArgs...))
  749. ctx.Redirect(redirectURL)
  750. } else {
  751. ctx.ServerError("DispatchActionWorkflow", err)
  752. }
  753. return
  754. }
  755. ctx.Flash.Success(ctx.Tr("actions.workflow.run_success", workflowID))
  756. ctx.Redirect(redirectURL)
  757. }