Compare commits

...

7 Commits

Author SHA1 Message Date
bircni
a8d0d8a7e0 enhance: run JavaScript actions on a pinned Node.js (#1400)
- The runner downloads its own Node.js 24 for JavaScript actions and `hashFiles()`, as GitHub's runner does, so job images and hosts no longer need `node`.
- Each build's version and SHA-256 are pinned and kept current by the weekly Renovate updates, from nodejs.org (or `NODEJS_ORG_MIRROR`) and, for Alpine, from https://github.com/actions/alpine_nodejs.
- Host, Docker and Kubernetes jobs use it, Docker jobs share one read-only volume per version.
- `runner.node_version` downloads a different version instead, checked against its published SHA-256.
- Where it can't be provided, jobs use the `node` on `PATH`, and `runner.node_download: false` always does.

Fixes: https://gitea.com/gitea/runner/issues/1393
Fixes: https://gitea.com/gitea/runner/issues/538

_Written by Claude (Opus 5.5)._
Co-authored-by: silverwind <me@silverwind.io>
Co-authored-by: silverwind <2021+silverwind@noreply.gitea.com>
Reviewed-on: https://gitea.com/gitea/runner/pulls/1400
Reviewed-by: silverwind <2021+silverwind@noreply.gitea.com>
2026-11-27 16:31:36 +00:00
silverwind
03bb09a656 fix: composite action masks, systempaths option and locked action clones (#1424)
- A composite action started in its pre stage shares masks with its job in every stage, so values masked by earlier steps stay masked inside it and neither side loses a mask
- `systempaths=unconfined` in container options takes effect instead of being dropped when options are merged
- A cached action or reusable workflow clone left locked by a killed git is cloned fresh instead of failing every later job
- actionslib v1.7.1 validates the contexts a reusable workflow caller's `with:` may use, from https://gitea.com/gitea/actionslib/pulls/36

_Written by Claude (Opus 5.5)._

Reviewed-on: https://gitea.com/gitea/runner/pulls/1424
Reviewed-by: bircni <bircni@icloud.com>
Co-authored-by: silverwind <2021+silverwind@noreply.gitea.com>
2026-11-27 13:16:07 +00:00
silverwind
e6d621d079 fix: upload artifacts directly when jobs cannot reach the runner's cache (#1425)
- Jobs that cannot reach the runner's `docker_gwbridge` address skip the cache with a warning, instead of timing out on artifact uploads
- Document how to keep the cache when jobs cannot reach the detected `cache.host`

Fixes https://gitea.com/gitea/runner/issues/1423

_Written by Claude (Opus 5.5)._

Reviewed-on: https://gitea.com/gitea/runner/pulls/1425
Reviewed-by: bircni <bircni@icloud.com>
Co-authored-by: silverwind <2021+silverwind@noreply.gitea.com>
2026-11-27 13:06:50 +00:00
bircni
fdd383b5c5 enhance: add host.stable_workdir for predictable host job paths (#1402)
- Add opt-in `host.stable_workdir`, which runs Linux host jobs in `<host.workdir_parent>/workspaces/<owner>/<repo>/<repo>`, like GitHub's `_work/<repo>/<repo>`, instead of a random directory
- Give each job a private mount namespace, so concurrent jobs of a repository share that path with separate files, and show one running job's files at the path on the host
- Needs `CAP_SYS_ADMIN`, without it jobs keep the random directory and log a warning

Fixes: https://gitea.com/gitea/runner/issues/1373
Co-authored-by: silverwind <me@silverwind.io>
Reviewed-on: https://gitea.com/gitea/runner/pulls/1402
Reviewed-by: silverwind <2021+silverwind@noreply.gitea.com>
Co-authored-by: bircni <bircni@icloud.com>
2026-11-27 07:05:06 +00:00
Renovate Bot
8167d12a43 chore(deps): update dependencies (#1422)
This PR contains the following updates:

| Package | Type | Update | Change | Pending | [Age](https://docs.renovatebot.com/merge-confidence/) | [Confidence](https://docs.renovatebot.com/merge-confidence/) |
|---|---|---|---|---|---|---|
| [actions/setup-go](https://github.com/actions/setup-go) ([changelog](b7ad1dad31..d8cbb8045d)) | action | digest | `b7ad1da` → `d8cbb80` |  |  |  |
| [docker](https://hub.docker.com/_/docker) ([source](https://github.com/docker-library/docker)) | stage | minor | `29.9.3-dind-rootless` → `29.10.0-dind-rootless` |  | ![age](https://developer.mend.io/api/mc/badges/age/docker/docker/29.10.0?slim=true) | ![confidence](https://developer.mend.io/api/mc/badges/confidence/docker/docker/29.9.3/29.10.0?slim=true) |
| [docker](https://hub.docker.com/_/docker) ([source](https://github.com/docker-library/docker)) | stage | minor | `29.9.3-dind` → `29.10.0-dind` |  | ![age](https://developer.mend.io/api/mc/badges/age/docker/docker/29.10.0?slim=true) | ![confidence](https://developer.mend.io/api/mc/badges/confidence/docker/docker/29.9.3/29.10.0?slim=true) |
| docker.gitea.com/runner-images |  | digest | `139605d` → `433d703` |  |  |  |
| [github.com/docker/cli](https://github.com/docker/cli) | require | minor | `v29.9.3+incompatible` → `v29.10.0+incompatible` |  | ![age](https://developer.mend.io/api/mc/badges/age/go/github.com%2fdocker%2fcli/v29.10.0+incompatible?slim=true) | ![confidence](https://developer.mend.io/api/mc/badges/confidence/go/github.com%2fdocker%2fcli/v29.9.3+incompatible/v29.10.0+incompatible?slim=true) |
| [github.com/moby/moby/api](https://github.com/moby/moby) | require | minor | `v1.56.1` → `v1.57.0` |  | ![age](https://developer.mend.io/api/mc/badges/age/go/github.com%2fmoby%2fmoby%2fapi/v1.57.0?slim=true) | ![confidence](https://developer.mend.io/api/mc/badges/confidence/go/github.com%2fmoby%2fmoby%2fapi/v1.56.1/v1.57.0?slim=true) |
| [github.com/moby/moby/client](https://github.com/moby/moby) | require | patch | `v0.6.2` → `v0.6.3` |  | ![age](https://developer.mend.io/api/mc/badges/age/go/github.com%2fmoby%2fmoby%2fclient/v0.6.3?slim=true) | ![confidence](https://developer.mend.io/api/mc/badges/confidence/go/github.com%2fmoby%2fmoby%2fclient/v0.6.2/v0.6.3?slim=true) |
| [golang.org/x/net](https://pkg.go.dev/golang.org/x/net) | require | minor | [`v0.62.0` → `v0.63.0`](https://cs.opensource.google/go/x/net/+/refs/tags/v0.62.0...refs/tags/v0.63.0) |  | ![age](https://developer.mend.io/api/mc/badges/age/go/golang.org%2fx%2fnet/v0.63.0?slim=true) | ![confidence](https://developer.mend.io/api/mc/badges/confidence/go/golang.org%2fx%2fnet/v0.62.0/v0.63.0?slim=true) |
| [golang.org/x/vuln](https://go.googlesource.com/vuln) |  | minor | `v1.9.0` → `v1.10.0` |  | ![age](https://developer.mend.io/api/mc/badges/age/go/golang.org%2fx%2fvuln/v1.10.0?slim=true) | ![confidence](https://developer.mend.io/api/mc/badges/confidence/go/golang.org%2fx%2fvuln/v1.9.0/v1.10.0?slim=true) |
| [nginx](https://hub.docker.com/_/nginx) ([source](https://github.com/nginx/docker-nginx)) |  | patch | `1.31.7-alpine` → `1.31.8-alpine` | `1.31.9-alpine` | ![age](https://developer.mend.io/api/mc/badges/age/docker/nginx/1.31.8?slim=true) | ![confidence](https://developer.mend.io/api/mc/badges/confidence/docker/nginx/1.31.7/1.31.8?slim=true) |
| [node](https://hub.docker.com/_/node) ([source](https://github.com/nodejs/node)) |  | digest | `bc0a2af` → `5df7998` |  |  |  |
| [quay.io/containers/podman](https://quay.io/containers/podman) ([source](https://github.com/podman-container-tools/podman)) |  | minor | `v6.1.3-immutable` → `v6.2.0-immutable` |  | ![age](https://developer.mend.io/api/mc/badges/age/docker/quay.io%2fcontainers%2fpodman/v6.2.0?slim=true) | ![confidence](https://developer.mend.io/api/mc/badges/confidence/docker/quay.io%2fcontainers%2fpodman/v6.1.3/v6.2.0?slim=true) |

---

### Release Notes

<details>
<summary>docker/cli (github.com/docker/cli)</summary>

### [`v29.10.0+incompatible`](https://github.com/docker/cli/compare/v29.9.3...v29.10.0)

[Compare Source](https://github.com/docker/cli/compare/v29.9.3...v29.10.0)

</details>

<details>
<summary>moby/moby (github.com/moby/moby/api)</summary>

### [`v1.57.0`](https://github.com/moby/moby/releases/tag/api/v1.57.0)

#### 1.57.0

##### Engine API specification moves to OpenAPI 3.2

> \[!WARNING]
> The Engine API specification now uses OpenAPI 3.2 as its source format, in [`api/openapi.yaml`](https://github.com/moby/moby/blob/api/v1.57.0/api/openapi.yaml).
> A Swagger 2.0 specification generated from it is still published for existing tooling, in [`api/swagger.yaml`](https://github.com/moby/moby/blob/api/v1.57.0/api/swagger.yaml).
> For the transition, this release also includes a Swagger 2.0 copy pinned to API v1.57, in [`api/docs/v1.57-swagger.yaml`](https://github.com/moby/moby/blob/api/v1.57.0/api/docs/v1.57-swagger.yaml).
> Future API versions won't get a per-version Swagger 2.0 copy, so update tooling that depends on these files to use the OpenAPI 3.2 specifications. [moby/moby#53630](https://github.com/moby/moby/pull/53630)

##### Changelog

- `GET /events`: Container `die` events now include a `restarting` attribute, set to `"true"` when the container is about to restart, either from its restart policy or from a manual restart. [moby/moby#50908](https://github.com/moby/moby/pull/50908)
  The attribute is omitted when the container won't restart, including during daemon shutdown.
  It announces the restart but doesn't guarantee it, because the restart can still be cancelled or fail.
- Fix the `ImageManifestSummary.ImageData` schema, which listed `UnpackedSize` as required even though that field doesn't exist. The unpacked size is reported in `Size.Unpacked`. [moby/moby#53750](https://github.com/moby/moby/pull/53750)
- Migrate the Engine API specification from Swagger 2.0 to OpenAPI 3.2. [moby/moby#53630](https://github.com/moby/moby/pull/53630)

</details>

<details>
<summary>nginx/docker-nginx (nginx)</summary>

### [`v1.31.8`](https://github.com/nginx/docker-nginx/compare/1.31.7...1.31.8)

[Compare Source](https://github.com/nginx/docker-nginx/compare/1.31.7...1.31.8)

</details>

<details>
<summary>podman-container-tools/podman (quay.io/containers/podman)</summary>

### [`v6.2.0`](https://github.com/podman-container-tools/podman/releases/tag/v6.2.0)

[Compare Source](https://github.com/podman-container-tools/podman/compare/v6.1.3...v6.2.0)

##### Security

- Addresses CVE-2026-121885, untrusted image labels could be used to trick podman auto-update into restarting incorrect systemd units [GHSA-55rm-rwr7-q2wr](https://github.com/podman-container-tools/podman/security/advisories/GHSA-55rm-rwr7-q2wr).
- Addresses CVE-2026-111361, malicious containers images could be able to bypass Digest and Signature validation [GHSA-pggw-qqjf-6cxw](https://github.com/podman-container-tools/container-libs/security/advisories/GHSA-pggw-qqjf-6cxw).
- Addresses CVE-2026-123876, default seccomp profile socket deny rule could be bypass by a malicious container.

##### Features

- The `podman push` command now supports a new option, `--platform`, which selects and pushes a single platform-specific manifest instead of the entire list.
- The `podman kube play` command now supports a new option, `--validate`, which determines how unrecognized YAML fields are handled ([#&#8203;18332](https://github.com/podman-container-tools/podman/issues/18332)).
- The `podman kube play` command now supports a new option, `--label`, to set labels on created containers, pods, volumes, and secrets ([#&#8203;26450](https://github.com/podman-container-tools/podman/issues/26450)).
- The `podman kube play` command can now create multiple pods if more than 1 replica is requested by a deployment using the new `--multiple-pods` option ([#&#8203;26769](https://github.com/podman-container-tools/podman/issues/26769)).
- The `podman kube play --build` command now supports building images from subdirectories of the main context directory ([#&#8203;28148](https://github.com/podman-container-tools/podman/issues/28418)).
- Quadlet `.container` files now support a new key, `Umask`, to set the default umask for the created container ([#&#8203;25278](https://github.com/podman-container-tools/podman/issues/25278)).
- All Quadlet files now support a new key, `SetMountsDependency`, configuring whether the generated unit will use `RequiresMountsFor`, `WantsMountsFor`, or no dependency at all on required source paths ([#&#8203;29946](https://github.com/podman-container-tools/podman/issues/29946)).
- The `podman farm list` command now supports two new options, `--quiet`, which will print only the names of active farms, and `--noheading`, which omits column headers from the output.
- The `podman artifact ls` command now supports two new options, `--format=json`, which will output machine-readable JSON, and `--quiet`, which prints only artifact digests.
- The `podman create` command now supports a new option, `--passwd`, to add entries to `/etc/passwd` in the container (this has previously been available with `podman run`).
- The `podman info` command now includes detailed information on the features supported by OCI runtimes.
- The `podman events --filter` command now supports a new filter, `network=`, to filter to events pertaining to a specific network ([#&#8203;29387](https://github.com/podman-container-tools/podman/issues/29387)).
- The `podman auto-update` command has been enabled on the remote Podman client.
- The `StartInterval` field in image healthcheck configuration is now respected, allowing images to configure startup healthchecks ([#&#8203;27724](https://github.com/podman-container-tools/podman/issues/27724)).
- The `podman image scp` command now supports two new options, `--compression-format` and `--compression-level`, to compress data during transfer ([#&#8203;23192](https://github.com/podman-container-tools/podman/issues/23192)).
- The `podman auto-update` command now supports a new option, `--filter`, to selectively update only containers that match the given filters.
- The `podman ps --sort` command now allows sorting by pod.
- The `podman ps --filter` command now supports a new filter, `status!`, which matches containers not in the given state ([#&#8203;21398](https://github.com/podman-container-tools/podman/issues/21398)).

##### Changes

- Podman now requires Go v1.26 or higher to build.
- The Podman machine WSL provider now has native systemd support, existing machines continue to be supported for now with our old custom systemd setup. We require at least WSL version 2.5.1 now, although we recommend using at least 2.7.5 for proper nftables networking support.
- The `podman kube play` command now uses the `securityContext.seccompProfile` fields in Kubernetes YAML for Seccomp configuration. Support for the existing annotation-based configuration of Seccomp is now deprecated, and will be removed with Podman 7.0.
- The `podman inspect` command on containers now includes three new fields, `DNSNames` (containing all names the container can be accessed via), `IsInitCtr` (whether the container is an init container), and `InitContainerType` (what type of init container this is, if it is one) ([#&#8203;29811](https://github.com/podman-container-tools/podman/issues/29811)).
- The `podman inspect` command on containers now only includes user-added DNS aliases in the `Aliases` field, which previously displayed all DNS aliases, improving Docker compatibility.
- The `podman inspect` command on containers now properly populates the `ConsoleSize` field for running containers ([#&#8203;28368](https://github.com/podman-container-tools/podman/issues/28368)).
- Systemd units created by Podman healthchecks are now named much more clearly (`libpod-healthcheck-$CONTAINERID-$randsuffix.service`) ([#&#8203;29373](https://github.com/podman-container-tools/podman/issues/29373)).
- Signal proxying is now enabled for attached `podman exec` commands. As such, killing a `podman exec` command with Control-C or similar should now also kill the processes started in the container (similar to how `podman run` already works) ([#&#8203;19486](https://github.com/podman-container-tools/podman/issues/19486)).
- The deprecated `--cpu-rt-period` and `--cpu-rt-runtime` options for `podman create`, `podman run`, `podman update`, and `podman container clone` are now hidden and undocumented. They have not been functional since the removal of cgroups v1 support and will be removed entirely in Podman v7.
- The `--health-startup-interval` option to `podman create`, `podman run`, and `podman update` has a new alias, `--health-start-interval`.
- When a startup healthcheck interval is specified, but no startup healthcheck command, the standard healthcheck command will be used instead.
- When using the `journald` event driver, timestamps are no longer included in logged events, as `journald` includes a timestamp already ([#&#8203;29835](https://github.com/podman-container-tools/podman/issues/29835)).
- Quadlet can now create template instances from instance-specific drop-in directories without requiring an explicit instance file or symlink ([#&#8203;27636](https://github.com/podman-container-tools/podman/issues/27636)).

##### Bugfixes

- Fixed a bug where passing an empty file to the `--ignorefile` option to `podman build` would cause the `.dockerignore` or `.containerignore` file in the context directory to be used, instead of not using an ignorefile at all ([#&#8203;25147](https://github.com/podman-container-tools/podman/issues/25147)).
- Fixed a bug where the `Pod=` key in Quadlet `.container` files did not expand the `%N` specifier ([#&#8203;29108](https://github.com/podman-container-tools/podman/issues/29108)).
- Fixed a bug where containers created with `--userns=auto` would report having a `private` user namespace in `podman inspect` after they started, but not when they were first created.
- Fixed a bug where logging was configured too late in the Podman init process to print errors from parsing configuration files ([#&#8203;25362](https://github.com/podman-container-tools/podman/issues/25362)).
- Fixed a bug where the `podman system prune --build` command could fail if a build container was removed while it was running.
- Fixed a bug where `copy` events from `podman machine cp` were not properly displayed by the remote Podman client.
- Fixed a bug where the `podman farm build --tag` command would fail if given a tag including a colon ([#&#8203;25039](https://github.com/podman-container-tools/podman/issues/25039)).
- Fixed a bug where the `podman machine init --image` command would fail when given a read-only disk image.
- Fixed a bug where the `podman machine start` and `podman machine init --now` commands could hang on Windows systems using the Hyper-V provider if the VM failed to start ([#&#8203;29455](https://github.com/podman-container-tools/podman/issues/29455)).
- Fixed a bug where the `podman machine start` command on Windows (both Hyper-V and WSL providers) would sometimes fail due to leftover processes from previous machines ([#&#8203;29474](https://github.com/podman-container-tools/podman/issues/29474)).
- Fixed a bug where the `podman machine start` command could hang indefinitely if the VM failed to start properly ([#&#8203;29880](https://github.com/podman-container-tools/podman/issues/29880)).
- Fixed a bug where the `podman machine start` command could create a VM that cannot be connected to on Windows if the host was shut down or restarted when the VM was running ([#&#8203;29971](https://github.com/podman-container-tools/podman/issues/29971)).
- Fixed a bug where the `podman machine init` command on Windows when using the Hyper-V provider did not correctly detach the file server process, causing VMs to lose access to host shares when the console that ran `podman machine init` closed ([#&#8203;29573](http://github.com/podman-container-tools/podman/issues/29573)).
- Fixed a bug where the `podman kube play` command incorrectly handled `emptyDir` volumes with `medium: Memory`, causing them to not be shared between containers in the pod and to ignore the `sizeLimit` parameter ([#&#8203;29555](https://github.com/podman-container-tools/podman/issues/29555)).
- Fixed a bug where the remote Podman client's `podman kube play` command incorrectly handled authentication credentials in API requests.
- Fixed a bug where volumes created by the `podman volume import` command would not adjust their permissions on being mounted into a container ([#&#8203;25442](https://github.com/podman-container-tools/podman/issues/25442)).
- Fixed a bug where the `podman build` command could leak temporary directories if a build failed ([#&#8203;22642](https://github.com/podman-container-tools/podman/issues/22642)).
- Fixed a bug where containers created with `--userns=keep-id` would use an image-specified user instead of forcing the same UID/GID in use on the host ([#&#8203;29600](https://github.com/podman-container-tools/podman/issues/29600)).
- Fixed a bug where the remote Podman client could not function when connecting over SSH to a server which does not support the direct-streamlocal channel type ([#&#8203;27814](https://github.com/podman-container-tools/podman/issues/27814)).
- Fixed a bug where the remote Podman client's `podman push`, `podman artifact push`, and `podman manifest push` commands would push an unsigned image instead of failing when the `--sign-by` or `--sign-by-sigstore-private-key` options were used.
- Fixed a bug where creating a container with `--userns=auto` that had overlay volume mounts would fail ([#&#8203;28758](https://github.com/podman-container-tools/podman/issues/28758)).
- Fixed a bug where volume subpaths including a `=` character in the path were handled incorrectly.
- Fixed a bug where the remote Podman client was unable to add subjects to artifacts with the `podman manifest annotate --subject` and `podman manifest add --artifact subject` commands.
- Fixed a bug where the remote Podman client's `podman manifest add --artifact` command could hang under some circumstances.
- Fixed a bug where the `podman manifest annotate --os-features` command did not properly save the OS features in the manifest.
- Fixed a bug where the remote Podman client's `podman image prune --filter` did not correctly handle filters with values including the `=` character.
- Fixed a bug where Quadlet `.volume` units did not recreate the volume if it was removed in Podman ([#&#8203;27862](https://github.com/podman-container-tools/podman/issues/27862)).
- Fixed a bug where containers with a failing startup healthcheck would not immediately transition to unhealthy when the startup period ended.
- Fixed a bug where containers started with `--sdnotify=healthy` and a `HealthStartPeriod` longer than the unit's `TimeoutStartSec` could be automatically killed by systemd if the healthcheck took an extended period to become healthy ([#&#8203;27290](https://github.com/podman-container-tools/podman/issues/27290)).
- Fixed a bug where the `--pids-limit=0` argument to `podman run` and `podman create` was incorrectly setting a process limit, instead of removing the limit, when the `runc` OCI runtime was in use ([#&#8203;29826](https://github.com/podman-container-tools/podman/issues/29826)).
- Fixed a bug where Quadlet did not search the parent directory of symlinked unit files for drop-in configuration files, which broke using Quadlets defined by root as a rootless user if drop-in overrides were in use ([#&#8203;29821](https://github.com/podman-container-tools/podman/issues/29821)).
- Fixed a bug where the `podman ps` and `podman pod ps` commands would fail when the `--format` argument was used with a format string including `.Label` ([#&#8203;29831](https://github.com/podman-container-tools/podman/issues/29831)).
- Fixed a bug where the `podman cp` command did not respect volume subpaths when copying into a mounted named or image volumes in a container that is not running ([#&#8203;29840](https://github.com/podman-container-tools/podman/issues/29840) and [#&#8203;29857](https://github.com/podman-container-tools/podman/issues/29857)).
- Fixed a bug where volume plugins were initialized when they were not required, which could cause early-boot containers started by Quadlet to error on missing plugins that the container was not actually using ([#&#8203;28110](https://github.com/podman-container-tools/podman/issues/28110)).
- Fixed a bug where the `podman export` command, when run by a rootless user on a container created with `--userns=keep-id`, would create an archive with incorrect UIDs and GIDs ([#&#8203;29856](https://github.com/podman-container-tools/podman/issues/29856)).
- Fixed a bug where the `podman system service` command would fail to start when run as a systemd unit and autostarted at the same time as other Podman units ([#&#8203;29964](https://github.com/podman-container-tools/podman/issues/29964)).
- Fixed a bug where the `podman events` command would return incomplete output when using the `file` events backend and `--until` specified with a time in the past ([#&#8203;29579](https://github.com/podman-container-tools/podman/issues/29579)).
- Fixed a bug where the `podman update` command allowed setting a startup healthcheck on a container without a normal healthcheck.
- Fixed a bug where the remote Podman client's `podman secret rm` command would fail when given an ambiguous name that could match multiple possible secrets.
- Fixed a bug where the `podman machine info` command would report the default VM type and config/image directories, not those used by the current machine.
- Fixed a bug where the `podman inspect` command on containers did not include `CheckpointLog` after a failed container checkpoint ([#&#8203;25154](https://github.com/podman-container-tools/podman/issues/25154)).

##### API

- The Libpod API now features a new endpoint, `POST /libpod/autoupdate`, which automatically updates containers with the `io.containers.autoupdate` label.
- The Compat API now features a new endpoint, `GET /distribution/{name}/json`, which inspects an image on a registry ([#&#8203;17726](https://github.com/podman-container-tools/podman/issues/17726)).
- The Compat Create endpoint for Containers now supports a new field, `HostConfig.Mounts.TmpfsOptions.Options`, to set additional options for tmpfs mounts.
- The Compat Create endpoint for Containers now allows a full Seccomp profile to be passed in the `HostConfig.SecurityOpt` field (instead of a path to a file containing a profile), improving Docker compatibility ([#&#8203;27710](https://github.com/podman-container-tools/podman/issues/27710)).
- The Compat Push endpoint for Images now supports a new query parameter, `platform`, to push only a single platform-specific manifest instead of the entire list.
- The Compat Info endpoint now includes the status of active OCI runtimes.
- Fixed a bug where the Libpod Create endpoint for Containers required that the `auto` userns mode also specify full UID/GID mappings for the created container.
- Fixed a bug where the Compat Create endpoint for Containers would incorrectly adjust mode when setting tmpfs size.
- Fixed a bug where the Compat Create endpoint for Containers would incorrectly treat a healthcheck of `{}` as the user explicitly requesting no healthcheck, instead of using the image's healthcheck as Docker does ([#&#8203;29467](https://github.com/podman-container-tools/podman/issues/29467)).
- Fixed a bug where the Compat Inspect endpoint for Secrets allowed the `showsecret` query parameter, which should be restricted to Libpod API requests only ([#&#8203;29570](https://github.com/podman-container-tools/podman/issues/29570)).
- Fixed a bug where the Compat Inspect endpoint for Images included the `Created` field even when it was empty.
- Fixed a bug where the Compat List and Inspect endpoints for Networks did not include `IPRange` in the returned `IPAMConfig` ([#&#8203;28378](https://github.com/podman-container-tools/podman/issues/28378)).
- Fixed a bug where the Compat List endpoint for Containers would error when passed a filter including container statuses supported by Docker but not Podman (`dead` and `restarting`) ([#&#8203;28904](https://github.com/podman-container-tools/podman/issues/28904)).
- Fixed a bug where the Compat Stats endpoint for Containers could panic on containers with a memory reservation, but no memory limit, set ([#&#8203;29627](https://github.com/podman-container-tools/podman/issues/29627)).
- Fixed a bug where the Compat Stats endpoint for Containers incorrectly populated `system_cpu_usage` and `percpu_stats` when not streaming ([#&#8203;28761](https://github.com/podman-container-tools/podman/issues/28761), [#&#8203;24730](https://github.com/podman-container-tools/podman/issues/24730), [#&#8203;25709](https://github.com/podman-container-tools/podman/issues/25709), [#&#8203;29912](https://github.com/podman-container-tools/podman/issues/29912)).
- Fixed a bug where the Compat Info endpoint reported an incorrect cgroup manager when running rootless with the `cgroupfs` cgroup manager ([#&#8203;27824](https://github.com/podman-container-tools/podman/issues/27824)).
- Fixed a bug where the Compat and Libpod Attach endpoints for Containers would, when doing a logs-only (`stream=0` and `logs=1`) attach, incorrectly reinitialize the container, changing its exit code and status ([#&#8203;29664](https://github.com/podman-container-tools/podman/issues/29664)).
- Fixed a bug where the Compat and Libpod Update endpoints would incorrectly clear a container's restart policy when it was omitted from the request ([#&#8203;29790](https://github.com/podman-container-tools/podman/issues/29790)).
- Fixed a bug where the Compat and Libpod Start endpoints for Exec sessions would return an error when trying to start an exec session with no standard streams attached without specifying `Detach=true`.
- Fixed a bug where the Libpod Generate Kube endpoint returned the wrong content type ([#&#8203;29674](https://github.com/podman-container-tools/podman/issues/29674)).
- Numerous fixes to the API's Swagger documentation have been made to ensure it accurately documents the REST API.

##### Misc

- Fixed a number of low-level resource leaks in various parts of Podman.
- Waiting for `gvproxy` to start when starting a `podman machine` VM now uses a notification socket, instead of polling, improving reliability and startup time.
- Updated documentation for the `--image-volume` option to `podman create` and `podman run` to remove the deprecated `bind` option and add the new default, `anonymous`, which was not shown as a valid option. Using the deprecated `bind` option now prints a warning.
- Updated Buildah to v1.46.0
- Updated Common to v0.70.0
- Updated Image to v5.42.1
- Updated Storage to v1.64.2

</details>

---

### Configuration

📅 **Schedule**: (UTC)

- Branch creation
  - Between 12:00 AM and 03:59 AM, only on Monday (`* 0-3 * * 1`)
- Automerge
  - At any time (no schedule defined)

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

👻 **Immortal**: This PR will be recreated if closed unmerged. Get [config help](https://github.com/renovatebot/renovate/discussions) if that's undesired.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Mend Renovate CLI](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0NC4yMzkuMSIsInVwZGF0ZWRJblZlciI6IjQ0LjIzOS4xIiwidGFyZ2V0QnJhbmNoIjoibWFpbiIsImxhYmVscyI6W119-->

Reviewed-on: https://gitea.com/gitea/runner/pulls/1422
Reviewed-by: silverwind <2021+silverwind@noreply.gitea.com>
Co-authored-by: Renovate Bot <renovate-bot@gitea.com>
2026-11-23 15:28:38 +00:00
silverwind
1d6b45bb65 feat: add runner.action_replacements to rewrite step uses (#1417)
Adds `runner.action_replacements`, regex rules that rewrite the `uses` of steps before they run. This keeps commits with `uses: builtin:checkout` buildable after the builtin actions were removed, and also allows redirecting actions to a mirror. Each regex must match the whole `uses`, `${1}` refers to a group, and rules apply in order.

Refs: https://gitea.com/gitea/runner/pulls/1407#issuecomment-1869470

_Written by Claude (Opus 5.5)._
Reviewed-on: https://gitea.com/gitea/runner/pulls/1417
Reviewed-by: bircni <bircni@icloud.com>
Co-authored-by: silverwind <2021+silverwind@noreply.gitea.com>
2026-11-22 10:18:04 +00:00
silverwind
e71a5028b0 enhance: align job execution closer to GitHub Actions (#1421)
Closes many small gaps between how workflows run on GitHub and on the runner, each checked against GitHub's runner and live runs.

- `action.yml` expressions are checked against the contexts GitHub allows per field, and input defaults are evaluated with those contexts only
- Reusable workflows take inputs from `workflow_call` only, evaluate outputs once after all called jobs finish, stop at 10 nested workflows and resolve relative `./` paths in remote workflows against that workflow's repository
- A called job failing under `continue-on-error` no longer fails the caller, and same-repository calls use their own clone cache
- Job timeouts cancel the job with GitHub's message, step timeouts fail the step with GitHub's message, and invalid `timeout-minutes` values behave like on GitHub
- `runner.timeout` expiry names the setting and server cancellation is logged
- Matrix and strategy evaluation errors fail the job
- `exec` records skipped jobs and sets `github.run_attempt`, `workflow_ref` and `workflow_sha`
- `runs-on` expressions keep their types
- Step summaries upload as each step ends
- Docker actions join the job network, and the job container no longer gets a network alias from the job name
- Container, network and volume names are unique per job invocation
- Cached images are matched against the daemon's platform and Dockerfile actions build for the requested platform
- `runner.arch` maps 32-bit ARM and x86 names like GitHub
- Pinned action SHAs are verified and git replace objects are ignored
- `hashFiles` uses GitHub's current bundle
- Registration trims labels and writes `.runner` as `0600`
- The container entrypoint quotes its arguments and reads the registration token from the environment or a file
- The systemd example uses `KillMode=mixed` so running jobs can finish on stop
- The cache server releases its database between eviction batches
- Shared rules come from actionslib v1.7.0, added in https://gitea.com/gitea/actionslib/pulls/34

_Written by Claude (Opus 5.5)._

Reviewed-on: https://gitea.com/gitea/runner/pulls/1421
Reviewed-by: bircni <bircni@icloud.com>
Co-authored-by: silverwind <me@silverwind.io>
2026-11-22 10:11:23 +00:00
90 changed files with 4245 additions and 3560 deletions

View File

@@ -4,7 +4,7 @@ description: Set up go and restore its caches, which only the cache-seeder workf
runs:
using: composite
steps:
- uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7
- uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7
id: setup-go
with:
go-version-file: go.mod

View File

@@ -30,7 +30,7 @@ jobs:
R2_BUCKET: ${{ secrets.R2_BUCKET }}
R2_ACCESS_KEY_ID: ${{ secrets.R2_ACCESS_KEY_ID }}
R2_SECRET_ACCESS_KEY: ${{ secrets.R2_SECRET_ACCESS_KEY }}
- uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7
- uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7
with:
go-version-file: "go.mod"
check-latest: true

View File

@@ -23,7 +23,7 @@ jobs:
R2_BUCKET: ${{ secrets.R2_BUCKET }}
R2_ACCESS_KEY_ID: ${{ secrets.R2_ACCESS_KEY_ID }}
R2_SECRET_ACCESS_KEY: ${{ secrets.R2_SECRET_ACCESS_KEY }}
- uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7
- uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7
with:
go-version-file: "go.mod"
check-latest: true

View File

@@ -25,7 +25,7 @@ jobs:
# daemon retains them between runs, and their digest pins skip the registry when it has them.
- name: pre-pull test images
env:
TEST_JOB_IMAGE: node:26-bookworm-slim@sha256:bc0a2afd3b74ce12222fc8bab99271e66257f021078f5f4a5d687a77d280c1d9 # renovate: datasource=docker
TEST_JOB_IMAGE: node:26-bookworm-slim@sha256:5df79989ed685e09f0a98019db4cebfb22fb9df1a53c0161664a011f7ff6b0f1 # renovate: datasource=docker
TEST_SERVICE_IMAGE: nginx:alpine@sha256:a3554c0d0b48177b1413c26e01f695334428020d9df01243fbae3e11cfd17417 # renovate: datasource=docker
run: |
for image in "$TEST_JOB_IMAGE" "$TEST_SERVICE_IMAGE"; do

View File

@@ -19,7 +19,7 @@ RUN --mount=type=cache,target=/go/pkg/mod \
### DIND VARIANT
#
#
FROM docker:29.9.3-dind AS dind
FROM docker:29.10.0-dind AS dind
ARG VERSION=dev
@@ -42,7 +42,7 @@ ENTRYPOINT ["s6-svscan","/etc/s6"]
### DIND-ROOTLESS VARIANT
#
#
FROM docker:29.9.3-dind-rootless AS dind-rootless
FROM docker:29.10.0-dind-rootless AS dind-rootless
ARG VERSION=dev

View File

@@ -3,9 +3,9 @@ GO ?= go
EXECUTABLE := gitea-runner$(shell $(GO) env GOEXE)
HAS_GO = $(shell hash $(GO) > /dev/null 2>&1 && echo "GO" || echo "NOGO" )
PODMAN_TEST_IMAGE ?= quay.io/containers/podman:v6.1.3-immutable@sha256:1d844fd1fc6ce68c1e72ae19550cc3caef039306219ee007d88f7e67c5df4dd1 # renovate: datasource=docker
E2E_JOB_IMAGE ?= docker.gitea.com/runner-images:ubuntu-latest@sha256:139605d4a6ab61e48dfd7687b11184881c2d7fcf06bf739e9cadb34f73deb51d # renovate: datasource=docker
SERVICE_IMAGE ?= nginx:1.31.7-alpine@sha256:892bb2152464f0c5d8972593a5f5afaf8054552580b699d95f8ff4af08c2d33d # renovate: datasource=docker
PODMAN_TEST_IMAGE ?= quay.io/containers/podman:v6.2.0-immutable@sha256:a80e41e595d1abe8eed2cf3f00d0e82612493d0b24b68ef7b04b4255f56816be # renovate: datasource=docker
E2E_JOB_IMAGE ?= docker.gitea.com/runner-images:ubuntu-latest@sha256:433d703e6214e93234583ecc9cbec0b30fb5691259b0581597aaede21b031f8b # renovate: datasource=docker
SERVICE_IMAGE ?= nginx:1.31.8-alpine@sha256:fed7e14be83cbd2661a75cdc5b872d936cf155d46c327084d30b8df19ae88d72 # renovate: datasource=docker
E2E_GITEA_IMAGE ?= gitea/gitea:main-nightly
E2E_K3S_IMAGE ?= rancher/k3s:v1.37.2-k3s1@sha256:21ea6e0fac4e3930c2ce8aa40ddd41a8b18cb3e9a0222c030dc005e7e88c4332 # renovate: datasource=docker
WINDOWS_TEST_IMAGE ?= dockurr/windows:6.06@sha256:16fd7c39a3e48bb946d29c59dc6015942e5b900a1fa5d7e5552053bfc48ee2ea # renovate: datasource=docker
@@ -17,7 +17,7 @@ DOCKER_TAG ?= nightly
DOCKER_REF := $(DOCKER_IMAGE):$(DOCKER_TAG)
GOLANGCI_LINT_PACKAGE ?= github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.15.0 # renovate: datasource=go
GOVULNCHECK_PACKAGE ?= golang.org/x/vuln/cmd/govulncheck@v1.9.0 # renovate: datasource=go
GOVULNCHECK_PACKAGE ?= golang.org/x/vuln/cmd/govulncheck@v1.10.0 # renovate: datasource=go
GOTEST_FLAGS ?= -race -timeout 20m -parallel 8

View File

@@ -14,7 +14,6 @@ Gitea Runner runs the jobs of Gitea Actions workflows. Register it with a Gitea
In the job image, or on the host for host jobs:
- `bash` or `sh`, or `pwsh` or `powershell` on Windows.
- `node` for JavaScript actions and `hashFiles()`.
Kubernetes mode needs [a few more tools](docs/kubernetes.md) in job images.
@@ -304,10 +303,32 @@ Hook scripts run where the job's steps run, before the first step and after the
Use them for per-job setup no workflow should carry, like registry logins or masking runner-wide secrets. They block the job, and a non-zero exit fails it. See [docs/job-hooks.md](docs/job-hooks.md).
### Action replacements (`runner.action_replacements`)
Rewrite the `uses` of steps before they run, for example to keep old commits using `builtin:checkout` buildable, or to fetch actions from a mirror:
```yaml
runner:
action_replacements:
- regex: 'builtin:checkout'
replacement: actions/checkout@v6
- regex: '(?:https://github\.com/)?actions/(.+)'
replacement: https://git.example.com/mirror/${1}
```
A regex must match the whole `uses`, and the replacement can insert its capture groups as `${1}`, `${2}` and so on. Entries apply in order, each to the result of the previous one. Steps inside composite actions are rewritten too.
### Secret masking
Secrets and `::add-mask::` values are hidden in job logs, [local job logs](#local-job-logs-logjobdir), job summaries and container names. As on GitHub, a job output containing one is dropped with a warning.
### Node.js
JavaScript actions and `hashFiles()` run on either:
- Node.js 24, downloaded by the runner from nodejs.org (or `NODEJS_ORG_MIRROR`), and from GitHub for Alpine. `runner.node_version` can be used to use a different version. If the download fails or doesn't run in the job's image, the `node` on `PATH` is used.
- The `node` on `PATH`, with `runner.node_download: false`.
## Operation
### Idle cleanup

View File

@@ -725,7 +725,7 @@ func (h *Handler) lookupCache(db *cacheDB, cred JobCredential, keys []string, ve
h.touch(db, cache)
return cache, nil
}
if !h.deleteCache(db, cache) {
if !h.removeBlob(cache) || !h.deleteEntries(db, cache) {
return nil, nil //nolint:nilnil // absence is not an error here
}
}
@@ -900,16 +900,12 @@ func (h *Handler) commitCache(cache *Cache) error {
if err != nil {
return err
}
defer db.Close()
if err := db.save(cache); err != nil {
return err
err = db.save(cache)
db.Close()
if err == nil && h.s3 == nil { // lifecycle rules on the bucket bound its size
h.evictOversized(&cache.Repo)
}
if h.s3 != nil {
return nil // lifecycle rules on the bucket bound its size
}
h.evictRepo(db, cache.Repo)
h.evictTotal(db)
return nil
return err
}
// GET /_apis/artifactcache/artifacts/:id
@@ -1243,6 +1239,7 @@ const (
miB = 1024 * 1024
defaultSweepInterval = time.Hour
evictionBatchSize = 8
touchStale = time.Minute // how stale a completed entry's UsedAt may get before an access rewrites it, sparing hits the fsync
@@ -1298,144 +1295,163 @@ func (h *Handler) gcCache() {
if err != nil {
return
}
defer db.Close()
if err := db.dropLegacyIndexes(); err != nil {
h.logger.Warnf("drop legacy indexes: %v", err)
}
h.evictIncomplete(db)
db.Close()
stalled := h.gcAt.Add(-uploadStallTimeout).Unix()
expired := h.gcAt.Add(-max(h.policy.Retention+touchStale, inUseGrace)).Unix() // never below inUseGrace, or a short retention would outrun a signed URL already issued
h.evictBatches(func(batch *evictionBatch) {
for _, cache := range h.caches(batch.db, func(cache *Cache) bool {
return !cache.Complete && cache.UsedAt < stalled ||
h.s3 == nil && h.policy.Retention > 0 && cache.UsedAt < expired
}) {
h.deleteCache(batch, cache)
}
})
if h.s3 != nil {
return // lifecycle rules on the bucket expire its entries
}
h.evictExpired(db)
h.evictSuperseded(db)
h.evictOversized(db)
_ = db.Close()
h.evictBatches(h.evictSuperseded)
h.evictOversized(nil)
h.makeRoom(0)
}
type evictionBatch struct {
db *cacheDB
failed map[uint64]bool
removed []*Cache
candidates int
}
func (h *Handler) evictBatches(evict func(*evictionBatch)) {
failed := make(map[uint64]bool)
for {
db, err := h.openDB()
if err != nil {
return
}
batch := evictionBatch{db: db, failed: failed}
evict(&batch)
deleted := len(batch.removed) == 0 || h.deleteEntries(db, batch.removed...)
db.Close()
if !deleted || batch.candidates <= evictionBatchSize {
return
}
}
}
func (h *Handler) deleteCache(batch *evictionBatch, cache *Cache) bool {
if batch.failed[cache.ID] {
return false
}
batch.candidates++
if batch.candidates > evictionBatchSize {
return false
}
if !h.removeBlob(cache) {
batch.failed[cache.ID] = true
return false
}
batch.removed = append(batch.removed, cache)
return true
}
func (h *Handler) diskShortfall(need int64) int64 {
free, err := h.freeDisk(h.dir)
if err != nil {
h.logger.Debugf("free disk check: %v", err) // unsupported platform, treat as unavailable rather than full
return 0
}
return max(h.policy.MinFreeDisk+max(need, 0)-int64(free), 0)
}
// makeRoom evicts the least recently used entries to keep need bytes above the floor, as GitHub saves new over old.
func (h *Handler) makeRoom(need int64) {
free, err := h.freeDisk(h.dir)
if err != nil {
h.logger.Debugf("free disk check: %v", err) // unsupported platform, treat as unavailable rather than full
if h.s3 != nil || h.diskShortfall(need) == 0 {
return
}
shortfall := h.policy.MinFreeDisk + max(need, 0) - int64(free)
if h.s3 != nil || shortfall <= 0 {
return
}
db, err := h.openDB()
if err != nil {
return
}
defer db.Close()
caches := h.completedByUse(db)
total := totalSize(caches)
if total <= shortfall {
// Say so, or shedding everything and still being short reads as the backstop working.
h.logger.Warnf("cache volume is %d MiB short of the free space floor with only %d MiB of cache on it; something else is filling it", shortfall/miB, total/miB)
}
h.evictTo(db, caches, total-shortfall, "the cache volume")
}
// evictIncomplete removes uploads that stopped part way, which are most likely broken.
func (h *Handler) evictIncomplete(db *cacheDB) {
stalled := time.Now().Add(-uploadStallTimeout).Unix()
h.sweep(db, func(cache *Cache) bool { return cache.UsedAt < stalled && !cache.Complete })
}
func (h *Handler) evictExpired(db *cacheDB) {
if h.policy.Retention <= 0 {
return
}
// Never below inUseGrace, or a short retention would outrun a signed URL already issued.
expired := time.Now().Add(-max(h.policy.Retention+touchStale, inUseGrace)).Unix()
h.sweep(db, func(cache *Cache) bool { return cache.UsedAt < expired })
h.evictBatches(func(batch *evictionBatch) {
shortfall := h.diskShortfall(need)
if shortfall == 0 {
return
}
caches := h.cachesByUse(batch.db, func(cache *Cache) bool { return cache.Complete })
total := totalSize(caches)
if total <= shortfall { // say so, or shedding everything and still being short reads as the backstop working
h.logger.Warnf("cache volume is %d MiB short of the free space floor with only %d MiB of cache on it. Something else is filling it", shortfall/miB, total/miB)
}
h.evictTo(batch, caches, total-shortfall, "the cache volume")
})
}
// evictSuperseded removes entries a newer one with the same repo, ref, key and version replaced.
func (h *Handler) evictSuperseded(db *cacheDB) {
func (h *Handler) evictSuperseded(batch *evictionBatch) {
type entry struct{ repo, ref, key, version string }
groups := make(map[entry][]*Cache)
for _, cache := range h.caches(db, func(cache *Cache) bool { return cache.Complete }) {
for _, cache := range h.caches(batch.db, func(cache *Cache) bool { return cache.Complete }) {
group := entry{cache.Repo, cache.Ref, cache.Key, cache.Version}
groups[group] = append(groups[group], cache)
}
for _, caches := range groups {
slices.SortFunc(caches, func(left, right *Cache) int {
return cmp.Or(cmp.Compare(left.createdAtNano(), right.createdAtNano()), cmp.Compare(left.ID, right.ID))
})
for _, cache := range caches[:len(caches)-1] {
if inUse(cache) {
continue
newest := latest(caches, (*Cache).createdAtNano)
for _, cache := range caches {
if cache != newest && !inUse(cache) {
h.deleteCache(batch, cache)
}
h.deleteCache(db, cache)
}
}
}
// evictOversized applies the per-repository limit, then the whole-store one. Only completed
// entries count, since only those carry a size measured at commit rather than claimed.
func (h *Handler) evictOversized(db *cacheDB) {
if h.policy.RepoSizeLimit > 0 {
byRepo := make(map[string][]*Cache)
for _, cache := range h.completedByUse(db) {
byRepo[cache.Repo] = append(byRepo[cache.Repo], cache)
}
for repo, caches := range byRepo {
h.evictTo(db, caches, h.policy.RepoSizeLimit, "repository "+repo)
}
}
h.evictTotal(db)
}
// evictTotal caps the store as a whole. It re-queries because the per-repo pass may have
// deleted rows an earlier result still holds.
func (h *Handler) evictTotal(db *cacheDB) {
if h.policy.SizeLimit <= 0 {
func (h *Handler) evictOversized(repo *string) {
if h.policy.RepoSizeLimit <= 0 && h.policy.SizeLimit <= 0 {
return
}
h.evictTo(db, h.completedByUse(db), h.policy.SizeLimit, "the cache")
}
// evictRepo reclaims space when a commit pushes a repo over, rather than at the next sweep.
func (h *Handler) evictRepo(db *cacheDB, repo string) {
if h.policy.RepoSizeLimit <= 0 {
return
}
h.evictTo(db, h.cachesByUse(db, func(cache *Cache) bool { return cache.Repo == repo && cache.Complete }), h.policy.RepoSizeLimit, "repository "+repo)
h.evictBatches(func(batch *evictionBatch) {
caches := h.cachesByUse(batch.db, func(cache *Cache) bool { return cache.Complete })
overTotal := h.policy.SizeLimit > 0 && totalSize(caches) > h.policy.SizeLimit
if h.policy.RepoSizeLimit > 0 {
byRepo := make(map[string][]*Cache)
for _, cache := range caches {
if overTotal || repo == nil || cache.Repo == *repo {
byRepo[cache.Repo] = append(byRepo[cache.Repo], cache)
}
}
for repo, caches := range byRepo {
h.evictTo(batch, caches, h.policy.RepoSizeLimit, "repository "+repo)
}
}
if overTotal {
caches = slices.DeleteFunc(caches, func(cache *Cache) bool { return slices.Contains(batch.removed, cache) })
h.evictTo(batch, caches, h.policy.SizeLimit, "the cache")
}
})
}
// evictTo deletes until caches fit limit. caches must be ordered by UsedAt ascending.
func (h *Handler) evictTo(db *cacheDB, caches []*Cache, limit int64, scope string) {
func (h *Handler) evictTo(batch *evictionBatch, caches []*Cache, limit int64, scope string) {
// An entry bigger than the limit never fits, so it goes on its own account instead of
// dragging every neighbour out first and then following them next sweep.
fits := caches[:0]
var total int64
for _, cache := range caches {
if cache.Size <= limit {
fits = append(fits, cache)
continue
}
if !inUse(cache) {
total += cache.Size
} else if !inUse(cache) && h.deleteCache(batch, cache) {
h.logger.Warnf("cache %q is %d MiB on its own, over the limit for %s; dropping it", cache.Key, cache.Size/miB, scope)
h.deleteCache(db, cache)
}
}
caches = fits
total := totalSize(caches)
var freed int64
for _, cache := range caches {
if total <= limit {
if total-freed <= limit {
break
}
if inUse(cache) || !h.deleteCache(db, cache) {
continue
if cache.Size <= limit && !inUse(cache) && h.deleteCache(batch, cache) {
freed += cache.Size
}
total -= cache.Size
freed += cache.Size
}
if freed > 0 {
h.logger.Warnf("evicted %d MiB from %s, least recently used first", freed/miB, scope)
@@ -1466,12 +1482,6 @@ func (h *Handler) touch(db *cacheDB, cache *Cache) {
}
}
func (h *Handler) sweep(db *cacheDB, match func(*Cache) bool) {
for _, cache := range h.caches(db, match) {
h.deleteCache(db, cache)
}
}
func (h *Handler) caches(db *cacheDB, match func(*Cache) bool) []*Cache {
caches, err := db.find(match)
if err != nil {
@@ -1486,11 +1496,6 @@ func (h *Handler) cachesByUse(db *cacheDB, match func(*Cache) bool) []*Cache {
return caches
}
// completedByUse returns every entry the size limits count, least recently accessed first.
func (h *Handler) completedByUse(db *cacheDB) []*Cache {
return h.cachesByUse(db, func(cache *Cache) bool { return cache.Complete })
}
func totalSize(caches []*Cache) int64 {
var total int64
for _, cache := range caches {
@@ -1499,9 +1504,7 @@ func totalSize(caches []*Cache) int64 {
return total
}
// deleteCache drops an entry and its bytes, reporting whether it went fully. The blob goes
// first, so a failed unlink leaves the row for the next sweep instead of orphaning bytes.
func (h *Handler) deleteCache(db *cacheDB, cache *Cache) bool {
func (h *Handler) removeBlob(cache *Cache) bool {
storage := h.storage
if h.s3 != nil && !cache.Complete {
storage = h.s3.Storage // an upload not yet committed has nothing in the bucket
@@ -1510,11 +1513,24 @@ func (h *Handler) deleteCache(db *cacheDB, cache *Cache) bool {
h.logger.Warnf("remove cache blob: %v", err)
return false
}
if err := db.update(func(bucket *bbolt.Bucket) error { return db.delete(bucket, cache.ID) }); err != nil {
return true
}
func (h *Handler) deleteEntries(db *cacheDB, caches ...*Cache) bool {
if err := db.update(func(bucket *bbolt.Bucket) error {
for _, cache := range caches {
if err := db.delete(bucket, cache.ID); err != nil {
return err
}
}
return nil
}); err != nil {
h.logger.Warnf("delete cache: %v", err)
return false
}
h.logger.Infof("deleted cache: %+v", cache)
for _, cache := range caches {
h.logger.Infof("deleted cache: %+v", cache)
}
return true
}

View File

@@ -731,40 +731,61 @@ func TestHandler_makeRoom(t *testing.T) {
}
}
func TestHandler_SweepKeepsEntryWhenBlobSurvives(t *testing.T) {
func TestHandler_SweepKeepsEntriesWhenBlobsSurviveAcrossBatches(t *testing.T) {
t.Parallel()
cache := &Cache{Key: "stuck", Complete: true, UsedAt: time.Now().Add(-(testRetention + time.Hour)).Unix()}
handler := newTestHandler(t, Policy{Retention: testRetention}, cache)
blob := handler.storage.(*Storage).filename(cache.ID)
require.NoError(t, os.MkdirAll(blob, 0o755))
require.NoError(t, os.WriteFile(filepath.Join(blob, "held"), []byte("x"), 0o600))
var caches []*Cache
for range evictionBatchSize + 1 {
caches = append(caches, &Cache{Key: "stuck", Complete: true, UsedAt: time.Now().Add(-(testRetention + time.Hour)).Unix()})
}
handler := newTestHandler(t, Policy{Retention: testRetention}, caches...)
for _, cache := range caches {
blob := handler.storage.(*Storage).filename(cache.ID)
require.NoError(t, os.MkdirAll(blob, 0o755))
require.NoError(t, os.WriteFile(filepath.Join(blob, "held"), []byte("x"), 0o600))
}
handler.gcAt = time.Time{}
handler.gcCache()
assert.Equal(t, []string{"stuck"}, keptKeys(t, handler, []*Cache{cache}), "the entry must outlive a blob that could not be removed")
assert.Len(t, keptKeys(t, handler, caches), len(caches), "an entry must outlive a blob that could not be removed")
}
func TestHandler_FindProtectsFromEviction(t *testing.T) {
func TestHandler_EvictionRechecksLookupsAndRepoLimitsBetweenBatches(t *testing.T) {
t.Parallel()
wanted := &Cache{Repo: testRepo, Key: "wanted", Version: "v", Complete: true, Size: 4 * miB, UsedAt: time.Now().Add(-3 * time.Hour).Unix()}
other := &Cache{Repo: testRepo, Key: "other", Version: "v", Complete: true, Size: 4 * miB, UsedAt: time.Now().Add(-2 * time.Hour).Unix()}
newest := &Cache{Repo: testRepo, Key: "newest", Version: "v", Complete: true, Size: 4 * miB, UsedAt: time.Now().Add(-time.Hour).Unix()}
handler := newTestHandler(t, Policy{RepoSizeLimit: 10 * miB}, wanted, other, newest)
writeBlob(t, handler, wanted.ID)
synctest.Test(t, func(t *testing.T) {
wanted := &Cache{Repo: testRepo, Key: "wanted", Complete: true, Size: 1, UsedAt: 1}
entries := []*Cache{
wanted,
{Key: "other", Complete: true, Size: 3, UsedAt: 2},
{Repo: "o/b", Key: "old", Complete: true, Size: 2, UsedAt: 3},
}
for range 8 {
entries = append(entries, &Cache{Complete: true, Size: 1})
}
handler := newTestHandler(t, Policy{RepoSizeLimit: 3, SizeLimit: 5}, entries...)
require.NoError(t, handler.Close())
writeBlob(t, handler, wanted.ID)
resp, err := testClient.Get(fmt.Sprintf("%s%s/cache?keys=wanted&version=v", handler.ExternalURL(), apiPath))
require.NoError(t, err)
defer resp.Body.Close()
require.Equal(t, 200, resp.StatusCode)
locked, err := handler.openDB()
require.NoError(t, err)
go handler.evictOversized(&wanted.Repo)
synctest.Wait()
go func() {
synctest.Wait()
locked.Close()
}()
db, err := handler.openDB()
require.NoError(t, err)
handler.evictOversized(db)
require.NoError(t, db.Close())
db, err := handler.openDB()
require.NoError(t, err)
require.Len(t, handler.caches(db, func(*Cache) bool { return true }), 3)
_, err = handler.lookupCache(db, JobCredential{Repo: testRepo}, []string{"wanted"}, "")
require.NoError(t, err)
require.NoError(t, handler.insertCache(db, &Cache{Repo: "o/b", Complete: true, Size: 2, UsedAt: time.Now().Unix()}))
require.NoError(t, db.Close())
synctest.Wait()
assert.Equal(t, []string{wanted.Key}, keptKeys(t, handler, []*Cache{wanted, other}), "the entry just promised to a job survives, the next least recently used goes instead")
assert.Equal(t, []string{"wanted"}, keptKeys(t, handler, entries))
})
}
func TestHandler_PrefixUsesNewestReservationWithinSecond(t *testing.T) {

View File

@@ -100,7 +100,7 @@ func fetchAction(ctx context.Context, input NewGitCloneExecutorInput) (string, s
data, _ := os.ReadFile(record)
sha, etag, _ := strings.Cut(string(data), "\n")
switch {
case !isFullObjectID(sha):
case !isFullObjectID(sha) || verifyPin(ctx, filepath.Join(input.Dir, "git"), input.Ref, sha) != nil:
sha, etag = "", ""
case input.OfflineMode && exists(tree(sha)) && !exists(tree(sha)+treeSizes):
return tree(sha), sha, nil // from an older runner, with no sizes to check, so offline mode uses it as before
@@ -114,7 +114,7 @@ func fetchAction(ctx context.Context, input NewGitCloneExecutorInput) (string, s
if err != nil && ctx.Err() == nil {
common.Logger(ctx).Debugf("Cloning %s@%s: %v", input.URL, input.Ref, err)
newEtag = ""
newSha, err = exportClone(ctx, input)
newSha, err = exportClone(ctx, input, err)
}
if err != nil {
return "", "", err
@@ -151,7 +151,7 @@ func downloadArchive(ctx context.Context, input NewGitCloneExecutorInput, sha, e
return nil
}}
for attempt := 1; ; attempt++ {
newSha, newEtag, retryAfter, err := downloadArchiveOnce(ctx, client, archive.String(), input.Token, sha, etag, input.Dir)
newSha, newEtag, retryAfter, err := downloadArchiveOnce(ctx, client, archive.String(), input, sha, etag)
if retryAfter == 0 || attempt == 3 || ctx.Err() != nil {
return newSha, newEtag, err
}
@@ -164,7 +164,7 @@ func downloadArchive(ctx context.Context, input NewGitCloneExecutorInput, sha, e
}
}
func downloadArchiveOnce(ctx context.Context, client *http.Client, archive, token, sha, etag, dir string) (string, string, time.Duration, error) {
func downloadArchiveOnce(ctx context.Context, client *http.Client, archive string, input NewGitCloneExecutorInput, sha, etag string) (string, string, time.Duration, error) {
request, err := http.NewRequestWithContext(ctx, http.MethodGet, archive, nil)
if err != nil {
return "", "", 0, err
@@ -172,8 +172,8 @@ func downloadArchiveOnce(ctx context.Context, client *http.Client, archive, toke
if etag != "" {
request.Header.Set("If-None-Match", etag)
}
if token != "" {
request.SetBasicAuth("token", token)
if input.Token != "" {
request.SetBasicAuth("token", input.Token)
}
response, err := client.Do(request)
if err != nil {
@@ -191,7 +191,7 @@ func downloadArchiveOnce(ctx context.Context, client *http.Client, archive, toke
newEtag := response.Header.Get("ETag")
gz, err := gzip.NewReader(response.Body)
if err == nil {
sha, err = extractTree(ctx, gz, dir, !strings.HasSuffix(newEtag, `-false"`)) // Gitea's mark of an unprefixed archive
sha, err = extractTree(ctx, gz, input.Dir, input.Ref, !strings.HasSuffix(newEtag, `-false"`)) // Gitea's mark of an unprefixed archive
}
var netErr net.Error
if errors.Is(err, io.ErrUnexpectedEOF) || errors.As(err, &netErr) {
@@ -205,10 +205,13 @@ func downloadArchiveOnce(ctx context.Context, client *http.Client, archive, toke
}
}
func exportClone(ctx context.Context, input NewGitCloneExecutorInput) (string, error) {
func exportClone(ctx context.Context, input NewGitCloneExecutorInput, archiveErr error) (string, error) {
clone := input
clone.Dir = filepath.Join(input.Dir, "git")
sha, _, err := resolveClone(ctx, clone)
if mismatch, ok := archiveErr.(*Error); ok && !strings.EqualFold(sha, mismatch.commit) {
return "", errors.Join(err, mismatch)
}
if err != nil || treeIntact(input.Dir, sha) {
return sha, err
}
@@ -216,11 +219,10 @@ func exportClone(ctx context.Context, input NewGitCloneExecutorInput) (string, e
if err != nil {
return "", err
}
_, err = extractTree(ctx, bytes.NewReader(archive), input.Dir, false)
return sha, err
return extractTree(ctx, bytes.NewReader(archive), input.Dir, sha, false)
}
func extractTree(ctx context.Context, archive io.Reader, dir string, strip bool) (string, error) { // into dir/<commit of the pax header>, strip dropping the directory wrapping the files
func extractTree(ctx context.Context, archive io.Reader, dir, ref string, strip bool) (string, error) { // into dir/<commit of the pax header>, strip dropping the directory wrapping the files
temp, err := os.MkdirTemp(dir, "tmp-")
if err != nil {
return "", err
@@ -246,8 +248,13 @@ func extractTree(ctx context.Context, archive io.Reader, dir string, strip bool)
return "", err
}
if header.Typeflag == tar.TypeXGlobalHeader {
if sha = header.PAXRecords["comment"]; isFullObjectID(sha) && treeIntact(dir, sha) {
return sha, nil
if sha = header.PAXRecords["comment"]; isFullObjectID(sha) {
if err := verifyPin(ctx, "", ref, sha); err != nil {
return "", err
}
if treeIntact(dir, sha) {
return sha, nil
}
}
continue
}

View File

@@ -79,6 +79,8 @@ func TestFetchAction(t *testing.T) {
case archives == "redirect" && request.Host != mirror.Listener.Addr().String():
http.Redirect(writer, request, mirror.URL+request.URL.Path, http.StatusFound)
return
case archives == "wrong commit":
ref = "main.tar.gz"
}
sha, ok := revisions[ref]
if !ok {
@@ -192,7 +194,7 @@ func TestFetchAction(t *testing.T) {
}
})
t.Run("downloads, revalidates and follows a moved tag", func(t *testing.T) {
t.Run("revalidates a moved tag and rejects mismatched cached and archived commits", func(t *testing.T) {
serve("prefixed", 0)
input := newInput("v1")
tree, sha, err := FetchAction(t.Context(), input)
@@ -244,12 +246,29 @@ func TestFetchAction(t *testing.T) {
assert.Empty(t, headers[0].Get("If-None-Match"))
assert.Equal(t, fmt.Sprintf(`W/"%s-tar.gz-true"`, sha), headers[1].Get("If-None-Match"))
assert.Equal(t, headers[1].Get("If-None-Match"), headers[2].Get("If-None-Match"))
require.NoError(t, gitCmd("-C", remote, "tag", "-a", "pinned", "-m", "release", sha))
input.Ref = gitRevParse(t, remote, "pinned")
for range 2 {
_, got, err := FetchAction(t.Context(), input)
require.NoError(t, err)
assert.Equal(t, sha, got)
}
_, headers = served()
require.Len(t, headers, 5)
serve("wrong commit", 0)
input = newInput(sha)
_, _, err = FetchAction(t.Context(), input)
require.ErrorContains(t, err, sha)
require.ErrorContains(t, err, movedSha)
assert.NoDirExists(t, filepath.Join(input.Dir, movedSha))
})
t.Run("downloads a pinned commit once and rejects a short one", func(t *testing.T) {
serve("prefixed", 0)
sha := expectedSha
input := newInput(sha)
input := newInput(strings.ToUpper(sha))
for range 2 {
tree, got, err := FetchAction(t.Context(), input)
require.NoError(t, err)
@@ -270,6 +289,9 @@ func TestFetchAction(t *testing.T) {
input := newInput(sha)
tree, _, err := FetchAction(t.Context(), input)
require.NoError(t, err, mode)
if mode == "none" {
require.NoError(t, gitCmd("-C", filepath.Join(input.Dir, "git"), "replace", sha+":action.yml", sha+":run.sh"))
}
yml := filepath.Join(tree, "action.yml")
require.NoError(t, os.WriteFile(filepath.Join(tree, "trampoline.js"), nil, 0o644)) // the runner's own, no damage
_, _, err = FetchAction(t.Context(), input)
@@ -398,7 +420,7 @@ func TestExtractTreeConfinesEntries(t *testing.T) {
require.NoError(t, writer.Close())
dir := t.TempDir()
_, err := extractTree(t.Context(), &archive, dir, false)
_, err := extractTree(t.Context(), &archive, dir, "", false)
require.Error(t, err)
assert.NoFileExists(t, filepath.Join(dir, "escape"))
assert.NoFileExists(t, filepath.Join(outside, "escape"))
@@ -448,7 +470,7 @@ func TestExtractTreeCopiesDeferredLinks(t *testing.T) {
require.NoError(t, writer.Close())
dir := t.TempDir()
_, err := extractTree(t.Context(), &archive, dir, false)
_, err := extractTree(t.Context(), &archive, dir, sha, false)
require.NoError(t, err)
assert.True(t, treeIntact(dir, sha))
if test.text {
@@ -493,7 +515,7 @@ func TestTreeIntactFindsNamesThatAreNotUTF8(t *testing.T) {
require.NoError(t, writer.Close())
dir := t.TempDir()
_, err = extractTree(t.Context(), &archive, dir, false)
_, err = extractTree(t.Context(), &archive, dir, sha, false)
require.NoError(t, err)
require.FileExists(t, filepath.Join(dir, sha, "caf\xe9.js"))
assert.True(t, treeIntact(dir, sha))
@@ -534,7 +556,7 @@ func TestExtractTreeCreatesLinksInPlatformOrder(t *testing.T) {
t.Run(test.name, func(t *testing.T) {
symlinkFallback = test.fallback
created = nil
_, err := extractTree(t.Context(), bytes.NewReader(archive.Bytes()), t.TempDir(), false)
_, err := extractTree(t.Context(), bytes.NewReader(archive.Bytes()), t.TempDir(), "", false)
require.NoError(t, err)
assert.Equal(t, test.want, created)
})

View File

@@ -12,6 +12,7 @@ import (
"errors"
"fmt"
"io"
"io/fs"
"net/http"
"net/url"
"os"
@@ -192,7 +193,11 @@ type NewGitCloneExecutorInput struct {
// CloneIfRequired reports whether an existing local clone was reused.
func CloneIfRequired(ctx context.Context, input NewGitCloneExecutorInput, logger *logging.Logger) (bool, error) {
var origin string
_, err := os.Stat(filepath.Join(input.Dir, ".git")) // without it git would discover a repository around Dir
gitDir := filepath.Join(input.Dir, ".git")
_, err := os.Stat(gitDir) // without it git would discover a repository around Dir
if err == nil && !input.OfflineMode {
err = findStaleLock(gitDir)
}
if err == nil {
origin, err = findGitRemoteURL(ctx, input.Dir)
}
@@ -205,7 +210,7 @@ func CloneIfRequired(ctx context.Context, input NewGitCloneExecutorInput, logger
if err == nil {
logger.Debugf("Removing cached clone at %s because origin URL changed from %s to %s", input.Dir, origin, input.URL)
} else if _, statErr := os.Stat(input.Dir); statErr == nil {
logger.Debugf("Removing cached clone at %s because origin cannot be read: %v", input.Dir, err)
logger.Debugf("Removing cached clone at %s because it cannot be reused: %v", input.Dir, err)
}
if err := os.RemoveAll(input.Dir); err != nil {
return false, fmt.Errorf("remove cached clone %s: %w", input.Dir, err)
@@ -219,6 +224,21 @@ func CloneIfRequired(ctx context.Context, input NewGitCloneExecutorInput, logger
return false, nil
}
// findStaleLock fails on a lock file a killed git left behind, which would fail every later fetch or checkout.
func findStaleLock(gitDir string) error {
for _, name := range []string{"HEAD.lock", "config.lock", "index.lock", "packed-refs.lock", "shallow.lock"} {
if _, err := os.Lstat(filepath.Join(gitDir, name)); err == nil {
return fmt.Errorf("stale lock %s", name)
}
}
return filepath.WalkDir(filepath.Join(gitDir, "refs"), func(path string, _entry fs.DirEntry, err error) error {
if err == nil && strings.HasSuffix(path, ".lock") {
return fmt.Errorf("stale lock %s", path)
}
return nil
})
}
// NewGitCloneExecutor creates an executor to clone git repos
func NewGitCloneExecutor(input NewGitCloneExecutorInput) common.Executor {
return func(ctx context.Context) error {
@@ -255,10 +275,10 @@ func resolveClone(ctx context.Context, input NewGitCloneExecutorInput) (string,
return "", false, err
}
resolved, err := resolveRef(ctx, input.Dir, input.Ref)
if errors.Is(err, ErrShortRef) || (err != nil && input.OfflineMode) {
return "", false, err
if _, invalidRef := errors.AsType[*Error](err); invalidRef || input.OfflineMode {
return resolved, reused, err
}
if !input.OfflineMode && (err != nil || (reused && !isFullHash(input.Ref, resolved))) {
if err != nil || (reused && !isFullObjectID(input.Ref)) {
if err := fetch(ctx, input); err != nil {
return "", false, err
}
@@ -340,20 +360,39 @@ func resolveRef(ctx context.Context, dir, ref string) (string, error) {
}
}
sha, err := gitOutput(ctx, dir, "rev-parse", "--verify", ref+"^{commit}")
if err == nil && hexRefRegex.MatchString(ref) && len(sha) != len(ref) {
if err != nil {
return "", err
}
if err := verifyPin(ctx, dir, ref, sha); err != nil {
return "", err
}
if len(sha) != len(ref) && hexRefRegex.MatchString(ref) {
return "", &Error{err: ErrShortRef, commit: sha}
}
return sha, err
return sha, nil
}
func verifyPin(ctx context.Context, gitDir, ref, sha string) error {
if strings.EqualFold(ref, sha) || !isFullObjectID(ref) {
return nil
}
if gitDir != "" && len(ref) == len(sha) {
objects, err := gitOutput(ctx, gitDir, "rev-parse", ref+"^{tag}", ref+"^{commit}")
if err == nil && strings.EqualFold(objects, ref+"\n"+sha) {
return nil
}
}
err := fmt.Errorf("action pinned to %s, got commit %s", ref, sha)
if gitDir != "" && len(ref) < len(sha) && strings.EqualFold(ref, sha[:len(ref)]) {
err = fmt.Errorf("%w: %w", err, ErrShortRef)
}
return &Error{err: err, commit: sha}
}
func isFullObjectID(ref string) bool {
return ObjectFormat(ref) != ""
}
func isFullHash(ref, resolved string) bool {
return isFullObjectID(ref) && len(ref) == len(resolved)
}
// ObjectFormat returns the object format of a full commit hash, empty for anything else.
func ObjectFormat(sha string) string {
switch {
@@ -476,7 +515,7 @@ func runGitWithStdin(ctx context.Context, dir string, input *NewGitCloneExecutor
for key, value := range ConfigEnv(config...) {
cmd.Env = append(cmd.Env, key+"="+value)
}
cmd.Env = append(cmd.Env, "GIT_TERMINAL_PROMPT=0")
cmd.Env = append(cmd.Env, "GIT_TERMINAL_PROMPT=0", "GIT_NO_REPLACE_OBJECTS=1")
var treeKill *process.TreeKill
if runtime.GOOS == "windows" {
treeKill = process.NewTreeKill(cmd) // a cancelled git leaves its remote helper holding the repository otherwise

View File

@@ -275,7 +275,7 @@ func TestGitCloneExecutor(t *testing.T) {
clones.Wait()
}
func TestGitCloneExecutorReclonesWhenOriginURLChanges(t *testing.T) {
func TestGitCloneExecutorReclonesWhenOriginURLChangesOrLockIsStale(t *testing.T) {
t.Parallel()
createRemote := func(message string) string {
dir := t.TempDir()
@@ -324,6 +324,13 @@ func TestGitCloneExecutorReclonesWhenOriginURLChanges(t *testing.T) {
_, err = os.Stat(markerPath)
require.True(t, os.IsNotExist(err), "stale cached directory should be removed before recloning")
lockPath := filepath.Join(cacheDir, ".git", "index.lock")
require.NoError(t, os.WriteFile(lockPath, nil, 0o644))
require.NoError(t, os.WriteFile(markerPath, nil, 0o644))
require.NoError(t, NewGitCloneExecutor(NewGitCloneExecutorInput{URL: newRemoteDir, Ref: "main", Dir: cacheDir})(t.Context()))
assert.NoFileExists(t, lockPath)
assert.NoFileExists(t, markerPath)
}
func TestGitCloneExecutorFollowsRemoteRefChanges(t *testing.T) {
@@ -488,6 +495,11 @@ func TestGitCloneExecutorShallow(t *testing.T) {
require.NoError(t, clone(t.Context()))
assert.FileExists(t, shallowMarker(dir))
require.ErrorIs(t, NewGitCloneExecutor(NewGitCloneExecutorInput{URL: remote, Ref: sha[:40], Dir: dir, Depth: 1, OfflineMode: true})(t.Context()), ErrShortRef)
tag := strings.Repeat("a", 40)
require.NoError(t, gitCmd("-C", dir, "tag", tag, sha))
err := NewGitCloneExecutor(NewGitCloneExecutorInput{URL: remote, Ref: tag, Dir: dir, OfflineMode: true})(t.Context())
require.ErrorContains(t, err, sha)
require.NotErrorIs(t, err, ErrShortRef)
require.NoError(t, os.RemoveAll(remote))
require.NoError(t, clone(t.Context()))
assert.Equal(t, sha, gitRevParse(t, dir, "HEAD"))

View File

@@ -27,6 +27,12 @@ var hostOS = runtime.GOOS // replaced in tests
// DrainGracePeriod caps the wait for container output to drain so the log tail is not truncated
const DrainGracePeriod = 2 * time.Second
// CacheIsolation is how jobs reach a cache address on another network: attach ContainerID to theirs, or not at all on a docker_gwbridge gateway.
type CacheIsolation struct {
ContainerID string
GatewayBridge bool
}
// ExitCodeError reports a non-zero process exit code from a container command.
type ExitCodeError int

View File

@@ -11,6 +11,7 @@ import (
cerrdefs "github.com/containerd/errdefs"
"github.com/moby/moby/client"
"github.com/moby/moby/client/pkg/versions"
specs "github.com/opencontainers/image-spec/specs-go/v1"
)
@@ -23,22 +24,30 @@ func ImageExistsLocally(ctx context.Context, imageName, platform string) (bool,
}
defer cli.Close()
inspectImage, err := cli.ImageInspect(ctx, imageName)
var requested *specs.Platform
if platform == "" {
if version, err := cli.ServerVersion(ctx, client.ServerVersionOptions{}); err == nil {
requested = &specs.Platform{OS: version.Os, Architecture: version.Arch}
}
} else if platform != "any" {
requested, err = parsePlatform(platform)
if err != nil {
return false, err
}
}
inspectPlatform := requested
if versions.LessThan(cli.ClientVersion(), "1.49") {
inspectPlatform = nil
}
inspectImage, err := cli.ImageInspect(ctx, imageName, client.ImageInspectWithPlatform(inspectPlatform))
if cerrdefs.IsNotFound(err) {
return false, nil
} else if err != nil {
return false, err
}
if platform == "" || platform == "any" {
return true, nil
}
requested, err := parsePlatform(platform)
if err != nil {
return false, err
}
return platformMatches(requested, &specs.Platform{OS: inspectImage.Os, Architecture: inspectImage.Architecture, Variant: inspectImage.Variant}), nil
return requested == nil || platformMatches(requested, &specs.Platform{OS: inspectImage.Os, Architecture: inspectImage.Architecture, Variant: inspectImage.Variant}), nil
}
func platformMatches(requested, image *specs.Platform) bool {
@@ -49,8 +58,6 @@ func platformMatches(requested, image *specs.Platform) bool {
return image.OS == requested.OS && image.Architecture == requested.Architecture && (requested.Variant == "" || requested.Variant == variant)
}
// RemoveImage removes image from local store, the function is used to run different
// container image architectures
func RemoveImage(ctx context.Context, imageName string, force, pruneChildren bool) (bool, error) {
cli, err := GetDockerClient(ctx)
if err != nil {

View File

@@ -238,23 +238,23 @@ func removeNetwork(ctx context.Context, cli client.APIClient, name string) error
return errors.Join(errs...)
}
// IsolatedCacheContainer returns the container holding addr, when jobs on jobNetwork cannot reach it there.
func IsolatedCacheContainer(ctx context.Context, addr netip.Addr, jobNetwork string) (string, error) {
// DetectCacheIsolation finds what jobs on jobNetwork need to reach a cache address held by another container.
func DetectCacheIsolation(ctx context.Context, addr netip.Addr, jobNetwork string) (CacheIsolation, error) {
cli, err := GetDockerClient(ctx)
if err != nil {
return "", err
return CacheIsolation{}, err
}
defer cli.Close()
return isolatedCacheContainer(ctx, cli, addr, jobNetwork)
return detectCacheIsolation(ctx, cli, addr, jobNetwork)
}
func isolatedCacheContainer(ctx context.Context, cli client.APIClient, addr netip.Addr, jobNetwork string) (string, error) {
func detectCacheIsolation(ctx context.Context, cli client.APIClient, addr netip.Addr, jobNetwork string) (CacheIsolation, error) {
if jobNetwork == "host" || strings.HasPrefix(jobNetwork, "container:") {
return "", nil
return CacheIsolation{}, nil
}
containers, err := cli.ContainerList(ctx, client.ContainerListOptions{})
if err != nil {
return "", err
return CacheIsolation{}, err
}
var holderID, holderContainer string
for _, summary := range containers.Items {
@@ -268,18 +268,29 @@ func isolatedCacheContainer(ctx context.Context, cli client.APIClient, addr neti
}
}
}
if holderID == "" {
return "", nil
if holderID == "" { // ContainerList omits docker_gwbridge gateway endpoints, which attaching their container to a job network would remove
gateway, err := cli.NetworkInspect(ctx, "docker_gwbridge", client.NetworkInspectOptions{})
if cerrdefs.IsNotFound(err) {
return CacheIsolation{}, nil
} else if err != nil {
return CacheIsolation{}, err
}
for _, endpoint := range gateway.Network.Containers {
if endpoint.IPv4Address.Addr() == addr || endpoint.IPv6Address.Addr() == addr {
return CacheIsolation{GatewayBridge: true}, nil
}
}
return CacheIsolation{}, nil
}
holder, err := cli.NetworkInspect(ctx, holderID, client.NetworkInspectOptions{})
if err != nil || holder.Network.Driver != "bridge" {
return "", err
return CacheIsolation{}, err
}
if jobNetwork != "" {
job, err := cli.NetworkInspect(ctx, jobNetwork, client.NetworkInspectOptions{})
if err != nil || job.Network.ID == holderID {
return "", err
return CacheIsolation{}, err
}
}
return holderContainer, nil
return CacheIsolation{ContainerID: holderContainer}, nil
}

View File

@@ -20,10 +20,11 @@ import (
"github.com/stretchr/testify/require"
)
func TestIsolatedCacheContainer(t *testing.T) {
func TestDetectCacheIsolation(t *testing.T) {
ctx := t.Context()
cache, lan := netip.MustParseAddr("172.18.0.3"), netip.MustParseAddr("192.168.1.20")
cache, lan, gateway := netip.MustParseAddr("172.18.0.3"), netip.MustParseAddr("192.168.1.20"), netip.MustParsePrefix("172.19.0.3/16")
client := &mockDockerClient{}
client.On("NetworkInspect", ctx, "docker_gwbridge", mobyclient.NetworkInspectOptions{}).Return(mobyclient.NetworkInspectResult{}, cerrdefs.ErrNotFound).Once()
client.On("ContainerList", ctx, mobyclient.ContainerListOptions{}).Return(mobyclient.ContainerListResult{Items: []container.Summary{{}, {
ID: "0123456789abcdef",
NetworkSettings: &container.NetworkSettingsSummary{Networks: map[string]*network.EndpointSettings{
@@ -31,26 +32,29 @@ func TestIsolatedCacheContainer(t *testing.T) {
"lan": {NetworkID: "beef", IPAddress: lan},
}},
}}}, nil)
for ref, inspected := range map[string]network.Network{
"c0ffee": {ID: "c0ffee", Name: "compose", Driver: "bridge"},
"beef": {ID: "beef", Name: "lan", Driver: "macvlan"},
"c0f": {ID: "c0ffee"},
"jobs": {ID: "f00d"},
for ref, inspected := range map[string]network.Inspect{
"c0ffee": {Network: network.Network{ID: "c0ffee", Name: "compose", Driver: "bridge"}},
"beef": {Network: network.Network{ID: "beef", Name: "lan", Driver: "macvlan"}},
"c0f": {Network: network.Network{ID: "c0ffee"}},
"jobs": {Network: network.Network{ID: "f00d"}},
"docker_gwbridge": {Containers: map[string]network.EndpointResource{"fedcba9876543210": {IPv4Address: gateway}}},
} {
client.On("NetworkInspect", ctx, ref, mobyclient.NetworkInspectOptions{}).
Return(mobyclient.NetworkInspectResult{Network: network.Inspect{Network: inspected}}, nil)
Return(mobyclient.NetworkInspectResult{Network: inspected}, nil)
}
check := func(addr netip.Addr, jobNetwork, want string) {
got, err := isolatedCacheContainer(ctx, client, addr, jobNetwork)
check := func(addr netip.Addr, jobNetwork string, want CacheIsolation) {
got, err := detectCacheIsolation(ctx, client, addr, jobNetwork)
require.NoError(t, err)
assert.Equal(t, want, got, jobNetwork)
}
check(cache, "", "0123456789ab")
check(cache, "jobs", "0123456789ab")
check(cache, "c0f", "")
check(cache, "host", "")
check(lan, "", "")
check(netip.MustParseAddr("10.0.0.5"), "", "")
check(cache, "", CacheIsolation{ContainerID: "0123456789ab"})
check(cache, "jobs", CacheIsolation{ContainerID: "0123456789ab"})
check(cache, "c0f", CacheIsolation{})
check(cache, "host", CacheIsolation{})
check(lan, "", CacheIsolation{})
check(gateway.Addr(), "jobs", CacheIsolation{})
check(gateway.Addr(), "jobs", CacheIsolation{GatewayBridge: true})
check(netip.MustParseAddr("10.0.0.5"), "", CacheIsolation{})
}
func TestIsAddressPoolExhausted(t *testing.T) {

View File

@@ -7,6 +7,7 @@
package container
import (
"cmp"
"context"
"fmt"
"strings"
@@ -77,7 +78,7 @@ func NewDockerPullExecutor(input NewDockerPullExecutorInput) common.Executor {
return nil
}
// a registry that is down should not fail a job whose image is already here
if exists, existsErr := ImageExistsLocally(ctx, input.Image, input.Platform); existsErr == nil && exists {
if exists, existsErr := ImageExistsLocally(ctx, input.Image, cmp.Or(input.Platform, "any")); existsErr == nil && exists {
logger.Warnf("could not update image '%s' (%s), continuing with the local copy: %v", imageRef, input.Platform, err)
return nil
}

View File

@@ -8,7 +8,10 @@ package container
import (
"io"
"net/http"
"net/http/httptest"
"os"
"path"
"path/filepath"
"strings"
"testing"
@@ -94,6 +97,41 @@ func TestIsPinnedImage(t *testing.T) {
assert.False(t, isPinnedImage("alpine:latest"))
}
func TestDockerPullFallsBackToLocalPlatform(t *testing.T) {
t.Setenv("DOCKER_API_VERSION", "1.49")
t.Setenv("DOCKER_CONFIG", t.TempDir())
t.Setenv("DOCKER_AUTH_CONFIG", "")
for _, image := range []string{"multiarch", "foreign", "no-version"} {
pulled := false
daemon := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
switch path.Base(request.URL.Path) {
case "version":
if image == "no-version" {
writer.WriteHeader(http.StatusForbidden)
}
_, _ = io.WriteString(writer, `{"Os":"linux","Arch":"s390x"}`)
case "json":
if platform := request.URL.Query().Get("platform"); platform == "" {
_, _ = io.WriteString(writer, `{"Os":"linux","Architecture":"arm64"}`)
} else if image == "multiarch" {
assert.JSONEq(t, `{"os":"linux","architecture":"s390x"}`, platform)
_, _ = io.WriteString(writer, `{"Os":"linux","Architecture":"s390x"}`)
} else {
writer.WriteHeader(http.StatusNotFound)
}
case "create":
pulled = true
writer.WriteHeader(http.StatusServiceUnavailable)
}
}))
t.Setenv("DOCKER_HOST", daemon.URL)
err := NewDockerPullExecutor(NewDockerPullExecutorInput{Image: image})(t.Context())
daemon.Close()
require.NoError(t, err, image)
assert.Equal(t, image == "foreign", pulled, image)
}
}
// The pull path reports a failure the daemon sent mid-stream, so it must carry the reason
// whichever of the two shapes the daemon used.
func TestLogDockerResponseError(t *testing.T) {

View File

@@ -145,6 +145,47 @@ func (cr *containerReference) CopyDir(destPath, srcPath string, useGitIgnore, sk
).IfNot(common.Dryrun)
}
// SeedVolume writes volume unless it already holds marker, so a seeded volume is never rewritten under running jobs, and prunes old volumes named prefix*.
func (cr *containerReference) SeedVolume(volume, prefix, marker string, write func(io.Writer) error) common.Executor {
return cr.connect().Then(func(ctx context.Context) (err error) {
platform, err := cr.containerPlatform(ctx)
if err != nil {
return err
}
const seedPath = "/gitea-runner-volume-seed"
created, err := cr.cli.ContainerCreate(ctx, client.ContainerCreateOptions{
Platform: platform,
Config: &container.Config{Image: cr.input.Image, Cmd: []string{"true"}},
HostConfig: &container.HostConfig{
NetworkMode: "none",
Mounts: []mount.Mount{{
Type: mount.TypeVolume,
Source: volume,
Target: seedPath,
VolumeOptions: &mount.VolumeOptions{NoCopy: true},
}},
},
})
if err != nil {
return fmt.Errorf("failed to create volume seed container: %w", err)
}
helper := &containerReference{cli: cr.cli, id: created.ID}
defer func() { err = errors.Join(err, helper.remove()(context.WithoutCancel(ctx))) }()
if _, err := cr.cli.ContainerStatPath(ctx, helper.id, client.ContainerStatPathOptions{Path: seedPath + "/" + marker}); err == nil {
return nil
}
reader, writer := io.Pipe()
defer reader.Close()
go func() { writer.CloseWithError(write(writer)) }()
if err := helper.upload(ctx, seedPath, reader); err != nil {
return err
}
pruneSeedVolumes(ctx, cr.cli, volume, prefix, time.Now().Add(-7*24*time.Hour))
return nil
}).IfNot(common.Dryrun)
}
func (cr *containerReference) GetContainerArchive(ctx context.Context, srcPath string) (io.ReadCloser, error) {
if common.Dryrun(ctx) {
return nil, errors.New("DRYRUN is not supported in GetContainerArchive")
@@ -334,12 +375,16 @@ func (cr *containerReference) UpdateFromImageEnv(env *map[string]string) common.
}
func (cr *containerReference) Exec(command []string, env map[string]string, user, workdir string) common.Executor {
return common.NewPipelineExecutor(
run := common.NewPipelineExecutor(
common.NewInfoExecutor("docker exec cmd=[%s] user=%s workdir=%s", strings.Join(command, " "), user, workdir),
cr.connect(),
cr.find(),
cr.exec(command, env, user, workdir),
).IfNot(common.Dryrun)
)
return common.Executor(func(ctx context.Context) error {
err := run(ctx)
return cmp.Or(context.Cause(ctx), err)
}).IfNot(common.Dryrun)
}
func (cr *containerReference) Remove() common.Executor {
@@ -436,17 +481,7 @@ func RunnerArch(ctx context.Context) string {
return ""
}
archMapper := map[string]string{
"x86_64": "X64",
"amd64": "X64",
"386": "X86",
"aarch64": "ARM64",
"arm64": "ARM64",
}
if arch, ok := archMapper[info.Architecture]; ok {
return arch
}
return info.Architecture
return goArchToActionArch(info.Architecture)
}
func (cr *containerReference) targetOS(ctx context.Context) string {
@@ -667,6 +702,12 @@ func (cr *containerReference) mergeContainerConfigs(ctx context.Context, config
overlay(reflect.ValueOf(hostConfig).Elem(), reflect.ValueOf(containerConfig.HostConfig).Elem(), false)
hostConfig.Binds = binds
hostConfig.Mounts = mounts
if containerConfig.HostConfig.MaskedPaths != nil {
hostConfig.MaskedPaths = containerConfig.HostConfig.MaskedPaths
}
if containerConfig.HostConfig.ReadonlyPaths != nil {
hostConfig.ReadonlyPaths = containerConfig.HostConfig.ReadonlyPaths
}
if cf.name != "" {
logger.Warn("--name in the options will be ignored.")
}
@@ -720,18 +761,9 @@ func (cr *containerReference) create(capAdd, capDrop []string) common.Executor {
})
}
var platSpecs *specs.Platform
if cr.input.Platform != "" {
// Dropping the platform silently would build for the host arch.
supported, err := supportsContainerImagePlatform(ctx, cr.cli)
if err != nil {
return err
}
if supported {
if platSpecs, err = parsePlatform(cr.input.Platform); err != nil {
return err
}
}
platform, err := cr.containerPlatform(ctx)
if err != nil {
return err
}
hostConfig := &container.HostConfig{
@@ -770,7 +802,7 @@ func (cr *containerReference) create(capAdd, capDrop []string) common.Executor {
Config: config,
HostConfig: hostConfig,
NetworkingConfig: networkingConfig,
Platform: platSpecs,
Platform: platform,
Name: input.Name,
})
if err != nil {
@@ -785,6 +817,21 @@ func (cr *containerReference) create(capAdd, capDrop []string) common.Executor {
}
}
func (cr *containerReference) containerPlatform(ctx context.Context) (*specs.Platform, error) {
platform := cr.input.Platform
if platform != "" {
// Dropping the platform silently would build for the host arch.
supported, err := supportsContainerImagePlatform(ctx, cr.cli)
if err != nil {
return nil, err
}
if !supported {
platform = ""
}
}
return parsePlatform(platform)
}
func (cr *containerReference) exec(cmd []string, env map[string]string, user, workdir string) common.Executor {
return func(ctx context.Context) error {
if cr.id == "" {

View File

@@ -11,6 +11,7 @@ import (
"bufio"
"bytes"
"context"
"crypto/rand"
"encoding/binary"
"errors"
"io"
@@ -23,6 +24,7 @@ import (
"sync"
"sync/atomic"
"testing"
"time"
"gitea.com/gitea/runner/act/common"
"gitea.com/gitea/runner/act/common/logging"
@@ -71,6 +73,58 @@ func TestDockerEnvironmentUsesContainerPath(t *testing.T) {
client.AssertExpectations(t)
}
func TestDockerSeedVolume(t *testing.T) {
requireDocker(t)
ctx := t.Context()
cleanupCtx := context.WithoutCancel(ctx)
require.NoError(t, NewDockerPullExecutor(NewDockerPullExecutorInput{Image: "alpine"})(ctx))
cr := &containerReference{input: &NewContainerInput{Image: "alpine"}}
require.NoError(t, cr.connect()(ctx))
t.Cleanup(func() { assert.NoError(t, cr.Close()(cleanupCtx)) })
prefix := "node-seed-test-" + strings.ToLower(rand.Text()) + "-"
volume, oldVolume := prefix+"current", prefix+"old"
t.Cleanup(func() {
assert.NoError(t, NewDockerVolumeRemoveExecutor(volume, false)(cleanupCtx))
assert.NoError(t, NewDockerVolumeRemoveExecutor(oldVolume, false)(cleanupCtx))
})
_, err := cr.cli.VolumeCreate(ctx, mobyclient.VolumeCreateOptions{Name: oldVolume})
require.NoError(t, err)
for _, body := range []string{"seeded", "reseeded"} {
require.NoError(t, cr.SeedVolume(volume, prefix, "node", func(out io.Writer) error {
return writeFilesTar(ctx, out, 0, 0, &FileEntry{Name: "node", Mode: 0o755, Body: body})
})(ctx))
}
_, err = cr.cli.VolumeInspect(ctx, oldVolume, mobyclient.VolumeInspectOptions{})
require.NoError(t, err)
pruneSeedVolumes(ctx, cr.cli, volume, prefix, time.Now().Add(time.Minute))
_, err = cr.cli.VolumeInspect(ctx, oldVolume, mobyclient.VolumeInspectOptions{})
require.ErrorIs(t, err, cerrdefs.ErrNotFound)
readback, err := cr.cli.ContainerCreate(ctx, mobyclient.ContainerCreateOptions{
Config: &container.Config{Image: "alpine"},
HostConfig: &container.HostConfig{
NetworkMode: "none",
Mounts: []mount.Mount{{Type: mount.TypeVolume, Source: volume, Target: "/readback", ReadOnly: true}},
},
})
require.NoError(t, err)
t.Cleanup(func() {
_, err := cr.cli.ContainerRemove(cleanupCtx, readback.ID, mobyclient.ContainerRemoveOptions{RemoveVolumes: true})
assert.NoError(t, err)
})
archive, err := cr.cli.CopyFromContainer(ctx, readback.ID, mobyclient.CopyFromContainerOptions{SourcePath: "/readback/node"})
require.NoError(t, err)
defer archive.Content.Close()
reader := tar.NewReader(archive.Content)
_, err = reader.Next()
require.NoError(t, err)
content, err := io.ReadAll(reader)
require.NoError(t, err)
assert.Equal(t, "seeded", string(content))
}
type mockDockerClient struct {
mobyclient.APIClient
mock.Mock
@@ -204,7 +258,7 @@ func (m *mockConn) Close() (err error) {
}
func TestDockerExecAbort(t *testing.T) {
ctx, cancel := context.WithCancel(t.Context())
ctx, cancel := context.WithCancelCause(t.Context())
reader := &interruptReader{started: make(chan struct{}), interrupted: make(chan struct{}), stopped: make(chan struct{})}
conn := &mockConn{}
@@ -213,30 +267,25 @@ func TestDockerExecAbort(t *testing.T) {
Return(1, nil)
client := &mockDockerClient{}
client.On("ContainerInspect", ctx, "123", mobyclient.ContainerInspectOptions{}).Return(mobyclient.ContainerInspectResult{}, nil)
client.On("ExecCreate", ctx, "123", mock.AnythingOfType("client.ExecCreateOptions")).Return(mobyclient.ExecCreateResult{ID: "id"}, nil)
client.On("ExecAttach", ctx, "id", mock.AnythingOfType("client.ExecAttachOptions")).Return(mobyclient.ExecAttachResult{
Conn: conn,
Reader: bufio.NewReader(reader),
}, nil)
cr := &containerReference{
id: "123",
cli: client,
input: &NewContainerInput{},
}
run := (&containerReference{id: "123", cli: client, input: &NewContainerInput{}}).Exec(nil, nil, "", "")
channel := make(chan error)
go func() {
channel <- cr.exec([]string{""}, map[string]string{}, "user", "workdir")(ctx)
channel <- run(ctx)
}()
<-reader.started
cancel()
cancel(assert.AnError)
err := <-channel
require.ErrorIs(t, <-channel, assert.AnError)
<-reader.stopped
assert.ErrorIs(t, err, context.Canceled) //nolint:testifylint // pre-existing issue from nektos/act
require.ErrorIs(t, run(ctx), assert.AnError)
conn.AssertExpectations(t)
client.AssertExpectations(t)
@@ -521,7 +570,7 @@ func TestRunnerArchCachedPerRun(t *testing.T) {
writer.Header().Set("API-Version", "1.47")
if strings.HasSuffix(request.URL.Path, "/info") {
infos.Add(1)
_, _ = io.WriteString(writer, `{"Architecture":"aarch64"}`)
_, _ = io.WriteString(writer, `{"Architecture":"armv7l"}`)
}
}))
t.Cleanup(daemon.Close)
@@ -530,10 +579,10 @@ func TestRunnerArchCachedPerRun(t *testing.T) {
run := WithRunnerArch(t.Context())
var lookups sync.WaitGroup
for range 4 {
lookups.Go(func() { assert.Equal(t, "ARM64", extensions.GetRunnerContext(run)["arch"]) })
lookups.Go(func() { assert.Equal(t, "ARM", extensions.GetRunnerContext(run)["arch"]) })
}
lookups.Wait()
assert.Equal(t, "ARM64", extensions.GetRunnerContext(t.Context())["arch"])
assert.Equal(t, "ARM", extensions.GetRunnerContext(t.Context())["arch"])
assert.EqualValues(t, 2, infos.Load())
}
@@ -810,7 +859,8 @@ func TestMergeContainerConfigsStripsDangerousOptionsWhenUnprivileged(t *testing.
// OS-independent options only, --device and --gpus need a linux/windows server OS
const dangerousOptions = "--pid=host --ipc=host --uts=host --cgroupns=host " +
"--userns=host --cap-add=ALL --security-opt seccomp=unconfined " +
"--security-opt apparmor=unconfined --volumes-from other --isolation process " +
"--security-opt apparmor=unconfined --security-opt systempaths=unconfined " +
"--volumes-from other --isolation process " +
"--runtime runc --cgroup-parent /custom --sysctl net.ipv4.ip_forward=1 " +
"--log-driver=syslog --log-opt syslog-address=tcp://169.254.169.254:514 " +
"--oom-score-adj=-1000 --oom-kill-disable"
@@ -830,6 +880,8 @@ func TestMergeContainerConfigsStripsDangerousOptionsWhenUnprivileged(t *testing.
assert.Equal(t, []string{"ALL"}, kept.CapAdd)
assert.Equal(t, "runc", kept.Runtime)
assert.Equal(t, "host", string(kept.UsernsMode))
assert.Equal(t, []string{}, kept.MaskedPaths)
assert.Equal(t, []string{}, kept.ReadonlyPaths)
assert.False(t, kept.Privileged)
// privileged is the administrator opting in, so the workflow's options are honored

View File

@@ -23,8 +23,8 @@ func GetDockerClient(context.Context) (client.APIClient, error) {
return nil, errors.ErrUnsupported
}
func IsolatedCacheContainer(context.Context, netip.Addr, string) (string, error) {
return "", nil
func DetectCacheIsolation(context.Context, netip.Addr, string) (CacheIsolation, error) {
return CacheIsolation{}, nil
}
// ImageExistsLocally returns a boolean indicating if an image with the
@@ -33,8 +33,6 @@ func ImageExistsLocally(ctx context.Context, imageName, platform string) (bool,
return false, errors.ErrUnsupported
}
// RemoveImage removes image from local store, the function is used to run different
// container image architectures
func RemoveImage(ctx context.Context, imageName string, force, pruneChildren bool) (bool, error) {
return false, errors.ErrUnsupported
}

View File

@@ -10,6 +10,7 @@ import (
"context"
"errors"
"fmt"
"strings"
"time"
"gitea.com/gitea/runner/act/common"
@@ -87,3 +88,16 @@ func NewDockerVolumeRemoveExecutor(volumeName string, force bool) common.Executo
return err
}
}
func pruneSeedVolumes(ctx context.Context, cli client.APIClient, current, prefix string, createdBefore time.Time) {
volumes, err := cli.VolumeList(ctx, client.VolumeListOptions{Filters: make(client.Filters).Add("dangling", "true")})
if err != nil {
return
}
for _, item := range volumes.Items {
created, err := time.Parse(time.RFC3339, item.CreatedAt)
if err == nil && created.Before(createdBefore) && item.Name != current && strings.HasPrefix(item.Name, prefix) {
_, _ = cli.VolumeRemove(ctx, item.Name, client.VolumeRemoveOptions{})
}
}
}

View File

@@ -45,6 +45,37 @@ type HostEnvironment struct {
// it while a step is still starting.
procGroupOnce sync.Once
procGroup atomic.Pointer[process.Group]
thread *jobThread
mountTarget, mountSource string
undo func()
}
// jobThread runs calls on the OS thread whose children enter the job's mount namespace, a nil one runs them in place.
type jobThread struct {
calls chan func()
stopped chan struct{}
}
func (t *jobThread) run(call func()) {
if t != nil {
done := make(chan struct{})
select {
case t.calls <- func() { defer close(done); call() }:
<-done
return
case <-t.stopped:
}
}
call()
}
// HostPath maps a path the job's processes see to the one the runner sees.
func (e *HostEnvironment) HostPath(path string) string {
if rest, ok := strings.CutPrefix(path, e.mountTarget); ok && (rest == "" || os.IsPathSeparator(rest[0])) {
return e.mountSource + rest
}
return path
}
// processGroup returns the job-scoped process group, creating it on first use.
@@ -70,6 +101,7 @@ func (e *HostEnvironment) Close() common.Executor {
}
func (e *HostEnvironment) Copy(destPath string, files ...*FileEntry) common.Executor {
destPath = e.HostPath(destPath)
return func(ctx context.Context) error {
for _, f := range files {
if err := os.MkdirAll(filepath.Dir(filepath.Join(destPath, f.Name)), 0o777); err != nil {
@@ -84,6 +116,7 @@ func (e *HostEnvironment) Copy(destPath string, files ...*FileEntry) common.Exec
}
func (e *HostEnvironment) CopyDir(destPath, srcPath string, useGitIgnore, skipGitDir bool) common.Executor {
destPath, srcPath = e.HostPath(destPath), e.HostPath(srcPath)
return func(ctx context.Context) error {
logger := common.Logger(ctx)
srcPrefix := filepath.Dir(srcPath)
@@ -113,7 +146,7 @@ func (e *HostEnvironment) Inspect(_ context.Context) (*Info, error) {
}
func (e *HostEnvironment) GetContainerArchive(ctx context.Context, srcPath string) (io.ReadCloser, error) {
srcPath = filepath.Clean(srcPath)
srcPath = e.HostPath(filepath.Clean(srcPath))
fi, err := os.Lstat(srcPath)
if err != nil {
return nil, err
@@ -258,7 +291,9 @@ func (e *HostEnvironment) exec(ctx context.Context, command []string, cmdline st
defer common.FlushWriter(e.StdOut)
process.UTF8Console()
f, err := lookupPathHost(command[0], env, e.StdOut)
var f string
var err error
e.thread.run(func() { f, err = lookupPathHost(command[0], env, e.StdOut) })
if err != nil {
return err
}
@@ -311,7 +346,8 @@ func (e *HostEnvironment) exec(ctx context.Context, command []string, cmdline st
}()
go writeKeepAlive(logctx, ppty)
}
if err := cmd.Start(); err != nil {
e.thread.run(func() { err = cmd.Start() })
if err != nil {
return err
}
if tracked {
@@ -349,15 +385,8 @@ func (e *HostEnvironment) Exec(command []string, env map[string]string, _user, w
func (e *HostEnvironment) ExecWithCmdLine(command []string, cmdline string, env map[string]string, workdir string) common.Executor {
return func(ctx context.Context) error {
if err := e.exec(ctx, command, cmdline, env, workdir); err != nil {
select {
case <-ctx.Done():
return fmt.Errorf("this step has been cancelled: %w", err)
default:
return err
}
}
return nil
err := e.exec(ctx, command, cmdline, env, workdir)
return cmp.Or(context.Cause(ctx), err)
}
}
@@ -427,6 +456,9 @@ func (e *HostEnvironment) Remove() common.Executor {
} else if killed > 0 {
logger.Debugf("killed %d leftover process(es) of the job", killed)
}
if e.undo != nil {
e.undo()
}
// Detach: a cancelled ctx would skip removePathWithRetry's retries,
// which absorb Windows file-handle release lag after the kill above.
@@ -483,12 +515,10 @@ func (*HostEnvironment) JoinPathVariable(paths ...string) string {
// https://docs.github.com/en/actions/learn-github-actions/contexts#runner-context
func goArchToActionArch(arch string) string {
return cmp.Or(map[string]string{
"x86_64": "X64",
"amd64": "X64",
"386": "X86",
"arm": "ARM",
"aarch64": "ARM64",
"arm64": "ARM64",
"386": "X86", "i386": "X86", "i686": "X86",
"amd64": "X64", "x86_64": "X64",
"arm": "ARM", "armv6l": "ARM", "armv7l": "ARM",
"arm64": "ARM64", "aarch64": "ARM64",
}[arch], arch)
}

View File

@@ -28,7 +28,9 @@ var _ ExecutionsEnvironment = &HostEnvironment{}
func TestActionPlatformNames(t *testing.T) {
assert.Equal(t, []string{"Linux", "macOS", "Windows", "FreeBSD"}, []string{goOsToActionOs("linux"), goOsToActionOs("darwin"), goOsToActionOs("windows"), goOsToActionOs("freebsd")})
assert.Equal(t, []string{"X86", "X64", "ARM", "ARM64"}, []string{goArchToActionArch("386"), goArchToActionArch("amd64"), goArchToActionArch("arm"), goArchToActionArch("arm64")})
for arch, want := range map[string]string{"386": "X86", "i686": "X86", "amd64": "X64", "arm": "ARM", "armv6l": "ARM", "arm64": "ARM64", "riscv64": "riscv64"} {
assert.Equal(t, want, goArchToActionArch(arch), arch)
}
}
func TestCopyDir(t *testing.T) {
@@ -124,6 +126,12 @@ func TestHostEnvironmentExecExitCode(t *testing.T) {
}
}
func TestHostEnvironmentExecDeadline(t *testing.T) {
ctx, cancel := context.WithTimeoutCause(t.Context(), 0, assert.AnError)
defer cancel()
require.ErrorIs(t, (&HostEnvironment{}).Exec([]string{os.Args[0], "-test.run=^$"}, nil, "", "")(ctx), assert.AnError)
}
func TestHostEnvironmentAllocatePTY(t *testing.T) {
t.Parallel()
if runtime.GOOS == "windows" {

View File

@@ -0,0 +1,154 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package container
import (
"errors"
"fmt"
"os"
"path/filepath"
"regexp"
"runtime"
"strings"
"sync"
"time"
"golang.org/x/sys/unix"
)
var safePathName = regexp.MustCompile(`^[\w.-]*[\w-][\w.-]*$`) // not only dots
// UseWorkspace runs the job at root/<owner>/<repo>/<repo>, its parent showing a directory of the job's own to its processes, and to the host while no other job does.
func (e *HostEnvironment) UseWorkspace(root, repository string) error {
owner, repo, ok := strings.Cut(repository, "/")
if !ok || !safePathName.MatchString(owner) || !safePathName.MatchString(repo) {
return fmt.Errorf("repository %q is unsafe in a path", repository)
}
target, source := filepath.Join(root, owner, repo), filepath.Join(e.Root, "work")
if err := os.MkdirAll(filepath.Join(source, repo), 0o777); err != nil {
return err
}
if err := os.MkdirAll(target, 0o777); err != nil {
return err
}
releaseRoot, err := privateMount(root)
if err != nil {
return err
}
thread, err := startJobThread(source, target)
if err != nil {
releaseRoot()
return err
}
releaseView := shareView(target+".lock", source, target)
e.Path, e.thread, e.mountTarget, e.mountSource = filepath.Join(target, repo), thread, target, source
e.undo = func() {
close(thread.stopped)
releaseView()
releaseRoot()
}
return nil
}
var privateMounts sync.Mutex // threads would each bind dir
// privateMount keeps dir a mount that propagates nowhere while a job of any runner uses it, so binds below it stay in the namespace that makes them.
func privateMount(dir string) (release func(), err error) {
lock, err := os.OpenFile(dir+".lock", os.O_CREATE|os.O_RDONLY, 0o666)
if err != nil {
return nil, err
}
if err := unix.Flock(int(lock.Fd()), unix.LOCK_SH); err != nil {
return nil, errors.Join(err, lock.Close())
}
privateMounts.Lock()
defer privateMounts.Unlock()
if unix.Mount("", dir, "", unix.MS_PRIVATE, "") != nil {
if err := unix.Mount(dir, dir, "", unix.MS_BIND|unix.MS_REC, ""); err != nil {
return nil, errors.Join(err, lock.Close())
}
if err := unix.Mount("", dir, "", unix.MS_PRIVATE, ""); err != nil {
return nil, errors.Join(err, unix.Unmount(dir, unix.MNT_DETACH), lock.Close())
}
}
return func() {
if unix.Flock(int(lock.Fd()), unix.LOCK_EX|unix.LOCK_NB) == nil {
_ = unix.Unmount(dir, unix.MNT_DETACH)
}
lock.Close()
}, nil
}
// startJobThread starts a locked thread, ending with its goroutine, whose children see source at target and get no ambient CAP_SYS_ADMIN.
func startJobThread(source, target string) (*jobThread, error) {
thread := &jobThread{calls: make(chan func()), stopped: make(chan struct{})}
started := make(chan error)
go func() {
runtime.LockOSThread()
err := unix.Unshare(unix.CLONE_NEWNS)
if err == nil {
unmountAll(target)
err = unix.Mount(source, target, "", unix.MS_BIND, "")
}
_ = unix.Prctl(unix.PR_CAP_AMBIENT, unix.PR_CAP_AMBIENT_LOWER, unix.CAP_SYS_ADMIN, 0, 0)
started <- err
if err != nil {
return
}
for {
select {
case call := <-thread.calls:
call()
case <-thread.stopped:
return
}
}
}()
return thread, <-started
}
// shareView binds source at target on the host whenever no other job holds lock, trying at once and then every second, until release.
func shareView(lock, source, target string) (release func()) {
file, err := os.OpenFile(lock, os.O_CREATE|os.O_RDONLY, 0o666)
if err != nil {
return func() {}
}
bind := func() bool {
if unix.Flock(int(file.Fd()), unix.LOCK_EX|unix.LOCK_NB) != nil {
return false
}
unmountAll(target)
if unix.Mount(source, target, "", unix.MS_BIND, "") != nil {
_ = unix.Flock(int(file.Fd()), unix.LOCK_UN)
return false
}
return true
}
stop, stopped := make(chan struct{}), make(chan struct{})
bound := bind()
go func() {
defer close(stopped)
defer file.Close()
for !bound {
select {
case <-stop:
return
case <-time.After(time.Second):
bound = bind()
}
}
<-stop
_ = unix.Unmount(target, unix.MNT_DETACH)
}()
return func() {
close(stop)
<-stopped
}
}
// unmountAll drops the binds at target, copies of other jobs' views or ones a crashed runner left.
func unmountAll(target string) {
for unix.Unmount(target, unix.MNT_DETACH) == nil {
}
}

View File

@@ -0,0 +1,56 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package container
import (
"bytes"
"errors"
"os"
"path/filepath"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/sys/unix"
)
func TestUseWorkspaceGivesConcurrentJobsOnePathAndHandsTheHostViewOn(t *testing.T) {
dir := t.TempDir()
root := filepath.Join(dir, "workspaces")
workspace := filepath.Join(root, "owner", "repo", "repo")
require.ErrorContains(t, (&HostEnvironment{Root: dir}).UseWorkspace(root, "owner/.."), "unsafe")
start := func(name string) *HostEnvironment {
env := &HostEnvironment{Root: filepath.Join(dir, name), TrackingID: name}
err := env.UseWorkspace(root, "owner/repo")
if errors.Is(err, unix.EPERM) {
t.Skip("needs CAP_SYS_ADMIN")
}
require.NoError(t, err)
require.NoError(t, os.WriteFile(env.HostPath(filepath.Join(env.Path, "name")), []byte(name), 0o644))
return env
}
read := func(env *HostEnvironment) string {
var out bytes.Buffer
env.StdOut = &out
require.NoError(t, env.Exec([]string{"cat", "name"}, map[string]string{"PATH": os.Getenv("PATH")}, "", "")(t.Context()))
return out.String()
}
first, second := start("first"), start("second")
assert.Equal(t, workspace, second.Path)
assert.Equal(t, "first", read(first))
assert.Equal(t, "second", read(second))
shown, err := os.ReadFile(filepath.Join(workspace, "name"))
require.NoError(t, err)
assert.Equal(t, "first", string(shown))
require.NoError(t, first.Remove()(t.Context()))
assert.Equal(t, "second", read(second))
assert.Eventually(t, func() bool {
shown, _ := os.ReadFile(filepath.Join(workspace, "name"))
return string(shown) == "second"
}, 5*time.Second, 50*time.Millisecond)
require.NoError(t, second.Remove()(t.Context()))
}

View File

@@ -0,0 +1,12 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
//go:build !linux
package container
import "errors"
func (e *HostEnvironment) UseWorkspace(_root, _repository string) error {
return errors.ErrUnsupported
}

View File

@@ -501,10 +501,13 @@ func (c *kubernetesContainer) Exec(command []string, env map[string]string, _, w
// compressCopyMin is the size from which Copy compresses and uses the transfer helper: below it that saves next to nothing on the wire and costs a process in the pod.
const compressCopyMin = 64 << 10
// extract streams the tar write produces into destPath, gzipped with compress, as copied actions shrink about fivefold and API server traffic often crosses zones.
func (c *kubernetesContainer) extract(ctx context.Context, destPath string, compress bool, write func(io.Writer) error) error {
// extract streams the tar write produces into destPath, gzipped with compress or as writeGz has it, as copied actions shrink about fivefold and API server traffic often crosses zones.
func (c *kubernetesContainer) extract(ctx context.Context, destPath string, compress bool, write, writeGz func(io.Writer) error) error {
if writeGz == nil {
writeGz = func(writer io.Writer) error { return writeGzip(writer, write) }
}
if compress && c.pod.transferHelper != "" {
request, done := c.pod.transfer.offer(c.pod.ips, write)
request, done := c.pod.transfer.offer(c.pod.ips, writeGz)
stdin, _ := json.Marshal(request)
var stderr bytes.Buffer
err := c.pod.client.exec(ctx, c.pod.name, c.name, []string{c.pod.transferHelper, KubernetesTransferCommand, "fetch", destPath}, bytes.NewReader(stdin), io.Discard, &stderr)
@@ -523,7 +526,7 @@ func (c *kubernetesContainer) extract(ctx context.Context, destPath string, comp
defer reader.Close()
go func() {
if compress {
writer.CloseWithError(writeGzip(writer, write))
writer.CloseWithError(writeGz(writer))
} else {
writer.CloseWithError(write(writer))
}
@@ -551,15 +554,41 @@ func (c *kubernetesContainer) Copy(destPath string, files ...*FileEntry) common.
for _, file := range files {
size += len(file.Body)
}
return c.extract(ctx, destPath, size >= compressCopyMin, func(writer io.Writer) error { return writeFilesTar(ctx, writer, 0, 0, files...) })
return c.extract(ctx, destPath, size >= compressCopyMin, func(writer io.Writer) error { return writeFilesTar(ctx, writer, 0, 0, files...) }, nil)
}
}
func (c *kubernetesContainer) ExtractTarGz(destPath, archive string) common.Executor {
return func(ctx context.Context) error {
return c.extract(ctx, destPath, true, func(writer io.Writer) error {
return copyArchive(writer, archive, true)
}, func(writer io.Writer) error {
return copyArchive(writer, archive, false)
})
}
}
func copyArchive(writer io.Writer, archive string, gunzip bool) error {
file, err := os.Open(archive)
if err != nil {
return err
}
defer file.Close()
var reader io.Reader = file
if gunzip {
if reader, err = gzip.NewReader(file); err != nil {
return err
}
}
_, err = io.Copy(writer, reader)
return err
}
func (c *kubernetesContainer) CopyDir(destPath, srcPath string, useGitIgnore, skipGitDir bool) common.Executor {
return func(ctx context.Context) error {
return c.extract(ctx, destPath, true, func(writer io.Writer) error { // directories are actions and workspaces, megabytes of compressible sources
return writeDirTar(ctx, writer, "/", srcPath, useGitIgnore, skipGitDir, 0, 0, hostOS == "windows")
})
}, nil)
}
}

View File

@@ -6,6 +6,7 @@ package container
import (
"archive/tar"
"bytes"
"compress/gzip"
"encoding/json"
"errors"
"fmt"
@@ -109,7 +110,7 @@ func fakeKubernetes(t *testing.T, podStatus string, env ...string) (string, *fak
if failure := cluster.nextExecFailure(); failure != nil {
failure(w, r)
} else {
serveLocalExec(t, w, r, env)
serveLocalExec(t, w, r, env, cluster)
}
case strings.HasSuffix(r.URL.Path, "/log"):
_, _ = io.WriteString(w, "log of "+r.URL.Query().Get("container"))
@@ -132,7 +133,7 @@ users: [{name: test, user: {tokenFile: token}}]
return kubeconfig, cluster
}
func serveLocalExec(t *testing.T, w http.ResponseWriter, r *http.Request, env []string) {
func serveLocalExec(t *testing.T, w http.ResponseWriter, r *http.Request, env []string, cluster *fakeCluster) {
conn, err := websocket.Accept(w, r, &websocket.AcceptOptions{Subprotocols: []string{execProtocol}})
if err != nil {
t.Error(err)
@@ -153,6 +154,7 @@ func serveLocalExec(t *testing.T, w http.ResponseWriter, r *http.Request, env []
}
stdin.Write(frame[1:])
}
cluster.record("exec-stdin", stdin.String())
cmd := exec.Command(command[0], command[1:]...)
cmd.Env = append(append(os.Environ(), "COPYFILE_DISABLE=1"), env...)
var stdout, stderr bytes.Buffer
@@ -169,6 +171,17 @@ func serveLocalExec(t *testing.T, w http.ResponseWriter, r *http.Request, env []
}
}
func kubernetesTestTarGz(t *testing.T, file *FileEntry) string {
t.Helper()
var compressed bytes.Buffer
writer := gzip.NewWriter(&compressed)
require.NoError(t, writeFilesTar(t.Context(), writer, 0, 0, file))
require.NoError(t, writer.Close())
archive := filepath.Join(t.TempDir(), "archive.tar.gz")
require.NoError(t, os.WriteFile(archive, compressed.Bytes(), 0o600))
return archive
}
func TestKubernetesServiceHostnames(t *testing.T) {
for id, hostnames := range map[string][]string{
"db": {"db"},
@@ -309,6 +322,17 @@ func TestKubernetesPodRunsJobThroughAPI(t *testing.T) {
assert.Contains(t, lastExec(), "command="+url.QueryEscape(workdir+"/act/actions/sha/"))
assert.Contains(t, lastExec(), url.QueryEscape("gzip -dc |"))
gzipArchive := kubernetesTestTarGz(t, &FileEntry{Name: "index.js", Mode: 0o644, Body: "main()"})
require.NoError(t, pod.job.ExtractTarGz(workdir+"/act/cached", gzipArchive)(ctx))
assert.Contains(t, lastExec(), url.QueryEscape("gzip -dc |"))
compressed, err := os.ReadFile(gzipArchive)
require.NoError(t, err)
inputs := cluster.requests["exec-stdin"]
assert.Equal(t, string(compressed), inputs[len(inputs)-1])
script, err = os.ReadFile(workdir + "/act/cached/index.js")
require.NoError(t, err)
assert.Equal(t, "main()", string(script))
imageEnv := map[string]string{}
require.NoError(t, job.UpdateFromImageEnv(&imageEnv)(ctx))
assert.Equal(t, map[string]string{"PATH": path, "ImageOS": "ubuntu24-arm64"}, imageEnv)
@@ -361,6 +385,16 @@ func TestKubernetesCopiesUncompressedWithoutGzip(t *testing.T) {
require.NoError(t, err)
assert.Equal(t, "main()", string(script))
assert.NotContains(t, cluster.requests["exec"][len(cluster.requests["exec"])-1], "gzip")
gzipArchive := kubernetesTestTarGz(t, &FileEntry{Name: "index.js", Mode: 0o644, Body: "main()"})
require.NoError(t, pod.job.ExtractTarGz(workdir+"/act/cached", gzipArchive)(ctx))
inputs := cluster.requests["exec-stdin"]
header, err := tar.NewReader(strings.NewReader(inputs[len(inputs)-1])).Next()
require.NoError(t, err)
assert.Equal(t, "index.js", header.Name)
script, err = os.ReadFile(workdir + "/act/cached/index.js")
require.NoError(t, err)
assert.Equal(t, "main()", string(script))
}
func TestKubernetesPodFailsBeforeSteps(t *testing.T) {

View File

@@ -110,7 +110,7 @@ func startTransferServer(host string, port uint16) (*transferServer, error) {
return server, nil
}
// offer serves write once to one of clients until done, which reports whether a client took it and what write failed with.
// offer serves a gzip stream once to one of clients until done, which reports whether a client took it and what write failed with.
func (s *transferServer) offer(clients []net.IP, write func(io.Writer) error) (request transferRequest, done func() (taken bool, err error)) {
token := rand.Text()
result := make(chan error, 1)
@@ -146,7 +146,7 @@ func (s *transferServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
return
}
w.Header().Set("Content-Encoding", "gzip")
err := writeGzip(w, offer.write)
err := offer.write(w)
offer.result <- err
if err != nil {
panic(http.ErrAbortHandler) // a cut-off body fails the fetch, a short tar might not

View File

@@ -56,12 +56,20 @@ func TestTransferServer(t *testing.T) {
loopback := []net.IP{net.ParseIP("127.0.0.1")}
nothing := func(io.Writer) error { return nil }
t.Run("serves an offer gzipped once to an IP of its job pod", func(t *testing.T) {
request, done := server.offer([]net.IP{net.ParseIP("fd00::1"), loopback[0]}, nothing)
t.Run("serves gzipped bytes unchanged and only once to an IP of its job pod", func(t *testing.T) {
var archive bytes.Buffer
require.NoError(t, writeGzip(&archive, nothing))
request, done := server.offer([]net.IP{net.ParseIP("fd00::1"), loopback[0]}, func(writer io.Writer) error {
_, err := writer.Write(archive.Bytes())
return err
})
client := &http.Client{Transport: &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, DisableCompression: true}}
response, err := client.Get(request.URL)
require.NoError(t, err)
body, err := io.ReadAll(response.Body)
require.NoError(t, response.Body.Close())
require.NoError(t, err)
assert.Equal(t, archive.Bytes(), body)
assert.Equal(t, "gzip", response.Header.Get("Content-Encoding"))
require.ErrorContains(t, fetch(t, request), "404")
taken, _ := done()
@@ -76,10 +84,12 @@ func TestTransferServer(t *testing.T) {
})
t.Run("a failed write fails the fetch even past the end blocks tar stops at, and done reports it", func(t *testing.T) {
request, done := server.offer(loopback, func(w io.Writer) error {
_, _ = w.Write(make([]byte, 1024))
_, _ = io.CopyN(w, rand.Reader, 1<<20)
return errors.New("source gone")
request, done := server.offer(loopback, func(writer io.Writer) error {
return writeGzip(writer, func(compressed io.Writer) error {
_, _ = compressed.Write(make([]byte, 1024))
_, _ = io.CopyN(compressed, rand.Reader, 1<<20)
return errors.New("source gone")
})
})
require.Error(t, fetch(t, request))
taken, err := done()
@@ -164,6 +174,13 @@ func TestKubernetesPodCopiesLargeFilesOverPodNetwork(t *testing.T) {
assert.Contains(t, lastExec(), "command="+KubernetesTransferCommand)
assert.NotContains(t, lastExec(), "127.0.0.1")
archive := kubernetesTestTarGz(t, large)
require.NoError(t, pod.job.ExtractTarGz(filepath.Join(workdir, "cached"), archive)(ctx))
assert.Contains(t, lastExec(), "command="+KubernetesTransferCommand)
content, err = os.ReadFile(filepath.Join(workdir, "cached", "large"))
require.NoError(t, err)
assert.Equal(t, large.Body, string(content))
require.NoError(t, job.Copy(workdir+"/act/", &FileEntry{Name: "event.json", Mode: 0o644, Body: `{}`})(ctx))
assert.NotContains(t, lastExec(), "command="+KubernetesTransferCommand)
@@ -179,7 +196,7 @@ func TestKubernetesPodCopiesLargeFilesOverPodNetwork(t *testing.T) {
assert.NoFileExists(t, filepath.Join(workdir, "direct", "large"))
pod.options.Transfer.Fallback = true
require.NoError(t, copyLarge("auto"))
require.NoError(t, pod.job.ExtractTarGz(filepath.Join(workdir, "auto"), archive)(ctx))
assert.FileExists(t, filepath.Join(workdir, "auto", "large"))
assert.Empty(t, pod.transferHelper)
}

View File

@@ -28,6 +28,8 @@ import (
_ "embed"
"gitea.dev/actionslib/pkg/expreval"
"gitea.dev/actionslib/pkg/exprparser"
"gitea.dev/actionslib/pkg/model"
"github.com/kballard/go-shellquote"
)
@@ -36,7 +38,7 @@ type actionStep interface {
step
getActionModel() *model.Action
getCompositeRunContext(context.Context) (*RunContext, error)
getCompositeRunContext(ctx context.Context, inputs map[string]string) *RunContext
getCompositeSteps() *compositeSteps
}
@@ -46,7 +48,7 @@ type actionYamlReader func(filename string) (io.Reader, io.Closer, error)
type fileWriter func(filename string, data []byte, perm fs.FileMode) error
type runAction func(step actionStep, actionDir string, remoteAction *remoteAction) common.Executor
type runAction func(step actionStep) common.Executor
//go:embed res/trampoline.js
var trampoline string
@@ -59,77 +61,49 @@ var (
)
func readActionImpl(ctx context.Context, step *model.Step, actionDir, actionPath string, readFile actionYamlReader, writeFile fileWriter) (*model.Action, error) {
logger := common.Logger(ctx)
allErrors := []error{}
addError := func(fileName string, err error) {
var readErrors []error
for _, filename := range []string{"action.yml", "action.yaml", "Dockerfile", "dockerfile"} {
manifest := strings.HasPrefix(filename, "action.")
reader, closer, err := readFile(filename)
if err != nil {
allErrors = append(allErrors, fmt.Errorf("failed to read '%s' from action '%s' with path '%s' of step %w", fileName, step.String(), actionPath, err))
} else {
// One successful read, clear error state
allErrors = nil
}
}
reader, closer, err := readFile("action.yml")
addError("action.yml", err)
if os.IsNotExist(err) {
reader, closer, err = readFile("action.yaml")
addError("action.yaml", err)
if os.IsNotExist(err) {
dockerfile := "Dockerfile"
_, closer, err := readFile(dockerfile)
addError(dockerfile, err)
readErrors = append(readErrors, fmt.Errorf("failed to read '%s' from action '%s' with path '%s' of step %w", filename, step.String(), actionPath, err))
if os.IsNotExist(err) {
dockerfile = "dockerfile"
_, closer, err = readFile(dockerfile)
addError(dockerfile, err)
continue
}
if err == nil {
closer.Close()
action := &model.Action{
Name: "(Synthetic)",
Runs: model.ActionRuns{
Using: "docker",
Image: dockerfile,
},
}
logger.Debugf("Using synthetic action %v for %s", action, dockerfile)
return action, nil
}
if val, ok := step.With["args"]; ok {
if err := writeFile(filepath.Join(actionDir, actionPath, "trampoline.js"), []byte(trampoline), 0o644); err != nil {
return nil, err
}
action := &model.Action{
Name: "(Synthetic)",
Inputs: map[string]model.Input{
"args": {},
"cwd": {
Description: "(Actual working directory)",
Required: false,
Default: filepath.Join(actionDir, actionPath),
},
"command": {
Description: "(Actual program)",
Required: false,
Default: val,
},
},
Runs: model.ActionRuns{
Using: "node12",
Main: "trampoline.js",
},
}
logger.Debugf("Using synthetic action %v", action)
return action, nil
if manifest {
return nil, errors.Join(readErrors...)
}
break
}
defer closer.Close()
if manifest {
action, err := model.ReadAction(reader)
if err != nil {
return nil, &fs.PathError{Op: "Failed to load", Path: filepath.Join(actionDir, actionPath, filename), Err: err}
}
return action, nil
}
action := &model.Action{Name: "(Synthetic)", Runs: model.ActionRuns{Using: model.ActionRunsUsingDocker, Image: filename}}
common.Logger(ctx).Debugf("Using synthetic action %v for %s", action, filename)
return action, nil
}
if allErrors != nil {
return nil, errors.Join(allErrors...)
if val, ok := step.With["args"]; ok {
if err := writeFile(filepath.Join(actionDir, actionPath, "trampoline.js"), []byte(trampoline), 0o644); err != nil {
return nil, err
}
action := &model.Action{
Name: "(Synthetic)",
Inputs: map[string]model.Input{
"args": {},
"cwd": {Description: "(Actual working directory)", Default: filepath.Join(actionDir, actionPath)},
"command": {Description: "(Actual program)", Default: val},
},
Runs: model.ActionRuns{Using: model.ActionRunsUsingNode12, Main: "trampoline.js"},
}
common.Logger(ctx).Debugf("Using synthetic action %v", action)
return action, nil
}
defer closer.Close()
return model.ReadAction(reader)
return nil, errors.Join(readErrors...)
}
func maybeCopyToActionDir(ctx context.Context, step actionStep, actionDir, actionPath, containerActionDir string) error {
@@ -167,84 +141,84 @@ func maybeCopyToActionDir(ctx context.Context, step actionStep, actionDir, actio
return rc.JobContainer.Copy(containerActionDirCopy, patched...)(ctx)
}
func runActionImpl(step actionStep, actionDir string, remoteAction *remoteAction) common.Executor {
rc := step.getRunContext()
stepModel := step.getStepModel()
func runActionImpl(step actionStep) common.Executor {
return func(ctx context.Context) error {
logger := common.Logger(ctx)
actionPath := ""
if remoteAction != nil {
actionPath = remoteAction.Path
}
action := step.getActionModel()
rc := step.getRunContext()
rc.withGithubEnv(ctx, getStepGithubContext(ctx, step), *step.getEnv())
populateEnvsFromSavedState(step.getEnv(), step, rc)
if err := populateEnvsFromInput(ctx, step, action); err != nil {
return err
}
warnUnexpectedInputs(ctx, action, stepModel.With)
printRunActionHeader(ctx, stepModel, action, *step.getEnv(), rc)
actionName, containerActionDir := getContainerActionPaths(step)
logger.Debugf("type=%v actionDir=%s actionPath=%s workdir=%s actionCacheDir=%s actionName=%s containerActionDir=%s", stepModel.Type(), actionDir, actionPath, rc.Config.Workdir, rc.ActionCacheDir(), actionName, containerActionDir)
x := action.Runs.Using
switch {
case x.IsNode():
if err := maybeCopyToActionDir(ctx, step, actionDir, actionPath, containerActionDir); err != nil {
return err
}
containerArgs := nodeActionCommand(container.JoinPath(containerActionDir, action.Runs.Main))
logger.Debugf("executing remote job container: %s", containerArgs)
rc.ApplyExtraPath(ctx, step.getEnv())
return rc.JobContainer.Exec(containerArgs, *step.getEnv(), "", "")(ctx)
case x.IsDocker():
location := path.Join(actionDir, actionPath)
if remoteAction == nil {
location = containerActionDir
}
return execAsDocker(ctx, step, actionName, actionDir, location, remoteAction == nil, stepStageMain)
case x.IsComposite():
if err := maybeCopyToActionDir(ctx, step, actionDir, actionPath, containerActionDir); err != nil {
return err
}
return execAsComposite(step)(ctx)
case x == model.ActionRunsUsingGo:
if err := maybeCopyToActionDir(ctx, step, actionDir, actionPath, containerActionDir); err != nil {
return err
}
rc.ApplyExtraPath(ctx, step.getEnv())
execFileName := action.Runs.Main + ".out"
return common.NewPipelineExecutor(
rc.JobContainer.Exec([]string{"go", "build", "-o", execFileName, action.Runs.Main}, *step.getEnv(), "", containerActionDir),
rc.JobContainer.Exec([]string{container.JoinPath(containerActionDir, execFileName)}, *step.getEnv(), "", ""),
)(ctx)
default:
return fmt.Errorf("the runs.using key must be one of: %v, got %s", []string{
model.ActionRunsUsingDocker,
model.ActionRunsUsingNode12,
model.ActionRunsUsingNode16,
model.ActionRunsUsingNode20,
model.ActionRunsUsingNode24,
model.ActionRunsUsingComposite,
model.ActionRunsUsingGo,
}, action.Runs.Using)
}
return runActionStage(ctx, step, stepStageMain)
}
}
func runActionStage(ctx context.Context, step actionStep, stage stepStage) error {
rc := step.getRunContext()
stepModel := step.getStepModel()
action := step.getActionModel()
inputs, err := rc.resolveActionInputs(ctx, step, action)
if err != nil {
return err
}
applyActionInputs(step, inputs)
if stage == stepStageMain {
warnUnexpectedInputs(ctx, action, stepModel.With)
}
if stage == stepStagePost {
populateEnvsFromSavedState(step.getEnv(), step, rc)
} else {
printRunActionHeader(ctx, stepModel, action, *step.getEnv(), rc)
}
actionDir, actionPath := actionSourcePaths(step)
actionName, containerActionDir := getContainerActionPaths(step)
if stage == stepStageMain {
common.Logger(ctx).Debugf("type=%v actionDir=%s actionPath=%s workdir=%s actionCacheDir=%s actionName=%s containerActionDir=%s", stepModel.Type(), actionDir, actionPath, rc.Config.Workdir, rc.ActionCacheDir(), actionName, containerActionDir)
}
using := action.Runs.Using
switch {
case using.IsDocker():
return execAsDocker(ctx, step, stage, inputs, actionName, containerActionDir)
case using.IsNode(), using.IsComposite(), using == model.ActionRunsUsingGo:
if stage != stepStagePost {
if err := maybeCopyToActionDir(ctx, step, actionDir, actionPath, containerActionDir); err != nil {
return err
}
}
if using.IsComposite() {
return execAsComposite(ctx, step, inputs)
}
return runActionScript(ctx, step, containerActionDir, [...]string{action.Runs.Pre, action.Runs.Main, action.Runs.Post}[stage])
default:
return fmt.Errorf("the runs.using key must be one of: %v, got %s", []string{
model.ActionRunsUsingDocker,
model.ActionRunsUsingNode12,
model.ActionRunsUsingNode16,
model.ActionRunsUsingNode20,
model.ActionRunsUsingNode24,
model.ActionRunsUsingComposite,
model.ActionRunsUsingGo,
}, using)
}
}
func runActionScript(ctx context.Context, step actionStep, actionDir, script string) error {
rc := step.getRunContext()
env := step.getEnv()
rc.ApplyExtraPath(ctx, env)
if step.getActionModel().Runs.Using.IsNode() {
args := nodeActionCommand(rc.node(ctx), container.JoinPath(actionDir, script))
common.Logger(ctx).Debugf("executing remote job container: %s", args)
return rc.JobContainer.Exec(args, *env, "", "")(ctx)
}
executable := script + ".out"
return common.NewPipelineExecutor(
rc.JobContainer.Exec([]string{"go", "build", "-o", executable, script}, *env, "", actionDir),
rc.JobContainer.Exec([]string{container.JoinPath(actionDir, executable)}, *env, "", ""),
)(ctx)
}
// /var/run is a symlink, so without the flag node's import.meta.url differs from argv[1], which ESM actions compare.
func nodeActionCommand(script string) []string {
return []string{"node", "--preserve-symlinks-main", script}
func nodeActionCommand(node, script string) []string {
return []string{node, "--preserve-symlinks-main", script}
}
// dockerActionImageTag derives the local docker image tag used when an action
@@ -291,115 +265,76 @@ func (rc *RunContext) dockerActionImage(ctx context.Context, step actionStep, ac
return image
}
// TODO: break out parts of function to reduce complexicity
func execAsDocker(ctx context.Context, step actionStep, actionName, actionDir, basedir string, localAction bool, stage stepStage) error {
logger := common.Logger(ctx)
func execAsDocker(ctx context.Context, step actionStep, stage stepStage, inputs map[string]string, actionName, buildDir string) error {
rc := step.getRunContext()
if rc.isWindowsHost() {
return errWindowsHostContainer
}
action := step.getActionModel()
if rc.kubernetes {
return errKubernetesDocker
}
var prepImage common.Executor
var image string
forcePull := false
if after, ok := strings.CutPrefix(action.Runs.Image, "docker://"); ok {
image = after
// Apply forcePull only for prebuild docker images
forcePull = rc.Config.ForcePull
} else {
image = rc.dockerActionImage(ctx, step, actionName, localAction)
contextDir, fileName := filepath.Split(filepath.Join(basedir, action.Runs.Image))
anyArchExists, err := ContainerImageExistsLocally(ctx, image, "any")
if err != nil {
return err
}
correctArchExists := anyArchExists
if anyArchExists && rc.Config.ContainerArchitecture != "" && rc.Config.ContainerArchitecture != "any" {
correctArchExists, err = ContainerImageExistsLocally(ctx, image, rc.Config.ContainerArchitecture)
if err != nil {
return err
}
}
if anyArchExists && !correctArchExists {
wasRemoved, err := container.RemoveImage(ctx, image, true, true)
if err != nil {
return err
}
if !wasRemoved {
return fmt.Errorf("failed to remove image '%s'", image)
}
}
if !correctArchExists || rc.Config.ForceRebuild {
logger.Debugf("image '%s' for architecture '%s' will be built from context '%s", image, rc.Config.ContainerArchitecture, contextDir)
prepImage = common.Executor(func(ctx context.Context) error {
input := container.NewDockerBuildExecutorInput{
ContextDir: contextDir,
Dockerfile: fileName,
ImageTag: image,
Platform: rc.Config.ContainerArchitecture,
BuildArgs: rc.proxyBuildArgs(),
Stdout: common.NewLineWriter(rawLogLine(ctx)),
}
if localAction {
input.Dockerignore, _ = readSingleFileFromContainerArchive(ctx, rc.JobContainer, contextDir+"/.dockerignore", 1<<20)
buildContext, err := rc.JobContainer.GetContainerArchive(ctx, contextDir+"/.")
if err != nil {
return err
}
defer buildContext.Close()
input.BuildContext = buildContext
} else {
unlock, err := git.AcquireCloneLock(ctx, actionDir) // held across the whole build, the daemon drains contextDir lazily
if err != nil {
return err
}
defer unlock()
}
return ContainerNewDockerBuildExecutor(input)(ctx)
}).Retry(3)
} else {
logger.Debugf("image '%s' for architecture '%s' already exists", image, rc.Config.ContainerArchitecture)
}
action := step.getActionModel()
remote, isRemote := step.(*stepActionRemote)
image, prebuilt := strings.CutPrefix(action.Runs.Image, "docker://")
if !prebuilt {
image = rc.dockerActionImage(ctx, step, actionName, !isRemote)
}
ee, err := evalDockerEnv(ctx, step, action)
cmd, err := evalDockerArgsAndEnv(ctx, step, action, inputs)
if err != nil {
return err
}
var cmd []string
if action.Runs.Args != nil {
// a fresh slice, the manifest is evaluated again for every stage
cmd = make([]string, len(action.Runs.Args))
for i, v := range action.Runs.Args {
if cmd[i], err = ee.Interpolate(ctx, v); err != nil {
return fmt.Errorf("unable to interpolate runs.args: %w", err)
}
}
} else {
cmd, err = shellquote.Split(stepInput(step.getStepModel(), "args"))
if err != nil {
return err
}
}
entrypoint, err := dockerEntrypoint(step, stage)
if err != nil {
return err
}
stepContainer := newStepContainer(ctx, step, image, cmd, entrypoint, rc.Config.ContainerOptions)
return common.NewPipelineExecutor(
prepImage,
stepContainer.Pull(forcePull),
stepContainer.Remove(),
stepContainer.Create(rc.Config.ContainerCapAdd, rc.Config.ContainerCapDrop),
stepContainer.Start(true),
).Finally(stepContainer.Close())(ctx)
containerInput := stepContainerInput(ctx, step, image, cmd, entrypoint, rc.Config.ContainerOptions)
stepContainer := ContainerNewContainer(containerInput)
if prebuilt {
return rc.runStepContainer(ctx, stepContainer, nil, rc.Config.ForcePull)
}
platform := containerInput.Platform
exists, err := ContainerImageExistsLocally(ctx, image, platform)
if err != nil {
return err
}
if exists && !rc.Config.ForceRebuild {
common.Logger(ctx).Debugf("image '%s' for architecture '%s' already exists", image, platform)
return rc.runStepContainer(ctx, stepContainer, nil, false)
}
if isRemote {
buildDir = path.Join(remote.actionDir, remote.remoteAction.Path)
}
contextDir, filename := filepath.Split(filepath.Join(buildDir, action.Runs.Image))
common.Logger(ctx).Debugf("image '%s' for architecture '%s' will be built from context '%s'", image, platform, contextDir)
buildImage := common.Executor(func(ctx context.Context) error {
input := container.NewDockerBuildExecutorInput{
ContextDir: contextDir,
Dockerfile: filename,
ImageTag: image,
Platform: platform,
BuildArgs: rc.proxyBuildArgs(),
Stdout: common.NewLineWriter(rawLogLine(ctx)),
}
if isRemote {
unlock, err := git.AcquireCloneLock(ctx, remote.actionDir) // held across the whole build, the daemon drains contextDir lazily
if err != nil {
return err
}
defer unlock()
} else {
input.Dockerignore, _ = readSingleFileFromContainerArchive(ctx, rc.JobContainer, contextDir+"/.dockerignore", 1<<20)
buildContext, err := rc.JobContainer.GetContainerArchive(ctx, contextDir+"/.")
if err != nil {
return err
}
defer buildContext.Close()
input.BuildContext = buildContext
}
return ContainerNewDockerBuildExecutor(input)(ctx)
})
return rc.runStepContainer(ctx, stepContainer, buildImage.Retry(3), false)
}
// dockerEntrypoint returns the entrypoint the action's image runs with for the given
@@ -428,40 +363,31 @@ func dockerEntrypoint(step actionStep, stage stepStage) ([]string, error) {
return shellquote.Split(entrypoint)
}
// evalDockerEnv returns an evaluator bound to the environment it installed.
func evalDockerEnv(ctx context.Context, step step, action *model.Action) (*expressionEvaluator, error) {
rc := step.getRunContext()
var err error
inputs := make(map[string]string)
providedInputs := make(map[string]bool, len(step.getStepModel().With))
for key := range step.getStepModel().With {
providedInputs[strings.ToLower(key)] = true
}
eval := rc.NewStepExpressionEvaluator(ctx, step)
for k, input := range action.Inputs {
if providedInputs[strings.ToLower(k)] {
continue
}
if inputs[k], err = eval.Interpolate(ctx, input.Default); err != nil {
return nil, fmt.Errorf("unable to interpolate the default of input %s: %w", k, err)
}
}
mergeIntoMap(step, step.getEnv(), inputs, step.getStepModel().With)
ee := rc.NewActionInputsExpressionEvaluator(ctx, step)
func evalDockerArgsAndEnv(ctx context.Context, step step, action *model.Action, inputs map[string]string) ([]string, error) {
env := step.getEnv()
ee := newActionInputsExpressionEvaluator(inputs)
runsEnv := make(map[string]string, len(action.Runs.Env))
for k, v := range action.Runs.Env {
if runsEnv[k], err = ee.Interpolate(ctx, v); err != nil {
return nil, fmt.Errorf("unable to interpolate env %s: %w", k, err)
var err error
for name, expression := range action.Runs.Env {
if runsEnv[name], err = ee.Interpolate(ctx, expression); err != nil {
return nil, fmt.Errorf("unable to interpolate env %s: %w", name, err)
}
}
mergeIntoMap(step, step.getEnv(), runsEnv, maps.Clone(*step.getEnv()))
aliasGiteaEnv(*step.getEnv())
return ee, nil
*env = step.getRunContext().mergeEnv(runsEnv, *env, inputs)
aliasGiteaEnv(*env)
if action.Runs.Args == nil {
return shellquote.Split(stepInput(step.getStepModel(), "args"))
}
cmd := make([]string, len(action.Runs.Args))
for i, expression := range action.Runs.Args {
if cmd[i], err = ee.Interpolate(ctx, expression); err != nil {
return nil, fmt.Errorf("unable to interpolate runs.args: %w", err)
}
}
return cmd, nil
}
func newStepContainer(ctx context.Context, step step, image string, cmd, entrypoint []string, runnerOptions string) container.Container {
func stepContainerInput(ctx context.Context, step step, image string, cmd, entrypoint []string, runnerOptions string) *container.NewContainerInput {
rc := step.getRunContext()
logWriter := rc.commandLogWriter(ctx)
envList := make([]string, 0)
@@ -475,11 +401,11 @@ func newStepContainer(ctx context.Context, step step, image string, cmd, entrypo
envList = append(envList, rc.runnerEnv(ctx)...)
binds, mounts, _ := rc.GetBindsAndMounts(ctx)
networkMode := "container:" + rc.jobContainerName()
networkMode := rc.topLevelRunContext().jobNetworkName
if rc.IsHostEnv() {
networkMode = "default"
}
return ContainerNewContainer(&container.NewContainerInput{
return &container.NewContainerInput{
Cmd: cmd,
Entrypoint: entrypoint,
WorkingDir: rc.JobContainer.ToContainerPath(rc.Config.Workdir),
@@ -498,7 +424,7 @@ func newStepContainer(ctx context.Context, step step, image string, cmd, entrypo
AutoRemove: true,
ValidVolumes: rc.validVolumes(),
AllocatePTY: rc.Config.AllocatePTY,
})
}
}
func populateEnvsFromSavedState(env *map[string]string, step actionStep, rc *RunContext) {
@@ -511,19 +437,30 @@ func inputEnvKey(inputID string) string {
return "INPUT_" + inputEnvPattern.ReplaceAllString(strings.ToUpper(inputID), "_")
}
func populateEnvsFromInput(ctx context.Context, step step, action *model.Action) error {
env := step.getEnv()
eval := step.getRunContext().NewStepExpressionEvaluator(ctx, step)
for inputID, input := range action.Inputs {
envKey := inputEnvKey(inputID)
if _, ok := (*env)[envKey]; !ok {
func (rc *RunContext) resolveActionInputs(ctx context.Context, step step, action *model.Action) (map[string]string, error) {
provided := step.getStepModel().With
inputs := mergeMaps(provided)
var evaluator *expressionEvaluator
eval := expreval.New(func(expression string, statusCheck exprparser.DefaultStatusCheck) (any, error) {
if evaluator == nil {
evaluator = &expressionEvaluator{interpreter: exprparser.NewInterpeter(
rc.actionDefaultEnvironment(ctx, getStepGithubContext(ctx, step), rc.getJobContext()), exprparser.Config{Context: "step"})}
}
return evaluator.evaluate(ctx, expression, statusCheck)
})
for name, input := range action.Inputs {
if _, ok := common.LookupFold(provided, name, true); !ok {
var err error
if (*env)[envKey], err = eval.Interpolate(ctx, input.Default); err != nil {
return fmt.Errorf("unable to interpolate the default of input %s: %w", inputID, err)
if inputs[name], err = eval.Interpolate(input.Default); err != nil {
return nil, fmt.Errorf("unable to interpolate the default of input %s: %w", name, err)
}
}
}
return nil
return inputs, nil
}
func applyActionInputs(step step, inputs map[string]string) {
mergeIntoMap(step, step.getEnv(), (&model.Step{With: inputs}).GetEnv())
}
func stepInput(step *model.Step, name string) string {
@@ -588,108 +525,18 @@ func shouldRunPreStep(step actionStep) common.Conditional {
func hasPreStep(step actionStep) common.Conditional {
return func(ctx context.Context) bool {
action := step.getActionModel()
// a pre stage evaluates `with` before earlier steps run, so only a composite nesting actions gets one
return (action.Runs.Using.IsComposite() && slices.ContainsFunc(action.Runs.Steps, func(compositeStep model.Step) bool { return compositeStep.Uses != "" })) ||
(action.Runs.Using.IsNode() &&
action.Runs.Pre != "") ||
(action.Runs.Using.IsDocker() &&
action.Runs.PreEntrypoint != "") ||
(action.Runs.Using == model.ActionRunsUsingGo &&
action.Runs.Pre != "")
runs := &step.getActionModel().Runs
return (runs.Using.IsComposite() && slices.ContainsFunc(runs.Steps, func(child model.Step) bool { return child.Uses != "" })) || // pre evaluates with before preceding steps produce outputs
(runs.Using.IsDocker() && runs.PreEntrypoint != "") ||
((runs.Using.IsNode() || runs.Using == model.ActionRunsUsingGo) && runs.Pre != "")
}
}
// actionStagePaths resolves where a step's action lives and where the job container sees
// it, for the pre and post stage.
func actionStagePaths(step actionStep) (actionDir, actionPath, actionName, containerActionDir string) {
rc := step.getRunContext()
stepModel := step.getStepModel()
func actionSourcePaths(step actionStep) (actionDir, actionPath string) {
if sar, ok := step.(*stepActionRemote); ok {
actionDir = sar.actionDir
actionPath = sar.remoteAction.Path
return sar.actionDir, sar.remoteAction.Path
} else {
actionDir = filepath.Join(rc.Config.Workdir, stepModel.Uses)
}
actionName, containerActionDir = getContainerActionPaths(step)
return actionDir, actionPath, actionName, containerActionDir
}
// execDockerActionStage runs a docker action's image for its pre or post stage.
func execDockerActionStage(ctx context.Context, step actionStep, stage stepStage) error {
actionDir, actionPath, actionName, containerActionDir := actionStagePaths(step)
_, remote := step.(*stepActionRemote)
location := containerActionDir
if remote {
location = path.Join(actionDir, actionPath)
}
return execAsDocker(ctx, step, actionName, actionDir, location, !remote, stage)
}
func runPreStep(step actionStep) common.Executor {
return func(ctx context.Context) error {
logger := common.Logger(ctx)
logger.Debugf("run pre step for '%s'", step.getStepModel())
rc := step.getRunContext()
action := step.getActionModel()
actionDir, actionPath, _, containerActionDir := actionStagePaths(step)
x := action.Runs.Using
if !x.IsComposite() {
// defaults in pre steps were missing, however provided inputs are available
if err := populateEnvsFromInput(ctx, step, action); err != nil {
return err
}
}
printRunActionHeader(ctx, step.getStepModel(), action, *step.getEnv(), rc)
switch {
case x.IsNode():
if err := maybeCopyToActionDir(ctx, step, actionDir, actionPath, containerActionDir); err != nil {
return err
}
containerArgs := nodeActionCommand(container.JoinPath(containerActionDir, action.Runs.Pre))
logger.Debugf("executing remote job container: %s", containerArgs)
rc.ApplyExtraPath(ctx, step.getEnv())
return rc.JobContainer.Exec(containerArgs, *step.getEnv(), "", "")(ctx)
case x.IsDocker():
return execDockerActionStage(ctx, step, stepStagePre)
case x.IsComposite():
if step.getCompositeSteps() == nil {
if _, err := step.getCompositeRunContext(ctx); err != nil {
return err
}
}
if steps := step.getCompositeSteps(); steps != nil && steps.pre != nil {
return steps.pre(ctx)
}
return errors.New("missing steps in composite action")
case x == model.ActionRunsUsingGo:
if err := maybeCopyToActionDir(ctx, step, actionDir, actionPath, containerActionDir); err != nil {
return err
}
rc.ApplyExtraPath(ctx, step.getEnv())
execFileName := action.Runs.Pre + ".out"
return common.NewPipelineExecutor(
rc.JobContainer.Exec([]string{"go", "build", "-o", execFileName, action.Runs.Pre}, *step.getEnv(), "", containerActionDir),
rc.JobContainer.Exec([]string{container.JoinPath(containerActionDir, execFileName)}, *step.getEnv(), "", ""),
)(ctx)
default:
return nil
}
return filepath.Join(step.getRunContext().Config.Workdir, step.getStepModel().Uses), ""
}
}
@@ -723,70 +570,45 @@ func shouldRunPostStep(step actionStep) common.Conditional {
func hasPostStep(step actionStep) common.Conditional {
return func(ctx context.Context) bool {
action := step.getActionModel()
return action.Runs.Using.IsComposite() ||
(action.Runs.Using.IsNode() &&
action.Runs.Post != "") ||
(action.Runs.Using.IsDocker() &&
action.Runs.PostEntrypoint != "") ||
(action.Runs.Using == model.ActionRunsUsingGo &&
action.Runs.Post != "")
runs := &step.getActionModel().Runs
return runs.Using.IsComposite() || (runs.Using.IsDocker() && runs.PostEntrypoint != "") ||
((runs.Using.IsNode() || runs.Using == model.ActionRunsUsingGo) && runs.Post != "")
}
}
func runPostStep(step actionStep) common.Executor {
func runActionHook(step actionStep, stage stepStage) common.Executor {
return func(ctx context.Context) error {
logger := common.Logger(ctx)
logger.Debugf("run post step for '%s'", step.getStepModel())
logger.Debugf("run %s step for '%s'", strings.ToLower(stage.String()), step.getStepModel())
rc := step.getRunContext()
action := step.getActionModel()
actionDir, actionPath, _, containerActionDir := actionStagePaths(step)
x := action.Runs.Using
if !x.IsComposite() { // a composite's children print their own
logger.With(rawOutputField, true).Info("Post job cleanup.")
if !step.getActionModel().Runs.Using.IsComposite() {
if stage == stepStagePost {
logger.With(rawOutputField, true).Info("Post job cleanup.")
}
return runActionStage(ctx, step, stage)
}
switch {
case x.IsNode():
populateEnvsFromSavedState(step.getEnv(), step, rc)
containerArgs := nodeActionCommand(container.JoinPath(containerActionDir, action.Runs.Post))
logger.Debugf("executing remote job container: %s", containerArgs)
rc.ApplyExtraPath(ctx, step.getEnv())
return rc.JobContainer.Exec(containerArgs, *step.getEnv(), "", "")(ctx)
case x.IsDocker():
populateEnvsFromSavedState(step.getEnv(), step, rc)
return execDockerActionStage(ctx, step, stepStagePost)
case x.IsComposite():
if stage == stepStagePre {
rc := step.getRunContext()
printRunActionHeader(ctx, step.getStepModel(), step.getActionModel(), *step.getEnv(), rc)
inputs, err := rc.resolveActionInputs(ctx, step, step.getActionModel())
if err != nil {
return err
}
step.getCompositeRunContext(ctx, inputs)
if pre := step.getCompositeSteps().pre; pre != nil {
return pre(ctx)
}
} else {
actionDir, actionPath := actionSourcePaths(step)
_, containerActionDir := getContainerActionPaths(step)
if err := maybeCopyToActionDir(ctx, step, actionDir, actionPath, containerActionDir); err != nil {
return err
}
if steps := step.getCompositeSteps(); steps != nil && steps.post != nil {
return steps.post(ctx)
}
return errors.New("missing steps in composite action")
case x == model.ActionRunsUsingGo:
populateEnvsFromSavedState(step.getEnv(), step, rc)
rc.ApplyExtraPath(ctx, step.getEnv())
execFileName := action.Runs.Post + ".out"
return common.NewPipelineExecutor(
rc.JobContainer.Exec([]string{"go", "build", "-o", execFileName, action.Runs.Post}, *step.getEnv(), "", containerActionDir),
rc.JobContainer.Exec([]string{container.JoinPath(containerActionDir, execFileName)}, *step.getEnv(), "", ""),
)(ctx)
default:
return nil
}
return errors.New("missing steps in composite action")
}
}

View File

@@ -8,6 +8,7 @@ import (
"context"
"errors"
"fmt"
"maps"
"slices"
"strconv"
"strings"
@@ -17,65 +18,18 @@ import (
"gitea.dev/actionslib/pkg/model"
)
func evaluateCompositeInputAndEnv(ctx context.Context, parent *RunContext, step actionStep) (map[string]string, error) {
env := make(map[string]string)
stepEnv := *step.getEnv()
for k, v := range stepEnv {
// do not set current inputs into composite action
// the required inputs are added in the second loop
if !strings.HasPrefix(k, "INPUT_") {
env[k] = v
}
func (rc *RunContext) setCompositeActionEnv(stepEnv, inputs map[string]string) {
isInput := func(key, _value string) bool { return strings.HasPrefix(key, "INPUT_") }
env := maps.Clone(stepEnv)
maps.DeleteFunc(env, isInput)
for name, value := range inputs {
env[inputEnvKey(name)] = value
}
ee := parent.NewStepExpressionEvaluator(ctx, step)
for inputID, input := range step.getActionModel().Inputs {
envKey := inputEnvKey(inputID)
// lookup if key is defined in the step but the already
// evaluated value from the environment
defined := false
for key := range step.getStepModel().With {
if strings.EqualFold(key, inputID) {
defined = true
break
}
}
if value, ok := stepEnv[envKey]; defined && ok {
env[envKey] = value
} else {
// defaults could contain expressions
var err error
if env[envKey], err = ee.Interpolate(ctx, input.Default); err != nil {
return nil, fmt.Errorf("unable to interpolate the default of input %s: %w", inputID, err)
}
}
}
for envKey, value := range (&model.Step{With: step.getStepModel().With}).GetEnv() {
if _, ok := env[envKey]; !ok {
env[envKey] = value
}
}
return env, nil
}
func (rc *RunContext) setCompositeActionEnv(env map[string]string) {
rc.setActionEnv(env)
for key := range rc.Env {
if strings.HasPrefix(key, "INPUT_") {
delete(rc.Env, key)
}
}
maps.DeleteFunc(rc.Env, isInput)
}
func newCompositeRunContext(ctx context.Context, parent *RunContext, step actionStep, actionPath string) (*RunContext, error) {
env, err := evaluateCompositeInputAndEnv(ctx, parent, step)
if err != nil {
return nil, err
}
func newCompositeRunContext(ctx context.Context, parent *RunContext, step actionStep, actionPath string, inputs map[string]string) *RunContext {
// run with the global config but without secrets
configCopy := *parent.Config
configCopy.Secrets = nil
@@ -99,7 +53,7 @@ func newCompositeRunContext(ctx context.Context, parent *RunContext, step action
JobContainer: parent.JobContainer,
ActionPath: actionPath,
GlobalEnv: parent.GlobalEnv,
Masks: parent.Masks,
Masks: slices.Clip(parent.Masks),
ExtraPath: parent.ExtraPath,
Parent: parent,
EventJSON: parent.EventJSON,
@@ -109,10 +63,10 @@ func newCompositeRunContext(ctx context.Context, parent *RunContext, step action
jobTotal: parent.jobTotal,
runtimeToken: parent.runtimeToken,
}
compositerc.setCompositeActionEnv(env)
compositerc.setCompositeActionEnv(*step.getEnv(), inputs)
compositerc.ExprEval = compositerc.NewExpressionEvaluator(ctx)
return compositerc, nil
return compositerc
}
// appendUniqueMasks appends the masks from src to dst, skipping any mask that
@@ -128,56 +82,36 @@ func appendUniqueMasks(dst, src []string) []string {
return dst
}
func execAsComposite(step actionStep) common.Executor {
func execAsComposite(ctx context.Context, step actionStep, inputs map[string]string) error {
compositeRC := step.getCompositeRunContext(ctx, inputs)
ctx = WithCompositeLogger(ctx, &compositeRC.Masks)
rc := step.getRunContext()
action := step.getActionModel()
err := step.getCompositeSteps().main(ctx)
return func(ctx context.Context) error {
compositeRC, err := step.getCompositeRunContext(ctx)
if err != nil {
return err
// Map outputs from composite RunContext to job RunContext
eval := compositeRC.NewExpressionEvaluator(ctx)
for outputName, output := range step.getActionModel().Outputs {
value, outputErr := eval.Interpolate(ctx, output.Value)
if outputErr != nil {
err = errors.Join(err, fmt.Errorf("unable to interpolate output %s: %w", outputName, outputErr))
continue
}
steps := step.getCompositeSteps()
if steps == nil || steps.main == nil {
return errors.New("missing steps in composite action")
}
ctx = WithCompositeLogger(ctx, &compositeRC.Masks)
err = steps.main(ctx)
// Map outputs from composite RunContext to job RunContext
eval := compositeRC.NewExpressionEvaluator(ctx)
for outputName, output := range action.Outputs {
value, outputErr := eval.Interpolate(ctx, output.Value)
if outputErr != nil {
err = errors.Join(err, fmt.Errorf("unable to interpolate output %s: %w", outputName, outputErr))
continue
}
rc.setOutput(ctx, map[string]string{"name": outputName}, value)
}
// compositeRC.Masks is seeded with rc.Masks (see newCompositeRunContext)
// and may have additional masks appended while the composite action runs.
// Only append masks that are not already present, otherwise nested or
// repeated composite actions grow rc.Masks exponentially.
rc.Masks = appendUniqueMasks(rc.Masks, compositeRC.Masks)
rc.ExtraPath = compositeRC.ExtraPath
// Propagate GlobalEnv only, so composite inputs and step-local values do not escape.
mergeIntoMap := mergeIntoMapCaseSensitive
if rc.JobContainer.IsEnvironmentCaseInsensitive() {
mergeIntoMap = mergeIntoMapCaseInsensitive
}
if rc.GlobalEnv == nil {
rc.GlobalEnv = map[string]string{}
}
mergeIntoMap(rc.GlobalEnv, compositeRC.GlobalEnv)
mergeIntoMap(rc.Env, compositeRC.GlobalEnv)
return err
rc.setOutput(ctx, map[string]string{"name": outputName}, value)
}
rc.ExtraPath = compositeRC.ExtraPath
// Propagate GlobalEnv only, so composite inputs and step-local values do not escape.
mergeIntoMap := mergeIntoMapCaseSensitive
if rc.JobContainer.IsEnvironmentCaseInsensitive() {
mergeIntoMap = mergeIntoMapCaseInsensitive
}
if rc.GlobalEnv == nil {
rc.GlobalEnv = map[string]string{}
}
mergeIntoMap(rc.GlobalEnv, compositeRC.GlobalEnv)
mergeIntoMap(rc.Env, compositeRC.GlobalEnv)
return err
}
type compositeSteps struct {
@@ -239,6 +173,10 @@ func (rc *RunContext) compositeExecutor(action *model.Action) *compositeSteps {
func (rc *RunContext) newCompositeCommandExecutor(executor common.Executor) common.Executor {
return func(ctx context.Context) error {
if parent := rc.Parent; parent != nil { // a composite context outlives the stage it was made in, so sync masks around every step
rc.Masks = appendUniqueMasks(rc.Masks, parent.Masks)
defer func() { parent.Masks = appendUniqueMasks(parent.Masks, rc.Masks) }()
}
return rc.withCommandLogWriter(WithCompositeLogger(ctx, &rc.Masks), executor)
}
}

View File

@@ -23,7 +23,7 @@ func TestCompositeActionParity(t *testing.T) {
for _, uses := range []string{"./action", "own/action@v2"} {
t.Run(uses, func(t *testing.T) {
rc := &RunContext{
Config: &Config{PresetGitHubContext: &model.GithubContext{}},
Config: &Config{PresetGitHubContext: &model.GithubContext{}, Secrets: map[string]string{"key": "secret"}, Vars: map[string]string{"key": "var"}},
Run: &model.Run{JobID: "job", Workflow: &model.Workflow{Jobs: map[string]*model.Job{"job": {}}}},
Env: map[string]string{"GITHUB_ACTION_REPOSITORY": "other/composite", "GITHUB_ACTION_REF": "v1"},
}
@@ -34,16 +34,17 @@ func TestCompositeActionParity(t *testing.T) {
want = "own/action|v2"
}
action := &model.Action{
Inputs: map[string]model.Input{"identity": {Default: "${{ github.action_repository }}|${{ github.action_ref }}"}},
Runs: model.ActionRuns{Env: map[string]string{"GITHUB_WORKFLOW_SHA": "runs-sha"}},
Inputs: map[string]model.Input{"identity": {Default: "${{ secrets.key || vars.key || env.GITHUB_JOB || github.action_repository }}|${{ gitea.action_ref }}"}},
Runs: model.ActionRuns{Env: map[string]string{"GITHUB_WORKFLOW_SHA": "${{ env.GITHUB_JOB || inputs.identity }}"}},
}
require.NoError(t, setupEnv(t.Context(), currentStep))
require.NoError(t, populateEnvsFromInput(t.Context(), currentStep, action))
assert.Equal(t, want, (*currentStep.getEnv())["INPUT_IDENTITY"])
_, err := evalDockerEnv(t.Context(), currentStep, action)
inputs, err := rc.resolveActionInputs(t.Context(), currentStep, action)
require.NoError(t, err)
assert.Equal(t, want, inputs["identity"])
_, err = evalDockerArgsAndEnv(t.Context(), currentStep, action, inputs)
require.NoError(t, err)
assert.Equal(t, want, (*currentStep.getEnv())["identity"])
assert.Equal(t, "runs-sha", (*currentStep.getEnv())["GITEA_WORKFLOW_SHA"])
assert.Equal(t, want, (*currentStep.getEnv())["GITEA_WORKFLOW_SHA"])
})
}
})
@@ -51,12 +52,19 @@ func TestCompositeActionParity(t *testing.T) {
t.Run("inherits contexts without leaking inputs", func(t *testing.T) {
hook := logtest.NewWithLevel(logging.LevelWarn)
ctx := common.WithLogger(t.Context(), logging.New(hook))
hashCalls := 0
strategy := &model.Strategy{MaxParallelString: "3", RawMatrix: yaml.Node{Kind: yaml.MappingNode}}
parent := &RunContext{
Config: &Config{PresetGitHubContext: &model.GithubContext{}},
Matrix: map[string]any{"os": "linux"},
Run: &model.Run{JobID: "job", Workflow: &model.Workflow{Name: "workflow", Jobs: map[string]*model.Job{"job": {Strategy: strategy}}}},
JobContainer: &jobContainerMock{},
Config: &Config{PresetGitHubContext: &model.GithubContext{}},
Matrix: map[string]any{"os": "linux"},
Run: &model.Run{JobID: "job", Workflow: &model.Workflow{Name: "workflow", Jobs: map[string]*model.Job{"job": {Strategy: strategy}}}},
JobContainer: &hashFilesContainer{
ExecutionsEnvironment: &jobContainerMock{},
execute: func(_command []string, _env map[string]string, _user, _workdir string) common.Executor {
hashCalls++
return noopExecutor
},
},
platformImage: "-self-hosted",
jobIndex: 1,
jobTotal: 4,
@@ -64,27 +72,23 @@ func TestCompositeActionParity(t *testing.T) {
step := &stepActionLocal{
Step: &model.Step{Uses: "./action", With: map[string]string{"SHARED": "outer", "extra": "literal${{ github.job }}"}},
RunContext: parent,
action: &model.Action{Inputs: map[string]model.Input{"shared": {Default: "outer-default"}}, Runs: model.ActionRuns{Using: "composite"}},
env: map[string]string{"INPUT_SHARED": "outer"},
action: &model.Action{Inputs: map[string]model.Input{"shared": {}, "target region": {Default: "${{ hashFiles('region') || 'local' }}"}}, Runs: model.ActionRuns{Using: "composite"}},
env: map[string]string{"INPUT_TARGET_REGION": "inherited"},
}
require.NoError(t, runActionImpl(step, "/action", nil)(ctx))
require.NoError(t, runActionImpl(step)(ctx))
assert.Equal(t, 1, hashCalls)
require.Len(t, hook.AllRecords(), 1)
assert.Equal(t, "##[warning]Unexpected input(s) 'extra', valid inputs are ['shared']", hook.LastRecord().Message)
composite, err := step.getCompositeRunContext(ctx)
require.NoError(t, err)
assert.Equal(t, "##[warning]Unexpected input(s) 'extra', valid inputs are ['shared', 'target region']", hook.LastRecord().Message)
composite := step.compositeRunContext
assert.Same(t, strategy, composite.Run.Job().Strategy)
assert.True(t, composite.IsHostEnv())
interpolated, err := composite.NewExpressionEvaluator(ctx).Interpolate(ctx,
"${{ matrix.os }}|${{ strategy.max-parallel }}|${{ strategy.job-index }}|${{ inputs.shared }}|${{ inputs.extra }}")
"${{ matrix.os }}|${{ strategy.max-parallel }}|${{ strategy.job-index }}|${{ inputs.shared }}|${{ inputs.target_region }}|${{ inputs.extra }}")
require.NoError(t, err)
assert.Equal(t, "linux|3|1|outer|literal${{ github.job }}", interpolated)
assert.Equal(t, "linux|3|1|outer|local|literal${{ github.job }}", interpolated)
assert.NotContains(t, composite.Env, "INPUT_SHARED")
assert.NotContains(t, composite.Env, "INPUT_EXTRA")
nestedEnv := composite.GetEnv()
require.NoError(t, populateEnvsFromInput(ctx, &stepActionLocal{RunContext: composite, env: nestedEnv}, &model.Action{Inputs: map[string]model.Input{"shared": {Default: "inner-default"}}}))
assert.Equal(t, "inner-default", nestedEnv["INPUT_SHARED"])
})
t.Run("propagates pre failures", func(t *testing.T) {
@@ -100,6 +104,25 @@ func TestCompositeActionParity(t *testing.T) {
require.ErrorIs(t, rc.compositeExecutor(&model.Action{Runs: model.ActionRuns{Using: "composite", Steps: []model.Step{{ID: "nested", Uses: "org/action@v1"}}}}).pre(t.Context()), assert.AnError)
})
t.Run("composite steps of every stage share masks with the job", func(t *testing.T) {
parent := makeTestRC(t, "runs-on: ubuntu-latest")
parent.JobContainer, parent.Masks = &jobContainerMock{}, make([]string, 0, 2)
step := &stepActionRemote{Step: &model.Step{Uses: "own/action@v1"}, RunContext: parent, action: &model.Action{Runs: model.ActionRuns{Using: "composite"}}, remoteAction: mustNewRemoteAction(t, "own/action@v1")}
composite := step.getCompositeRunContext(t.Context(), nil)
require.NoError(t, composite.newCompositeCommandExecutor(func(ctx context.Context) error {
composite.AddMask(ctx, "composite-pre")
return nil
})(t.Context()))
parent.AddMask(t.Context(), "job-first")
parent.AddMask(t.Context(), "job-later")
require.NoError(t, composite.newCompositeCommandExecutor(func(ctx context.Context) error {
assert.Contains(t, composite.Masks, "job-later")
composite.AddMask(ctx, "composite-post")
return nil
})(t.Context()))
assert.ElementsMatch(t, []string{"composite-pre", "job-first", "job-later", "composite-post"}, parent.Masks)
})
t.Run("post steps log under their own step ids", func(t *testing.T) {
hook := logtest.NewWithLevel(logging.LevelDebug)
rc := &RunContext{Config: &Config{}, JobContainer: &jobContainerMock{}}
@@ -186,12 +209,10 @@ func TestCompositeStepIfReadsJobStatusExceptInItsOwnMainSteps(t *testing.T) {
}
func newTestCompositeRunContext(t *testing.T, parent *RunContext) *RunContext {
composite, err := newCompositeRunContext(t.Context(), parent, &stepActionRemote{
return newCompositeRunContext(t.Context(), parent, &stepActionRemote{
Step: &model.Step{},
RunContext: parent,
action: &model.Action{},
env: map[string]string{},
}, "/action")
require.NoError(t, err)
return composite
}, "/action", nil)
}

View File

@@ -14,15 +14,13 @@ import (
"path/filepath"
"runtime"
"strings"
"sync"
"testing"
"time"
"gitea.com/gitea/runner/act/common"
"gitea.com/gitea/runner/act/common/git"
"gitea.com/gitea/runner/act/common/logging"
"gitea.com/gitea/runner/act/common/logging/logtest"
"gitea.com/gitea/runner/act/container"
"gitea.com/gitea/runner/internal/pkg/lock"
"gitea.dev/actionslib/pkg/model"
"github.com/stretchr/testify/assert"
@@ -54,72 +52,27 @@ runs:
},
}
table := []struct {
type readerCase struct {
name string
step *model.Step
step model.Step
filename string
fileContent string
expected *model.Action
}{
{
name: "readActionYml",
step: &model.Step{},
filename: "action.yml",
fileContent: yaml,
expected: yamlAction,
},
{
name: "readActionYaml",
step: &model.Step{},
filename: "action.yaml",
fileContent: yaml,
expected: yamlAction,
},
{
name: "readDockerfile",
step: &model.Step{},
filename: "Dockerfile",
fileContent: "FROM ubuntu:20.04",
expected: &model.Action{
Name: "(Synthetic)",
Runs: model.ActionRuns{
Using: "docker",
Image: "Dockerfile",
},
},
},
{
name: "readLowercaseDockerfile",
step: &model.Step{},
filename: "dockerfile",
fileContent: "FROM ubuntu:20.04",
expected: &model.Action{
Name: "(Synthetic)",
Runs: model.ActionRuns{
Using: "docker",
Image: "dockerfile",
},
},
},
}
table := []readerCase{
{
name: "readWithArgs",
step: &model.Step{
With: map[string]string{
"args": "cmd",
},
},
step: model.Step{With: map[string]string{"args": "cmd"}},
expected: &model.Action{
Name: "(Synthetic)",
Inputs: map[string]model.Input{
"args": {},
"cwd": {
Description: "(Actual working directory)",
Required: false,
Default: filepath.Join("actionDir", "actionPath"),
},
"command": {
Description: "(Actual program)",
Required: false,
Default: "cmd",
},
},
@@ -129,6 +82,20 @@ runs:
},
},
},
{
name: "invalid manifest",
filename: "action.yaml",
fileContent: "runs: {using: node99}\n",
},
}
for _, filename := range []string{"action.yml", "action.yaml"} {
table = append(table, readerCase{name: filename, filename: filename, fileContent: yaml, expected: yamlAction})
}
for _, filename := range []string{"Dockerfile", "dockerfile"} {
table = append(table, readerCase{name: filename, filename: filename, expected: &model.Action{
Name: "(Synthetic)", Runs: model.ActionRuns{Using: "docker", Image: filename},
}})
}
for _, tt := range table {
@@ -149,12 +116,15 @@ runs:
return nil
}
action, err := readActionImpl(t.Context(), tt.step, "actionDir", "actionPath", readFile, writeFile)
require.NoError(t, err)
assert.Equal(t, tt.expected, action)
action, err := readActionImpl(t.Context(), &tt.step, "actionDir", "actionPath", readFile, writeFile)
assert.Equal(t, tt.filename != "", closed)
if tt.expected == nil {
require.ErrorContains(t, err, "Failed to load "+filepath.Join("actionDir", "actionPath", tt.filename))
return
}
require.NoError(t, err)
assert.Equal(t, tt.expected, action)
})
}
}
@@ -165,20 +135,18 @@ func TestActionRunner(t *testing.T) {
name string
inputs map[string]model.Input
with map[string]string
inherited map[string]string
state map[string]string
expectedEnv map[string]string
warning string
}{
{
name: "with-input",
inputs: map[string]model.Input{"key": {Default: "default value"}},
expectedEnv: map[string]string{"INPUT_KEY": "default value"},
},
{
name: "declared input ignores case",
inputs: map[string]model.Input{"key": {Default: "default value"}},
with: map[string]string{"KEY": "provided value"},
expectedEnv: map[string]string{"INPUT_KEY": "provided value"},
name: "input precedence and saved state across stages",
inputs: map[string]model.Input{"foo": {Default: "default"}, "key": {Default: "${{ fromJSON('') }}"}},
with: map[string]string{"KEY": "provided"},
inherited: map[string]string{"INPUT_FOO": "inherited", "INPUT_KEY": "inherited"},
state: map[string]string{"name": "state value"},
expectedEnv: map[string]string{"INPUT_FOO": "default", "INPUT_KEY": "provided", "STATE_name": "state value"},
},
{
name: "unexpected inputs warn once across stages",
@@ -191,30 +159,26 @@ func TestActionRunner(t *testing.T) {
with: map[string]string{"unknown": "value"},
warning: "##[warning]Unexpected input(s) 'unknown', valid inputs are ['']",
},
{
name: "restore-saved-state",
state: map[string]string{"name": "state value"},
expectedEnv: map[string]string{"STATE_name": "state value"},
},
} {
t.Run(tt.name, func(t *testing.T) {
hook := logtest.NewWithLevel(logging.LevelWarn)
ctx := common.WithLogger(t.Context(), logging.New(hook))
cm := &containerMock{}
containerActionDir := "/var/run/act/actions/" + model.UsesHash("/org/repo/path@ref") + "/"
cm.On("CopyDir", containerActionDir, "dir/", false, true).Return(func(_ctx context.Context) error { return nil })
cm.On("CopyDir", containerActionDir, "dir/", false, true).Return(noopExecutor)
envMatcher := mock.MatchedBy(func(env map[string]string) bool {
for k, v := range tt.expectedEnv {
if env[k] != v {
return false
for _, script := range []string{"path/pre.js", "path/main.js", "path/post.js"} {
cm.On("Exec", nodeActionCommand("node", containerActionDir+script), mock.Anything, "", "").Return(noopExecutor).Once().Run(func(args mock.Arguments) {
env := args.Get(1).(map[string]string)
for key, value := range tt.expectedEnv {
if script == "path/pre.js" && strings.HasPrefix(key, "STATE_") {
assert.NotContains(t, env, key)
} else {
assert.Equal(t, value, env[key], "%s in %s", key, script)
}
}
}
return true
})
cm.On("Exec", []string{"node", "--preserve-symlinks-main", containerActionDir + "path"}, envMatcher, "", "").Return(func(_ctx context.Context) error { return nil })
cm.On("Exec", nodeActionCommand(containerActionDir+"path/pre.js"), mock.Anything, "", "").Return(func(_ctx context.Context) error { return nil })
cm.On("Exec", nodeActionCommand(containerActionDir+"path/post.js"), envMatcher, "", "").Return(func(_ctx context.Context) error { return nil })
})
}
remoteAction := mustNewRemoteAction(t, "org/repo/path@ref")
step := &stepActionRemote{
@@ -225,15 +189,17 @@ func TestActionRunner(t *testing.T) {
IntraActionState: map[string]map[string]string{"step": tt.state},
JobContainer: cm,
},
action: &model.Action{Inputs: tt.inputs, Runs: model.ActionRuns{Using: "node16", Pre: "pre.js", Post: "post.js"}},
action: &model.Action{Inputs: tt.inputs, Runs: model.ActionRuns{Using: "node16", Pre: "pre.js", Main: "main.js", Post: "post.js"}},
actionDir: "dir",
env: (&model.Step{With: tt.with}).GetEnv(),
remoteAction: remoteAction,
}
require.NoError(t, runPreStep(step)(ctx))
assert.Empty(t, hook.AllRecords())
require.NoError(t, runActionImpl(step, "dir", remoteAction)(ctx))
require.NoError(t, runPostStep(step)(ctx))
for index, execute := range []common.Executor{runActionHook(step, stepStagePre), runActionImpl(step), runActionHook(step, stepStagePost)} {
step.env = mergeMaps(tt.inherited)
require.NoError(t, execute(ctx))
if index == 0 {
assert.Empty(t, hook.AllRecords())
}
}
if tt.warning == "" {
assert.Empty(t, hook.AllRecords())
} else {
@@ -254,7 +220,9 @@ func TestGoActionUsesLinuxExecutablePaths(t *testing.T) {
t.Run(stage, func(t *testing.T) {
cm := &containerMock{}
containerActionDir := "/var/run/act/actions/" + model.UsesHash("/org/repo@ref")
cm.On("CopyDir", containerActionDir+"/", mock.Anything, false, true).Return(noopExecutor).Maybe()
if stage != "post" {
cm.On("CopyDir", containerActionDir+"/", mock.Anything, false, true).Return(noopExecutor).Once()
}
cm.On("Exec", []string{"go", "build", "-o", stage + ".go.out", stage + ".go"}, mock.Anything, "", containerActionDir).Return(noopExecutor).Once()
cm.On("Exec", []string{containerActionDir + "/" + stage + ".go.out"}, mock.Anything, "", "").Return(noopExecutor).Once()
step := &stepActionRemote{
@@ -271,11 +239,11 @@ func TestGoActionUsesLinuxExecutablePaths(t *testing.T) {
}
switch stage {
case "main":
require.NoError(t, runActionImpl(step, step.actionDir, step.remoteAction)(t.Context()))
require.NoError(t, runActionImpl(step)(t.Context()))
case "pre":
require.NoError(t, runPreStep(step)(t.Context()))
require.NoError(t, runActionHook(step, stepStagePre)(t.Context()))
case "post":
require.NoError(t, runPostStep(step)(t.Context()))
require.NoError(t, runActionHook(step, stepStagePost)(t.Context()))
}
cm.AssertExpectations(t)
})
@@ -303,247 +271,59 @@ if (process.argv[1] !== self) {
require.NoError(t, os.Symlink(actionDir, symlinkedActionDir))
symlinkedEntrypoint := filepath.Join(symlinkedActionDir, "index.mjs")
args := nodeActionCommand(symlinkedEntrypoint)
args := nodeActionCommand("node", symlinkedEntrypoint)
output, err := exec.CommandContext(t.Context(), args[0], args[1:]...).CombinedOutput()
require.NoError(t, err, "%s", output)
}
func TestNewStepContainerDoesNotUseDockerSecrets(t *testing.T) {
cm := &containerMock{}
var captured *container.NewContainerInput
origContainerNewContainer := ContainerNewContainer
ContainerNewContainer = func(input *container.NewContainerInput) container.ExecutionsEnvironment {
captured = input
return cm
}
defer func() {
ContainerNewContainer = origContainerNewContainer
}()
ctx := t.Context()
rc := &RunContext{
Name: "job",
Config: &Config{
Secrets: map[string]string{
"DOCKER_USERNAME": "docker-user",
"DOCKER_PASSWORD": "docker-password",
},
},
Run: &model.Run{
JobID: "job",
Workflow: &model.Workflow{
Name: "test",
Jobs: map[string]*model.Job{
"job": {},
},
},
},
JobContainer: cm,
StepResults: map[string]*model.StepResult{},
}
env := map[string]string{}
step := &stepMock{}
step.On("getRunContext").Return(rc)
step.On("getStepModel").Return(&model.Step{ID: "action"})
step.On("getEnv").Return(&env)
newStepContainer(ctx, step, "registry.example.com/action:tag", nil, nil, "")
assert.Empty(t, captured.Username)
assert.Empty(t, captured.Password)
assert.True(t, captured.AutoRemove)
step.AssertExpectations(t)
}
func TestMaybeCopyToActionDirHoldsCloneLock(t *testing.T) {
ctx := t.Context()
actionDir := t.TempDir()
releaseCopy := make(chan struct{})
release := sync.OnceFunc(func() { close(releaseCopy) })
defer release()
copyEntered := make(chan struct{})
cm := &containerMock{}
cm.On("CopyDir", "/var/run/act/actions/", actionDir+"/", false, true).Return(func(ctx context.Context) error {
close(copyEntered)
<-releaseCopy
cm.On("CopyDir", "/var/run/act/actions/", actionDir+"/", false, true).Return(func(context.Context) error {
_, err := lock.TryLock(actionDir)
assert.ErrorIs(t, err, lock.ErrLocked)
return nil
})
step := &stepActionRemote{Step: &model.Step{Uses: "remote/action@v1"}, RunContext: &RunContext{Config: &Config{}, JobContainer: cm}}
step := &stepActionRemote{
Step: &model.Step{Uses: "remote/action@v1"},
RunContext: &RunContext{
Config: &Config{},
JobContainer: cm,
},
}
copyDone := make(chan error, 1)
go func() {
copyDone <- maybeCopyToActionDir(ctx, step, actionDir, "", "/var/run/act/actions/")
}()
select {
case <-copyEntered:
case err := <-copyDone:
t.Fatalf("maybeCopyToActionDir returned before CopyDir was entered: %v", err)
case <-time.After(time.Second):
t.Fatal("CopyDir was not entered within 1 second")
}
peerAcquired := make(chan struct{})
go func() {
unlock, err := git.AcquireCloneLock(t.Context(), actionDir)
if !assert.NoError(t, err) {
return
}
close(peerAcquired)
unlock()
}()
select {
case <-peerAcquired:
t.Fatal("peer AcquireCloneLock returned while CopyDir was running")
case <-time.After(50 * time.Millisecond):
}
release()
select {
case err := <-copyDone:
if err != nil {
t.Fatalf("maybeCopyToActionDir returned error: %v", err)
}
case <-time.After(time.Second):
t.Fatal("maybeCopyToActionDir did not return after CopyDir was unblocked")
}
select {
case <-peerAcquired:
case <-time.After(time.Second):
t.Fatal("peer AcquireCloneLock did not proceed after lock released")
}
require.NoError(t, maybeCopyToActionDir(t.Context(), step, actionDir, "", "/var/run/act/actions/"))
release, err := lock.TryLock(actionDir)
require.NoError(t, err)
require.NoError(t, release())
cm.AssertExpectations(t)
}
func TestExecAsDockerHoldsCloneLockForRemoteUncached(t *testing.T) {
actionDir := t.TempDir()
unlock, err := git.AcquireCloneLock(t.Context(), actionDir)
require.NoError(t, err)
unlockOnce := sync.OnceFunc(unlock)
defer unlockOnce()
innerEntered := make(chan struct{})
releaseInner := make(chan struct{})
releaseOnce := sync.OnceFunc(func() { close(releaseInner) })
defer releaseOnce()
origImageExists := ContainerImageExistsLocally
ContainerImageExistsLocally = func(_ context.Context, _, _ string) (bool, error) {
return false, nil
}
defer func() { ContainerImageExistsLocally = origImageExists }()
origBuildExec := ContainerNewDockerBuildExecutor
ContainerNewDockerBuildExecutor = func(_ container.NewDockerBuildExecutorInput) common.Executor {
return func(_ context.Context) error {
close(innerEntered)
<-releaseInner
return nil
}
}
defer func() { ContainerNewDockerBuildExecutor = origBuildExec }()
step := &stepActionRemote{
Step: &model.Step{ID: "1", Uses: "remote/action@v1", With: map[string]string{}},
RunContext: &RunContext{
Config: &Config{Env: testCheckoutEnv()},
Run: &model.Run{
JobID: "1",
Workflow: &model.Workflow{
Name: "wf",
Jobs: map[string]*model.Job{"1": {}},
},
},
JobContainer: &containerMock{},
},
action: &model.Action{Runs: model.ActionRuns{Using: "docker", Image: "Dockerfile"}},
env: map[string]string{},
}
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
done := make(chan error, 1)
go func() { done <- execAsDocker(ctx, step, "test-action", actionDir, actionDir, false, stepStageMain) }()
select {
case <-innerEntered:
t.Fatal("inner build executor ran before clone lock was released")
case err := <-done:
t.Fatalf("execAsDocker returned before inner was entered: %v", err)
case <-time.After(50 * time.Millisecond):
}
unlockOnce()
select {
case <-innerEntered:
case err := <-done:
t.Fatalf("execAsDocker returned without entering inner: %v", err)
}
cancel()
releaseOnce()
assert.ErrorIs(t, <-done, context.Canceled)
}
func TestExecAsDockerImageChecks(t *testing.T) {
actionRoot := t.TempDir()
originalExists, originalBuild, originalContainer := ContainerImageExistsLocally, ContainerNewDockerBuildExecutor, ContainerNewContainer
if container.NewContainer(&container.NewContainerInput{}) == nil {
t.Skip("Docker backend is disabled")
}
originalExists, originalBuild := ContainerImageExistsLocally, ContainerNewDockerBuildExecutor
t.Cleanup(func() {
ContainerImageExistsLocally, ContainerNewDockerBuildExecutor, ContainerNewContainer = originalExists, originalBuild, originalContainer
ContainerImageExistsLocally, ContainerNewDockerBuildExecutor = originalExists, originalBuild
})
ContainerNewContainer = func(*container.NewContainerInput) container.ExecutionsEnvironment { return fakeContainer{} }
var removed bool
fakeDockerDaemon(t, func(writer http.ResponseWriter, request *http.Request) {
if request.Method == http.MethodDelete {
removed = true
_, _ = io.WriteString(writer, `[]`)
} else {
_, _ = io.WriteString(writer, `{"Architecture":"aarch64"}`)
}
})
for _, testcase := range []struct {
name, platform string
exists, matches, rebuild bool
wantBuild, wantRemove bool
wantChecks []string
name, platform, options, wantPlatform string
exists, rebuild, wantBuild bool
}{
{name: "missing image", platform: "linux/arm64", wantBuild: true, wantChecks: []string{"any"}},
{name: "unspecified platform", exists: true, matches: true, wantChecks: []string{"any"}},
{name: "any platform", platform: "any", exists: true, matches: true, wantChecks: []string{"any"}},
{name: "matching platform", platform: "linux/arm64", exists: true, matches: true, wantChecks: []string{"any", "linux/arm64"}},
{name: "different platform", platform: "linux/arm64", exists: true, wantBuild: true, wantRemove: true, wantChecks: []string{"any", "linux/arm64"}},
{name: "forced rebuild", exists: true, matches: true, rebuild: true, wantBuild: true, wantChecks: []string{"any"}},
{name: "matching platform", platform: "linux/arm64", wantPlatform: "linux/arm64", exists: true},
{name: "runner options override architecture", platform: "linux/arm64", options: "--platform linux/amd64", wantPlatform: "linux/amd64", wantBuild: true},
{name: "forced rebuild", exists: true, rebuild: true, wantBuild: true},
} {
t.Run(testcase.name, func(t *testing.T) {
var checks []string
actionDir := t.TempDir()
ContainerImageExistsLocally = func(_ctx context.Context, _image, platform string) (bool, error) {
checks = append(checks, platform)
return testcase.exists && (platform == "any" || testcase.matches), nil
assert.Equal(t, testcase.wantPlatform, platform)
return testcase.exists, nil
}
var built bool
removed = false
ContainerNewDockerBuildExecutor = func(container.NewDockerBuildExecutorInput) common.Executor {
return func(context.Context) error { built = true; return nil }
ContainerNewDockerBuildExecutor = func(input container.NewDockerBuildExecutorInput) common.Executor {
assert.Equal(t, testcase.wantPlatform, input.Platform)
return func(context.Context) error {
built = true
_, err := lock.TryLock(actionDir)
assert.ErrorIs(t, err, lock.ErrLocked)
return nil
}
}
step := &stepActionRemote{
Step: &model.Step{ID: "action"},
@@ -551,19 +331,19 @@ func TestExecAsDockerImageChecks(t *testing.T) {
Config: &Config{
PresetGitHubContext: &model.GithubContext{},
ContainerArchitecture: testcase.platform,
ContainerOptions: testcase.options,
ForceRebuild: testcase.rebuild,
},
Run: &model.Run{JobID: "job", Workflow: &model.Workflow{Jobs: map[string]*model.Job{"job": {}}}},
JobContainer: &jobContainerMock{},
},
action: &model.Action{Runs: model.ActionRuns{Using: "docker", Image: "Dockerfile"}},
env: map[string]string{},
action: &model.Action{Runs: model.ActionRuns{Using: "docker", Image: "Dockerfile"}},
actionDir: actionDir,
remoteAction: mustNewRemoteAction(t, "remote/action@v1"),
env: map[string]string{},
}
dir := filepath.Join(actionRoot, testcase.name)
require.NoError(t, execAsDocker(t.Context(), step, "action", dir, dir, false, stepStageMain))
assert.Equal(t, testcase.wantChecks, checks)
require.NoError(t, runActionImpl(step)(common.WithDryrun(t.Context(), true)))
assert.Equal(t, testcase.wantBuild, built)
assert.Equal(t, testcase.wantRemove, removed)
})
}
}
@@ -657,21 +437,12 @@ func TestExecAsDockerStageEntrypoint(t *testing.T) {
warning: "##[warning]Unexpected input(s) 'unknown', valid inputs are ['entryPoint', 'args', 'message']",
},
{
name: "manifest args keep caller input quotes literal",
name: "manifest args preserve quoted and explicitly empty caller inputs",
stage: stepStageMain,
with: map[string]string{"args": "it's literal"},
runs: model.ActionRuns{Args: []string{"${{ inputs.args }}"}},
env: map[string]string{"INPUT_ARGS": "it's literal"},
wantCmd: []string{"it's literal"},
},
{
name: "caller input skips its default expression",
stage: stepStageMain,
with: map[string]string{"MESSAGE": "provided"},
with: map[string]string{"args": "it's literal", "MESSAGE": ""},
inputs: map[string]model.Input{"message": {Default: "${{ fromJSON('') }}"}},
runs: model.ActionRuns{Args: []string{"${{ inputs.message }}"}},
env: map[string]string{"INPUT_MESSAGE": "provided"},
wantCmd: []string{"provided"},
runs: model.ActionRuns{Args: []string{"${{ inputs.args }}", "${{ inputs.message }}"}},
wantCmd: []string{"it's literal", ""},
},
{
name: "explicit empty manifest args suppress caller args",
@@ -696,7 +467,8 @@ func TestExecAsDockerStageEntrypoint(t *testing.T) {
{
name: "post stage uses manifest entrypoint",
stage: stepStagePost,
runs: model.ActionRuns{PostEntrypoint: "post.sh", Args: []string{"hello"}},
inputs: map[string]model.Input{"message": {Default: "hello"}},
runs: model.ActionRuns{PostEntrypoint: "post.sh", Args: []string{"${{ github.job || inputs.message }}"}},
wantCmd: []string{"hello"},
wantEntrypoint: []string{"post.sh"},
},
@@ -705,11 +477,10 @@ func TestExecAsDockerStageEntrypoint(t *testing.T) {
hook := logtest.NewWithLevel(logging.LevelWarn)
ctx := common.WithLogger(t.Context(), logging.New(hook))
tc.runs.Using, tc.runs.Image = "docker", "docker://node:14"
cm := &containerMock{}
var input *container.NewContainerInput
ContainerNewContainer = func(in *container.NewContainerInput) container.ExecutionsEnvironment {
input = in
return cm
return fakeContainer{}
}
step := &stepActionRemote{
@@ -717,23 +488,20 @@ func TestExecAsDockerStageEntrypoint(t *testing.T) {
RunContext: &RunContext{
Config: &Config{PresetGitHubContext: &model.GithubContext{}},
Run: &model.Run{JobID: "1", Workflow: &model.Workflow{Jobs: map[string]*model.Job{"1": {}}}},
JobContainer: cm,
JobContainer: &jobContainerMock{},
},
action: &model.Action{Inputs: tc.inputs, Runs: tc.runs},
env: mergeMaps(tc.env),
remoteAction: mustNewRemoteAction(t, "org/action@v1"),
}
cm.On("Pull", false).Return(func(context.Context) error { return nil })
cm.On("Remove").Return(func(context.Context) error { return nil })
cm.On("Create", []string(nil), []string(nil)).Return(func(context.Context) error { return nil })
cm.On("Start", true).Return(func(context.Context) error { return nil })
cm.On("Close").Return(func(context.Context) error { return nil })
if tc.stage == stepStageMain {
require.NoError(t, runActionImpl(step, "", step.remoteAction)(ctx))
} else {
require.NoError(t, execAsDocker(ctx, step, "action", "", "", false, tc.stage))
switch tc.stage {
case stepStageMain:
require.NoError(t, runActionImpl(step)(ctx))
case stepStagePre:
require.NoError(t, runActionHook(step, stepStagePre)(ctx))
case stepStagePost:
require.NoError(t, runActionHook(step, stepStagePost)(ctx))
}
if tc.warning == "" {
assert.Empty(t, hook.AllRecords())

View File

@@ -18,143 +18,57 @@ import (
"go.yaml.in/yaml/v4"
)
// TestCancelledJobStatusEnablesAlwaysAndCancelledSteps verifies that once a job is
// cancelled, getJobContext reports the "cancelled" status so the step `if` functions
// evaluate the way GitHub Actions does: cancelled()/always() are true, success()/failure()
// are false. A step that defaults to success() is therefore skipped while an always() step
// still runs. Before the fix the status could only ever be success/failure, so cancelled()
// was structurally impossible and cancel-only cleanup steps never ran.
func TestCancelledJobStatusEnablesAlwaysAndCancelledSteps(t *testing.T) {
rc := createIfTestRunContext(map[string]*model.Job{
"job1": createJob(t, `runs-on: ubuntu-latest`, ""),
})
rc.markCancelled()
// The core fix: the job status context now reports "cancelled" instead of being
// pinned to success/failure.
jobCtx := rc.getJobContext()
require.Equal(t, "cancelled", jobCtx.Status)
// Feed that status through the step-context expression functions, which is what a
// step `if` evaluates. On a cancelled job only always()/cancelled() are true.
interp := exprparser.NewInterpeter(
&exprparser.EvaluationEnvironment{Job: jobCtx},
exprparser.Config{Context: "step"},
)
for expr, want := range map[string]bool{
"cancelled()": true,
"always()": true,
"success()": false,
"failure()": false,
"!cancelled()": false,
func TestStepsExecutorRunsMainStepsUnlessSetupFailed(t *testing.T) {
for name, tt := range map[string]struct {
stage, status, result string
cause error
ran []string
}{
"setup failure": {"pre", "failure", "failure", setupError{assert.AnError}, []string{"pre"}},
"pre step failure": {"pre", "failure", "failure", assert.AnError, []string{"pre", "main", "always"}},
"cancel during pre": {"pre", "cancelled", "cancelled", context.Canceled, []string{"pre", "main", "always"}},
"cancel during main": {"main", "cancelled", "cancelled", context.Canceled, []string{"pre", "main", "always"}},
"deadline during main": {"main", "cancelled", "failure", context.DeadlineExceeded, []string{"pre", "main", "always"}},
} {
got, err := interp.Evaluate(expr, exprparser.DefaultStatusCheckNone)
require.NoErrorf(t, err, "Evaluate(%q)", expr)
assert.Equalf(t, want, got, "Evaluate(%q) on a cancelled job", expr)
}
// A step without an `if` defaults to success() and must be skipped on cancel,
// while an `if: always()` step must still run.
disabled, err := interp.Evaluate("", exprparser.DefaultStatusCheckSuccess)
require.NoError(t, err)
assert.Equal(t, false, disabled, "default-success step must be skipped on a cancelled job")
enabled, err := interp.Evaluate("always()", exprparser.DefaultStatusCheckSuccess)
require.NoError(t, err)
assert.Equal(t, true, enabled, "`if: always()` step must run on a cancelled job")
setJobResult(t.Context(), rc, rc, true)
assert.Equal(t, "cancelled", rc.Run.Job().Result)
}
func TestMainStepsExecutorRunsAlwaysStepsAfterInterruption(t *testing.T) {
for name, wantError := range map[string]error{"cancel": context.Canceled, "timeout": context.DeadlineExceeded} {
t.Run(name, func(t *testing.T) {
rc := createIfTestRunContext(map[string]*model.Job{
"job1": createJob(t, `runs-on: ubuntu-latest`, ""),
})
var ctx context.Context
var interrupt func()
if wantError == context.Canceled {
ctx, interrupt = context.WithCancel(t.Context())
defer interrupt()
} else {
deadline := newControllableDeadlineContext(t.Context())
rc := makeTestRC(t, "{}")
ctx, interrupt := context.WithCancel(common.WithJobErrorContainer(t.Context()))
defer interrupt()
if tt.cause == context.DeadlineExceeded {
deadline := newControllableDeadlineContext(ctx)
ctx, interrupt = deadline, deadline.expire
}
var ran []string
var laterStepCtxErr error
err := newMainStepsExecutor(rc, []common.Executor{
func(_ctx context.Context) error {
ran = append(ran, "step1")
interrupt()
return nil
},
func(ctx context.Context) error {
ran = append(ran, "always-step")
laterStepCtxErr = ctx.Err()
return nil
},
})(ctx)
require.ErrorIs(t, err, wantError)
assert.Equal(t, []string{"step1", "always-step"}, ran)
require.NoError(t, laterStepCtxErr)
assert.Equal(t, wantError == context.Canceled, rc.jobCancelled)
assert.Equal(t, "cancelled", rc.getJobContext().Status)
setJobResult(t.Context(), rc, rc, true)
if wantError == context.DeadlineExceeded {
assert.True(t, rc.jobFailed)
assert.Equal(t, "failure", rc.Run.Job().Result)
} else {
assert.Equal(t, "cancelled", rc.Run.Job().Result)
}
})
}
}
func TestStepsExecutorRunsMainStepsAfterPreInterruption(t *testing.T) {
for name, tt := range map[string]struct {
cancel bool
preErr error
wantError error
}{
"cancel": {cancel: true, wantError: context.Canceled},
"failure": {preErr: assert.AnError, wantError: assert.AnError},
} {
t.Run(name, func(t *testing.T) {
rc := createIfTestRunContext(map[string]*model.Job{
"job1": createJob(t, `runs-on: ubuntu-latest`, ""),
})
ctx := t.Context()
var cancel context.CancelFunc
if tt.cancel {
ctx, cancel = context.WithCancel(ctx)
defer cancel()
}
var ran []string
var mainStepCtxErr error
err := newStepsExecutor(rc, []common.Executor{
func(_ctx context.Context) error {
ran = append(ran, "pre1")
if tt.cancel {
cancel()
phase := func(stage string) common.Executor {
return func(stepCtx context.Context) error {
ran = append(ran, stage)
require.NoError(t, stepCtx.Err())
switch {
case stage != tt.stage:
case tt.cause == context.Canceled || tt.cause == context.DeadlineExceeded:
interrupt()
default:
reportStepError(stepCtx, rc, tt.cause)
return tt.cause
}
return tt.preErr
},
}, []common.Executor{
func(ctx context.Context) error {
ran = append(ran, "always-step")
mainStepCtxErr = ctx.Err()
return nil
},
})(ctx)
}
}
require.ErrorIs(t, err, tt.wantError)
assert.Equal(t, []string{"pre1", "always-step"}, ran)
require.NoError(t, mainStepCtxErr)
assert.Equal(t, tt.cancel, rc.jobCancelled)
require.ErrorIs(t, newStepsExecutor(rc, []common.Executor{phase("pre")}, []common.Executor{phase("main"), phase("always")})(ctx), tt.cause)
assert.Equal(t, tt.ran, ran)
assert.Equal(t, tt.cause == context.Canceled, rc.jobCancelled)
jobContext := rc.getJobContext()
assert.Equal(t, tt.status, jobContext.Status)
cancelled := tt.status == "cancelled"
evaluator := exprparser.NewInterpeter(&exprparser.EvaluationEnvironment{Job: jobContext}, exprparser.Config{Context: "step"})
for condition, want := range map[string]bool{"cancelled()": cancelled, "always()": true, "success()": false, "failure()": !cancelled, "!cancelled()": !cancelled, "": false} {
got, err := evaluator.Evaluate(condition, exprparser.DefaultStatusCheckSuccess)
require.NoError(t, err, condition)
assert.Equal(t, want, got, condition)
}
rc.setJobResult(t.Context(), true)
assert.Equal(t, tt.result, rc.Run.Job().Result)
})
}
}

View File

@@ -50,6 +50,7 @@ func TestDockerProxyMountedJob(t *testing.T) {
ContainerDaemonSocket: dockerClient.DaemonHost(),
ContainerMaxLifetime: 2 * time.Minute,
Sweep: true,
NoNodeDownload: true,
ContainerOptions: "-v /usr/local/bin/docker:/usr/local/bin/docker:ro -v /usr/local/libexec/docker/cli-plugins:/usr/local/libexec/docker/cli-plugins:ro",
ValidVolumes: []string{"/usr/local/bin/docker", "/usr/local/libexec/docker/cli-plugins"},
Env: map[string]string{"PROXY_TEST_RESOURCE": resourceName, "PROXY_TEST_MODE": mode, "PROXY_TEST_IMAGE": baseImage, "COMPOSE_PROJECT_NAME": resourceName},
@@ -62,26 +63,18 @@ func TestDockerProxyMountedJob(t *testing.T) {
plan, err = planner.PlanJob("proxy")
}
require.NoError(t, err)
runContext, err := runner.newRunContext(ctx, plan.Stages[0].Runs[0], nil)
require.NoError(t, err)
jobName := runContext.jobContainerName()
jobNetwork, _ := runContext.networkNameForGitea()
t.Cleanup(func() {
cleanCtx, cleanCancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
defer cleanCancel()
if _, err := dockerClient.ContainerRemove(cleanCtx, jobName, client.ContainerRemoveOptions{Force: true, RemoveVolumes: true}); !cerrdefs.IsNotFound(err) {
containers, err := dockerClient.ContainerList(cleanCtx, client.ContainerListOptions{All: true, Filters: make(client.Filters).Add("name", resourceName)})
assert.NoError(t, err)
assert.Empty(t, containers.Items, "job container survived cleanup")
for _, leftover := range containers.Items {
_, err := dockerClient.ContainerRemove(cleanCtx, leftover.ID, client.ContainerRemoveOptions{Force: true, RemoveVolumes: true})
assert.NoError(t, err)
}
for _, name := range []string{resourceName, jobNetwork} {
if _, err := dockerClient.NetworkRemove(cleanCtx, name, client.NetworkRemoveOptions{}); !cerrdefs.IsNotFound(err) {
assert.NoError(t, err)
}
}
for _, name := range []string{resourceName, jobName, jobName + "-env"} {
if _, err := dockerClient.VolumeRemove(cleanCtx, name, client.VolumeRemoveOptions{}); !cerrdefs.IsNotFound(err) {
assert.NoError(t, err)
}
}
assert.NoError(t, container.NewDockerNetworkRemoveExecutor(resourceName)(cleanCtx))
assert.NoError(t, container.NewDockerVolumeRemoveExecutor(resourceName, false)(cleanCtx))
})
hook := logtest.New()
@@ -94,8 +87,6 @@ func TestDockerProxyMountedJob(t *testing.T) {
if mode == "proxy" {
require.Contains(t, messages, "docker binds verified")
}
_, err = dockerClient.ContainerInspect(ctx, jobName, client.ContainerInspectOptions{})
assert.True(t, cerrdefs.IsNotFound(err), "job container survived cleanup: %v", err)
_, err = dockerClient.NetworkInspect(ctx, resourceName, client.NetworkInspectOptions{})
if mode == "proxy" {
assert.True(t, cerrdefs.IsNotFound(err), "labelled network survived cleanup: %v", err)

View File

@@ -32,54 +32,25 @@ func (rc *RunContext) NewExpressionEvaluator(ctx context.Context) *ExpressionEva
}
func (rc *RunContext) NewExpressionEvaluatorWithEnv(ctx context.Context, env map[string]string) *ExpressionEvaluator {
var workflowCallResult map[string]*model.WorkflowCallResult
return rc.newExpressionEvaluator(ctx, env, rc.getJobContext(), rc.getGithubContext(ctx), "job")
}
// todo: cleanup EvaluationEnvironment creation
strategy := make(map[string]any)
if rc.Run != nil {
strategy = exprparser.StrategyContext(rc.Run.Job().Strategy, rc.jobIndex, rc.jobTotal)
// only setup jobs context in case of workflow_call
// and existing expression evaluator (this means, jobs are at
// least ready to run)
if rc.caller != nil && rc.ExprEval != nil {
workflowCallResult = map[string]*model.WorkflowCallResult{}
for jobName, job := range rc.Run.Workflow.Jobs {
result := model.WorkflowCallResult{
Outputs: map[string]string{},
}
unlock := lockJob(job)
maps.Copy(result.Outputs, job.Outputs)
unlock()
workflowCallResult[jobName] = &result
}
}
func (rc *RunContext) newExpressionEvaluator(ctx context.Context, env map[string]string, jobContext *model.JobContext, github *model.GithubContext, scope string) *ExpressionEvaluator {
ee := rc.actionDefaultEnvironment(ctx, github, jobContext)
if scope == "job" {
ee.Jobs = new(map[string]*model.WorkflowCallResult)
}
ghc := rc.getGithubContext(ctx)
ee := &exprparser.EvaluationEnvironment{
Github: ghc,
Env: env,
Job: rc.getJobContext(),
Jobs: &workflowCallResult,
// todo: should be unavailable
// but required to interpolate/evaluate the step outputs on the job
Steps: rc.StepResults,
Secrets: getWorkflowSecrets(rc),
Vars: rc.Config.Vars,
Strategy: strategy,
Matrix: rc.Matrix,
Needs: exprparser.NeedsContext(rc.Run),
Inputs: getEvaluatorInputs(rc, rc.actionInputs, ghc),
HashFiles: getHashFilesFunction(ctx, rc),
}
ee.Runner = rc.getRunnerContext(ctx)
ee.Env = env
ee.Steps = rc.StepResults
ee.Secrets = getWorkflowSecrets(rc)
ee.Vars = rc.Config.Vars
ee.Needs = exprparser.NeedsContext(rc.Run)
ee.Inputs = rc.getEvaluatorInputs(github)
return &expressionEvaluator{
interpreter: exprparser.NewInterpeter(ee, exprparser.Config{
Run: rc.Run,
WorkingDir: rc.Config.Workdir,
Context: "job",
Context: scope,
}),
}
}
@@ -89,46 +60,31 @@ var hashfiles string
// NewStepExpressionEvaluator creates a new evaluator with the `inputs` of the enclosing workflow or composite action
func (rc *RunContext) NewStepExpressionEvaluator(ctx context.Context, step step) *ExpressionEvaluator {
return rc.newStepExpressionEvaluator(ctx, step, rc.actionInputs, rc.getJobContext(), getStepGithubContext(ctx, step))
return rc.newExpressionEvaluator(ctx, *step.getEnv(), rc.getJobContext(), getStepGithubContext(ctx, step), "step")
}
// NewActionInputsExpressionEvaluator creates a new evaluator with the step's own with: values as `inputs`
func (rc *RunContext) NewActionInputsExpressionEvaluator(ctx context.Context, step step) *ExpressionEvaluator {
return rc.newStepExpressionEvaluator(ctx, step, inputsFromEnv(*step.getEnv()), rc.getJobContext(), getStepGithubContext(ctx, step))
}
func (rc *RunContext) newStepExpressionEvaluator(ctx context.Context, step step, stepInputs map[string]any, jobContext *model.JobContext, github *model.GithubContext) *ExpressionEvaluator {
// todo: cleanup EvaluationEnvironment creation
ee := &exprparser.EvaluationEnvironment{
Github: github,
Env: *step.getEnv(),
Job: jobContext,
Steps: rc.StepResults,
Secrets: getWorkflowSecrets(rc),
Vars: rc.Config.Vars,
Strategy: exprparser.StrategyContext(rc.Run.Job().Strategy, rc.jobIndex, rc.jobTotal),
Matrix: rc.Matrix,
Needs: exprparser.NeedsContext(rc.Run),
// todo: should be unavailable
// but required to interpolate/evaluate the inputs in actions/composite
Inputs: getEvaluatorInputs(rc, stepInputs, github),
func (rc *RunContext) actionDefaultEnvironment(ctx context.Context, github *model.GithubContext, job *model.JobContext) *exprparser.EvaluationEnvironment {
return &exprparser.EvaluationEnvironment{
Github: github,
Strategy: exprparser.StrategyContext(rc.Run.Job().Strategy, rc.jobIndex, rc.jobTotal),
Matrix: rc.Matrix,
Job: job,
Runner: rc.getRunnerContext(ctx),
HashFiles: getHashFilesFunction(ctx, rc),
}
ee.Runner = rc.getRunnerContext(ctx)
return &expressionEvaluator{
interpreter: exprparser.NewInterpeter(ee, exprparser.Config{
Run: rc.Run,
WorkingDir: rc.Config.Workdir,
Context: "step",
}),
}
func newActionInputsExpressionEvaluator(inputs map[string]string) *ExpressionEvaluator {
values := make(map[string]any, len(inputs))
for name, value := range inputs {
values[name] = value
}
return &expressionEvaluator{interpreter: exprparser.NewInterpeter(&exprparser.EvaluationEnvironment{Inputs: values}, exprparser.Config{Context: "step"})}
}
func getHashFilesFunction(ctx context.Context, rc *RunContext) func(v []reflect.Value) (any, error) {
return func(v []reflect.Value) (any, error) {
if rc.JobContainer != nil {
timeoutCtx, cancel := context.WithTimeout(ctx, 120*time.Second)
defer cancel()
name := "workflow/hashfiles/index.js"
hout := &bytes.Buffer{}
herr := &bytes.Buffer{}
@@ -152,6 +108,9 @@ func getHashFilesFunction(ctx context.Context, rc *RunContext) func(v []reflect.
if followSymlink {
env["followSymbolicLinks"] = "true"
}
node := rc.node(ctx)
timeoutCtx, cancel := context.WithTimeout(ctx, 120*time.Second)
defer cancel()
stdout, stderr := rc.JobContainer.ReplaceLogWriter(hout, herr)
defer rc.JobContainer.ReplaceLogWriter(stdout, stderr)
@@ -159,19 +118,18 @@ func getHashFilesFunction(ctx context.Context, rc *RunContext) func(v []reflect.
Name: name,
Mode: 0o644,
Body: hashfiles,
}).Then(rc.JobContainer.Exec([]string{"node", container.JoinPath(rc.JobContainer.GetActPath(), name)}, env, "", ""))(timeoutCtx)
quotedPatterns := expressionStringEscape(strings.Join(patterns, ", "))
}).Then(rc.JobContainer.Exec([]string{node, container.JoinPath(rc.JobContainer.GetActPath(), name)}, env, "", ""))(timeoutCtx)
switch {
case err == nil:
case ctx.Err() != nil:
return "", ctx.Err()
case timeoutCtx.Err() != nil || errors.Is(err, context.DeadlineExceeded):
return "", fmt.Errorf("hashFiles('%s') couldn't finish within 120 seconds", quotedPatterns)
return "", fmt.Errorf("hashFiles('%s') couldn't finish within 120 seconds", expressionStringEscape(strings.Join(patterns, ", ")))
case hashFilesNodeMissing(err):
common.Logger(ctx).With(rawOutputField, true).Warnf("##[warning]hashFiles could not run because node is unavailable in the job environment. Returning an empty string.")
return "", nil
default:
return "", fmt.Errorf("hashFiles('%s') failed. Fail to hash files under directory '%s'", quotedPatterns, rc.githubWorkspace())
return "", fmt.Errorf("hashFiles('%s') failed. Fail to hash files under directory '%s'", expressionStringEscape(strings.Join(patterns, ", ")), rc.githubWorkspace())
}
for line := range strings.Lines(hout.String() + "\n" + herr.String()) {
if hash, ok := strings.CutPrefix(strings.TrimRight(line, "\r\n"), "__OUTPUT__"); ok {
@@ -253,9 +211,12 @@ func inputsFromEnv(env map[string]string) map[string]any {
return inputs
}
func getEvaluatorInputs(rc *RunContext, stepInputs map[string]any, ghc *model.GithubContext) map[string]any {
if stepInputs != nil { // an action's own inputs, which workflow inputs must not shadow
return maps.Clone(stepInputs)
func (rc *RunContext) getEvaluatorInputs(ghc *model.GithubContext) map[string]any {
if rc.actionInputs != nil {
return maps.Clone(rc.actionInputs)
}
if rc.caller != nil {
return maps.Clone(rc.caller.inputs)
}
// only a called workflow's job itself takes the inputs Gitea resolved,
// composite actions copy its Config but have their own `inputs`
@@ -264,7 +225,6 @@ func getEvaluatorInputs(rc *RunContext, stepInputs map[string]any, ghc *model.Gi
}
inputs := map[string]any{}
maps.Copy(inputs, rc.workflowCallInputs)
switch ghc.EventName {
case "workflow_dispatch":
@@ -292,36 +252,39 @@ func setEvaluatorInput(inputs map[string]any, ghc *model.GithubContext, name str
inputs[name] = model.CoerceInputValue(value, input.Type)
}
// resolveWorkflowCall evaluates the caller's with: and secrets: once, as the server does before dispatching a called workflow.
func (c *caller) resolveInputs(ctx context.Context, workflow *model.Workflow) error {
rc := c.runContext
callerEval := rc.ExprEval.shared(ctx)
var callerWith map[string]any
if err := model.DecodeEvaluated("workflow inputs", rc.Run.Job().RawWith, callerEval.EvaluateYamlNode, &callerWith); err != nil {
return err
}
c.workflowCallConfig = workflow.WorkflowCallConfig()
var err error
if c.inputs, err = callerEval.ResolveWorkflowCallInputs(c.workflowCallConfig, callerWith); err != nil {
common.Logger(ctx).Warn(err)
}
return nil
}
func (rc *RunContext) resolveWorkflowCall(ctx context.Context) error {
if rc.caller == nil {
return nil
}
logger := common.Logger(ctx)
callerJob := rc.caller.runContext.Run.Job()
callerEval := rc.caller.runContext.ExprEval.shared(ctx)
var callerWith map[string]any
if err := model.DecodeEvaluated("workflow inputs", callerJob.RawWith, callerEval.EvaluateYamlNode, &callerWith); err != nil {
return err
}
if !rc.Run.Workflow.IsWorkflowCall() {
logger.Warn("workflow_call key is not defined in the referenced workflow")
}
config := rc.Run.Workflow.WorkflowCallConfig()
var err error
if rc.workflowCallInputs, err = callerEval.ResolveWorkflowCallInputs(config, callerWith); err != nil {
logger.Warn(err)
}
caller := rc.caller.runContext
callerJob := caller.Run.Job()
if callerJob.InheritSecrets() {
rc.workflowCallSecrets = getWorkflowSecrets(rc.caller.runContext)
rc.workflowCallSecrets = getWorkflowSecrets(caller)
return nil
}
secrets := callerJob.Secrets()
if err := config.ValidateSecrets(secrets); err != nil {
if err := rc.caller.workflowCallConfig.ValidateSecrets(secrets); err != nil {
logger.Warn(err)
}
if rc.workflowCallSecrets, err = callerEval.EvaluateCallerSecrets(secrets); err != nil {
var err error
if rc.workflowCallSecrets, err = caller.ExprEval.shared(ctx).EvaluateCallerSecrets(secrets); err != nil {
return fmt.Errorf("unable to interpolate %w", err)
}
for _, name := range []string{"GITHUB_TOKEN", "GITEA_TOKEN"} {

View File

@@ -10,9 +10,9 @@ import (
"errors"
"fmt"
"io"
"os/exec"
"reflect"
"strings"
"sync"
"testing"
"time"
@@ -178,6 +178,15 @@ func (c *hashFilesContainer) ReplaceLogWriter(stdout, stderr io.Writer) (io.Writ
}
func TestGetHashFilesFunction(t *testing.T) {
t.Run("regular file with trailing slash", func(t *testing.T) {
requireHostTools(t, "node")
cmd := exec.CommandContext(t.Context(), "node", "hashfiles/index.js")
cmd.Env = []string{"patterns=hashfiles/index.js/"}
output, err := cmd.CombinedOutput()
require.NoError(t, err)
assert.Contains(t, string(output), "__OUTPUT____OUTPUT__")
})
const failureMessage = "hashFiles('dir''file, *.sum, 123, true, ') failed. Fail to hash files under directory '/workspace'"
for _, test := range []struct {
name string
@@ -422,7 +431,7 @@ func TestGetEvaluatorInputsBoolean(t *testing.T) {
}
ghc := &model.GithubContext{EventName: eventName, Event: table.event}
inputs := getEvaluatorInputs(rc, nil, ghc)
inputs := rc.getEvaluatorInputs(ghc)
assert.Equal(t, table.flag, inputs["flag"])
assert.Equal(t, "gitea", inputs["name"])
assert.Equal(t, false, inputs["unset"])
@@ -432,6 +441,7 @@ func TestGetEvaluatorInputsBoolean(t *testing.T) {
t.Run("deferred workflow call inputs", func(t *testing.T) {
workflow, err := model.ReadWorkflow(strings.NewReader(workflow("workflow_call") + `
workflow_dispatch: {inputs: {name: {type: string, default: dispatch}}}
jobs:
test: {}
call:
@@ -447,9 +457,11 @@ jobs:
t.Parallel()
parent, err := (&runnerImpl{config: &Config{PresetGitHubContext: &model.GithubContext{}}}).newRunContext(t.Context(), &model.Run{Workflow: workflow, JobID: "call"}, map[string]any{"args": `{"flag":` + value + `,"name":"${{ 'runner' }}"}`})
require.NoError(t, err)
child, err := (&runnerImpl{config: &Config{PresetGitHubContext: &model.GithubContext{}}, caller: &caller{runContext: parent}}).newRunContext(t.Context(), &model.Run{Workflow: workflow, JobID: "test"}, nil)
call := &caller{runContext: parent}
require.NoError(t, call.resolveInputs(t.Context(), workflow))
child, err := (&runnerImpl{config: parent.Config, caller: call}).newRunContext(t.Context(), &model.Run{Workflow: workflow, JobID: "test"}, nil)
require.NoError(t, err)
assert.Equal(t, map[string]any{"flag": value == "true", "name": "${{ 'runner' }}", "unset": false}, child.workflowCallInputs)
assert.Equal(t, map[string]any{"flag": value == "true", "name": "${{ 'runner' }}", "unset": false}, child.getEvaluatorInputs(&model.GithubContext{EventName: "workflow_dispatch"}))
assert.Equal(t, rawWith, job.RawWith)
assert.Nil(t, job.With)
})
@@ -472,10 +484,10 @@ on:
ghc := &model.GithubContext{EventName: "workflow_dispatch", Event: map[string]any{"inputs": map[string]any{"name": "dispatch"}}}
job := &RunContext{Config: config, Run: &model.Run{JobID: "job1", Workflow: wf}}
assert.Equal(t, map[string]any{"name": "caller", "target": "dispatch"}, getEvaluatorInputs(job, nil, ghc))
assert.Equal(t, map[string]any{"name": "caller", "target": "dispatch"}, job.getEvaluatorInputs(ghc))
composite := &RunContext{Config: config, Run: &model.Run{JobID: "job1", Workflow: &model.Workflow{}}, Parent: job}
assert.Equal(t, map[string]any{"arg": "x"}, getEvaluatorInputs(composite, map[string]any{"arg": "x"}, ghc))
composite := &RunContext{Config: config, Parent: job, actionInputs: map[string]any{"arg": "x"}}
assert.Equal(t, map[string]any{"arg": "x"}, composite.getEvaluatorInputs(ghc))
}
func TestActionInputsShadowDispatchInputs(t *testing.T) {
@@ -491,16 +503,16 @@ jobs:
rc := newTestRC(wf, nil)
rc.Config.EventName = "workflow_dispatch"
rc.EventJSON = `{"inputs":{"message":"workflow"}}`
step := &stepActionRemote{RunContext: rc, env: map[string]string{"INPUT_MESSAGE": "step"}}
assert.Equal(t, "step", rc.NewActionInputsExpressionEvaluator(t.Context(), step).InterpolateName(t.Context(), "${{ inputs.message }}"))
assert.Equal(t, "workflow", rc.NewStepExpressionEvaluator(t.Context(), step).InterpolateName(t.Context(), "${{ inputs.message }}"))
step := &stepActionRemote{RunContext: rc, Step: &model.Step{}, env: map[string]string{"INPUT_EXTRA": "inherited"}}
inputs, err := rc.resolveActionInputs(t.Context(), step, &model.Action{Inputs: map[string]model.Input{
"message": {Default: "${{ env.INPUT_EXTRA || gitea.event_name }}"},
}})
require.NoError(t, err)
applyActionInputs(step, inputs)
assert.Equal(t, "workflow_dispatch|", newActionInputsExpressionEvaluator(inputs).InterpolateName(t.Context(), "${{ inputs.message }}|${{ inputs.extra || gitea.event_name }}"))
enabled, err := isStepEnabled(t.Context(), "inputs.message == 'workflow'", step, stepStageMain)
require.NoError(t, err)
assert.True(t, enabled)
step.Step, step.action = &model.Step{}, &model.Action{Inputs: map[string]model.Input{"fallback": {Default: "${{ inputs.message }}"}}}
env, err := evaluateCompositeInputAndEnv(t.Context(), rc, step)
require.NoError(t, err)
assert.Equal(t, "workflow", env["INPUT_FALLBACK"])
}
func TestResolveWorkflowCallToleratesMismatchesAndPassesSecretsAndTokens(t *testing.T) {
@@ -534,26 +546,30 @@ jobs:
PresetGitHubContext: &model.GithubContext{},
RuntimeTokens: map[*model.Workflow]string{callerWorkflow: "caller-run"},
}
resolve := func(callerJobID string, workflow *model.Workflow) *RunContext {
parent, err := (&runnerImpl{config: config}).newRunContext(t.Context(), &model.Run{Workflow: callerWorkflow, JobID: callerJobID}, nil)
require.NoError(t, err)
child, err := (&runnerImpl{config: config, caller: &caller{runContext: parent}}).newRunContext(t.Context(), &model.Run{Workflow: workflow, JobID: "test"}, nil)
call := func(parent *RunContext, workflow *model.Workflow) *RunContext {
state := &caller{runContext: parent}
require.NoError(t, state.resolveInputs(t.Context(), workflow))
child, err := (&runnerImpl{config: config, caller: state}).newRunContext(t.Context(), &model.Run{Workflow: workflow, JobID: "test"}, nil)
require.NoError(t, err)
return child
}
resolve := func(callerJobID string, workflow *model.Workflow) *RunContext {
parent, err := (&runnerImpl{config: config}).newRunContext(t.Context(), &model.Run{Workflow: callerWorkflow, JobID: callerJobID}, nil)
require.NoError(t, err)
return call(parent, workflow)
}
called := resolve("call", callee)
assert.Equal(t, map[string]any{"flag": true}, called.workflowCallInputs)
assert.Equal(t, map[string]any{"flag": true}, called.caller.inputs)
assert.Equal(t, map[string]string{"undeclared": "${{ github.token }}", "GITHUB_TOKEN": "github-token", "GITEA_TOKEN": "gitea-token"}, called.workflowCallSecrets)
assert.Equal(t, "caller-run", called.GetEnv()["ACTIONS_RUNTIME_TOKEN"])
inherited := resolve("inherit", notCallable)
assert.Empty(t, inherited.workflowCallInputs)
assert.Empty(t, inherited.caller.inputs)
assert.Equal(t, map[string]string{"token": "${{ github.token }}", "GITHUB_TOKEN": "github-token", "GITEA_TOKEN": "gitea-token", "ACTIONS_RUNTIME_TOKEN": "caller-run"}, inherited.workflowCallSecrets)
assert.Equal(t, "${{ github.token }}:", resolve("override", callee).ExprEval.InterpolateName(t.Context(), "${{ secrets.GITHUB_TOKEN }}:${{ secrets.GITEA_TOKEN }}"))
middle, err := model.ReadWorkflow(strings.NewReader("on: workflow_call\njobs:\n test: {uses: ./reuse.yml}\n"))
require.NoError(t, err)
nested, err := (&runnerImpl{config: config, caller: &caller{runContext: resolve("override", middle)}}).newRunContext(t.Context(), &model.Run{Workflow: callee, JobID: "test"}, nil)
require.NoError(t, err)
nested := call(resolve("override", middle), callee)
assert.Equal(t, "github-token:gitea-token", nested.ExprEval.InterpolateName(t.Context(), "${{ secrets.GITHUB_TOKEN }}:${{ secrets.GITEA_TOKEN }}"))
}
@@ -579,22 +595,3 @@ jobs:
assert.NotContains(t, a, "s3cr3t")
assert.NotEqual(t, a, b)
}
func TestNewExpressionEvaluatorReadsJobOutputsWhileCombinationsWriteThem(t *testing.T) {
rc := createRunContext(t)
rc.caller = &caller{runContext: createRunContext(t)}
rc.ExprEval = rc.NewExpressionEvaluator(t.Context())
job := rc.Run.Job()
var writes sync.WaitGroup
writes.Go(func() {
for range 100 {
unlock := lockJob(job)
job.Outputs = map[string]string{"out": "value"}
unlock()
}
})
for range 100 {
rc.NewExpressionEvaluator(t.Context())
}
writes.Wait()
}

File diff suppressed because it is too large Load Diff

View File

@@ -31,55 +31,36 @@ import (
"gitea.dev/actionslib/pkg/exprparser"
"gitea.dev/actionslib/pkg/model"
"gitea.dev/actionslib/pkg/protocol"
unicodeencoding "golang.org/x/text/encoding/unicode"
"golang.org/x/text/transform"
)
const (
jobCleanupTimeout = time.Minute
maxJobSummaryBytes = 1024 * 1024
jobCleanupTimeout = time.Minute
jobSummaryUploadPhaseTimeout = 15 * time.Second
)
// jobSummaryTruncationMarker is appended to a summary that exceeded the size limit
// so the rendered output makes the truncation visible instead of silently cutting off.
const jobSummaryTruncationMarker = "\n\n---\n\n*Job summary truncated: it exceeded the maximum allowed size.*\n"
var (
jobSummaryUploadRetryDelay = time.Second
// jobSummaryUploadRequestTimeout bounds a single step upload request. It is kept
// below jobSummaryUploadPhaseTimeout so one slow or unreachable request times out
// and lets the remaining steps still upload within the phase budget, instead of a
// single stuck request consuming the whole phase.
jobSummaryUploadRequestTimeout = 5 * time.Second
// jobSummaryUploadPhaseTimeout bounds the total time spent uploading all step
// summaries. The uploads run inside the job cleanup budget that is also used to
// stop and remove the container, so a slow or unreachable endpoint must not be
// allowed to consume it; this keeps the remaining budget available for teardown.
jobSummaryUploadPhaseTimeout = 15 * time.Second
)
type jobInfo interface {
matrix() map[string]any
steps() []*model.Step
startContainer() common.Executor
stopContainer() common.Executor
closeContainer() common.Executor
interpolateOutputs() common.Executor
result(result string)
}
// reportStepError records a step error so the job is reported failed — except a
// cancellation, which is an interruption, not a failure.
func reportStepError(ctx context.Context, rc *RunContext, err error) {
if errors.Is(err, context.Canceled) {
// Defer to the job context: a genuine cancel reports cancelled, a stray teardown
// cancellation on a live ctx is ignored — never a step FAILURE.
rc.markInterrupted(ctx.Err())
return
if ctx.Err() != nil {
rc.markJobInterrupted(ctx)
} else if err != nil && !errors.Is(err, context.Canceled) { // A live job can receive cancellation from step teardown.
common.Logger(ctx).Errorf("##[error]%s", EscapeCommandData(err.Error()))
common.SetJobError(ctx, err)
rc.markFailed()
}
common.Logger(ctx).Errorf("##[error]%s", EscapeCommandData(err.Error()))
common.SetJobError(ctx, err)
rc.markFailed()
}
// actionPreparer is implemented by steps that download an action before they run, so the job
@@ -158,22 +139,14 @@ func (e setupError) Unwrap() error { return e.error }
// printCompleteJobName closes the setup section the way actions/runner ends its "Set up job" step.
func printCompleteJobName(rc *RunContext) common.Executor {
return func(ctx context.Context) error {
// Name holds a matrix combination; JobName is the shared name GitHub reports.
name := cmp.Or(rc.JobName, rc.Name)
if name == "" && rc.Run != nil {
name = rc.Run.JobID
}
common.Logger(ctx).With(rawOutputField, true).Infof("Complete job name: %s", name)
common.Logger(ctx).With(rawOutputField, true).Infof("Complete job name: %s", cmp.Or(rc.JobName, rc.Name, rc.Run.JobID)) // Name holds a matrix combination; JobName is the shared name GitHub reports.
return nil
}
}
func newJobExecutor(info jobInfo, sf stepFactory, rc *RunContext) common.Executor {
steps := make([]common.Executor, 0)
preSteps := make([]common.Executor, 0)
// Collected separately: every action is downloaded before the first pre step runs.
stepPreSteps := make([]common.Executor, 0)
preparers := make([]actionPreparer, 0)
var steps, preSteps, stepPreSteps []common.Executor // Collected separately: every action is downloaded before the first pre step runs.
var preparers []actionPreparer
var postExecutor common.Executor
infoSteps := info.steps()
@@ -183,16 +156,12 @@ func newJobExecutor(info jobInfo, sf stepFactory, rc *RunContext) common.Executo
}
preSteps = append(preSteps, func(ctx context.Context) error {
if len(info.matrix()) > 0 {
common.Logger(ctx).Infof("Matrix: %v", info.matrix())
if len(rc.Matrix) > 0 {
common.Logger(ctx).Infof("Matrix: %v", rc.Matrix)
}
return nil
})
preSteps = append(preSteps, func(ctx context.Context) error {
// Have to be skipped for some Tests
if rc.Run == nil {
return nil
}
if err := evaluateJobEnvAndDefaults(ctx, rc); err != nil {
reportStepError(ctx, rc, err)
return err
@@ -202,9 +171,7 @@ func newJobExecutor(info jobInfo, sf stepFactory, rc *RunContext) common.Executo
for i, stepModel := range infoSteps {
if stepModel == nil {
return func(ctx context.Context) error {
return fmt.Errorf("invalid Step %v: missing run or uses key", i)
}
return common.NewErrorExecutor(fmt.Errorf("invalid Step %v: missing run or uses key", i))
}
if stepModel.ID == "" {
stepModel.ID = strconv.Itoa(i)
@@ -220,42 +187,17 @@ func newJobExecutor(info jobInfo, sf stepFactory, rc *RunContext) common.Executo
preparers = append(preparers, preparer)
}
stepIdx := stepModel.Number
preExec := step.pre()
stepPreSteps = append(stepPreSteps, useStepLogger(rc, stepModel, stepStagePre, func(ctx context.Context) error {
rc.CurrentStepIndex = stepIdx
preErr := preExec(ctx)
if preErr != nil {
reportStepError(ctx, rc, preErr)
} else if ctx.Err() != nil {
reportStepError(ctx, rc, ctx.Err())
}
return preErr
}))
stepExec := step.main()
steps = append(steps, useStepLogger(rc, stepModel, stepStageMain, func(ctx context.Context) error {
rc.CurrentStepIndex = stepIdx
err := stepExec(ctx)
if err != nil {
runPhase := func(stage stepStage, executor common.Executor) common.Executor {
return useStepLogger(rc, stepModel, stage, func(ctx context.Context) error {
rc.CurrentStepIndex = i
err := executor(ctx)
reportStepError(ctx, rc, err)
} else if ctx.Err() != nil {
reportStepError(ctx, rc, ctx.Err())
}
return nil
}))
postFn := step.post()
postExec := useStepLogger(rc, stepModel, stepStagePost, func(ctx context.Context) error {
rc.CurrentStepIndex = stepIdx
err := postFn(ctx)
if err != nil {
reportStepError(ctx, rc, err)
} else if ctx.Err() != nil {
reportStepError(ctx, rc, ctx.Err())
}
return err
})
return err
})
}
stepPreSteps = append(stepPreSteps, runPhase(stepStagePre, step.pre()))
steps = append(steps, runPhase(stepStageMain, step.main()))
postExec := runPhase(stepStagePost, step.post())
if postExecutor != nil {
// run the post executor in reverse order
postExecutor = postExec.Finally(postExecutor)
@@ -267,37 +209,23 @@ func newJobExecutor(info jobInfo, sf stepFactory, rc *RunContext) common.Executo
// The setup section of the job log. The started hook goes first, so what it sets up is
// in place for the first action download and the first step.
// The pre steps come after it, as steps of their own.
preSteps = append(preSteps, rc.runJobStartedHook)
preSteps = append(preSteps, printPrepareActions(rc, preparers))
preSteps = append(preSteps, printCompleteJobName(rc))
preSteps = append(preSteps, stepPreSteps...)
preSteps = append(preSteps, rc.runJobStartedHook, printPrepareActions(rc, preparers), printCompleteJobName(rc))
runSteps := newStepsExecutor(rc, append(preSteps, stepPreSteps...), steps)
// Ahead of the teardown below, while the job environment is still up.
postExecutor = postExecutor.Finally(useJobStageLogger(StageComplete, rc.runJobCompletedHook))
postExecutor = postExecutor.Finally(useJobStageLogger(StageComplete, func(ctx context.Context) error {
// swallowed: a bad output fails this job, it must not abandon the rest of the plan
if err := info.interpolateOutputs()(ctx); err != nil {
reportStepError(ctx, rc, err)
} else if err := setJobOutputs(ctx, rc); err != nil {
reportStepError(ctx, rc, err)
}
return nil
}))
postExecutor = postExecutor.Finally(useJobStageLogger(StageComplete, func(ctx context.Context) error {
jobError := common.JobError(ctx)
var err error
// always allow 1 min for stopping and removing the runner, even if we were cancelled
ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), jobCleanupTimeout)
reportStepError(ctx, rc, info.interpolateOutputs()(ctx)) // A bad output fails the job without abandoning the plan.
ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), jobCleanupTimeout) // Teardown needs time even after cancellation.
defer cancel()
rc.summaryUploads.wait(ctx)
logger := common.Logger(ctx)
tryUploadJobSummary(ctx, rc)
logger.Infof("Cleaning up container for job %s", rc.JobName)
if err = info.stopContainer()(ctx); err != nil {
err := info.stopContainer()(ctx)
if err != nil {
logger.Errorf("##[error]%s", EscapeCommandData("Error while stop job container: "+err.Error()))
}
setJobResult(ctx, info, rc, jobError == nil)
rc.removeDockerActionImages(ctx)
return err
@@ -305,33 +233,27 @@ func newJobExecutor(info jobInfo, sf stepFactory, rc *RunContext) common.Executo
return common.Executor(func(ctx context.Context) error {
if err := info.startContainer()(ctx); err != nil {
rc.markFailed()
return err
}
return newStepsExecutor(rc, preSteps, steps).Finally(func(ctx context.Context) error {
// Record an interrupt (backstop for interrupts that land outside the main
// step loop) so the post steps observe the cancelled/failed job status.
rc.markInterrupted(ctx.Err())
rc.summaryUploads = newStepSummaryUploads(ctx)
return runSteps.Finally(func(ctx context.Context) error {
rc.markJobInterrupted(ctx) // Post steps must see interrupts that landed after the last main step.
postCtx, cancel := postStepsContext(ctx)
defer cancel()
return postExecutor(postCtx)
})(ctx)
}).Finally(info.closeContainer())
}).Finally(info.closeContainer()).Finally(useJobStageLogger(StageComplete, func(ctx context.Context) error {
rc.markJobInterrupted(ctx)
rc.setJobResult(ctx, common.JobError(ctx) == nil)
return nil
}))
}
// postStepsContext derives the context used to run the job's post/cleanup steps from the
// finished main-pipeline context. Cleanup has to run even when the run was interrupted, so the
// returned context always carries a fresh bounded deadline and is never itself cancelled.
//
// - context.Canceled (server cancel): detach with WithoutCancel under a fresh job-error
// container, so a failing post step cannot turn the cancellation into a failure.
// - context.DeadlineExceeded (job timeout): detach the deadline with WithoutCancel, which
// keeps the original values — including the job-error container — so the timeout failure and
// any post-step error are preserved and the job is still reported as failed.
// - otherwise: run on the live context unchanged.
func postStepsContext(ctx context.Context) (context.Context, context.CancelFunc) {
switch ctx.Err() {
case context.Canceled:
return context.WithTimeout(common.WithJobErrorContainer(context.WithoutCancel(ctx)), 5*time.Minute)
return context.WithTimeout(common.WithJobErrorContainer(context.WithoutCancel(ctx)), 5*time.Minute) // a failed post step cannot replace a server cancellation
case context.DeadlineExceeded:
return context.WithTimeout(context.WithoutCancel(ctx), 5*time.Minute)
default:
@@ -339,105 +261,54 @@ func postStepsContext(ctx context.Context) (context.Context, context.CancelFunc)
}
}
// newStepsExecutor sequences the job's pre steps and main steps.
//
// The pre steps run as a normal pipeline that short-circuits on the first failure or
// cancellation. The main-steps executor then runs unconditionally — even if a pre step failed
// or the job was interrupted — so always()/cancelled()/failure() main steps still run, mirroring
// GitHub Actions. This is safe because each main step re-evaluates its own `if` (a pre-step
// failure flips the expression job status to failure, so success()-default steps skip) and
// newMainStepsExecutor detaches from an interrupted context before running the remaining steps.
//
// A pre-step failure or interrupt is still propagated so the job is reported with the correct
// conclusion; the pre error takes precedence since it happened first.
func newStepsExecutor(rc *RunContext, preSteps, steps []common.Executor) common.Executor {
preExecutor := common.NewPipelineExecutor(preSteps...)
mainExecutor := newMainStepsExecutor(rc, steps)
return func(ctx context.Context) error {
preErr := preExecutor(ctx)
if errors.As(preErr, new(setupError)) {
if _, setupFailed := errors.AsType[setupError](preErr); setupFailed {
return preErr // as on GitHub, no step runs after the job setup failed
}
mainErr := mainExecutor(ctx)
return cmp.Or(preErr, mainErr)
}
}
// newMainStepsExecutor runs the job's main-stage step executors in order. Unlike a plain
// pipeline, an interruption (context.Canceled from a server cancel, or context.DeadlineExceeded
// from the job timeout) does not abandon the remaining steps: it marks the job cancelled when
// appropriate and keeps iterating under a fresh, bounded context so steps whose `if` still
// evaluates true — always() and cancelled() — run for cleanup, mirroring GitHub Actions. Steps
// that default to success() skip themselves because success() is false once the job is no longer
// successful. The main-step wrappers report their own errors and return nil, so the loop drives
// step ordering off the context, not return values.
func newMainStepsExecutor(rc *RunContext, steps []common.Executor) common.Executor {
return func(ctx context.Context) error {
for i, step := range steps {
if ctx.Err() != nil {
return runMainStepsAfterInterrupt(ctx, rc, steps[i:])
if err := ctx.Err(); err != nil {
rc.markJobInterrupted(ctx)
freshCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Minute)
defer cancel()
for _, remaining := range steps[i:] {
_ = remaining(freshCtx)
}
return cmp.Or(preErr, err)
}
_ = step(ctx)
}
// An interrupt can land during the final step, after the loop's last context
// check; record it so the post steps still observe the cancelled/failed status.
rc.markInterrupted(ctx.Err())
return nil
rc.markJobInterrupted(ctx)
return preErr
}
}
// runMainStepsAfterInterrupt runs the remaining main steps after the job context was cancelled or
// timed out. It detaches from the interrupted context (keeping its values: logger and job error)
// and applies a fresh deadline so always()/cancelled() steps run to completion. The original
// interrupt error is returned so callers up the chain still see the job as cancelled/timed out.
func runMainStepsAfterInterrupt(ctx context.Context, rc *RunContext, steps []common.Executor) error {
interruptErr := ctx.Err()
rc.markInterrupted(interruptErr)
freshCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Minute)
defer cancel()
for _, step := range steps {
_ = step(freshCtx)
}
return interruptErr
}
func setJobResult(ctx context.Context, info jobInfo, rc *RunContext, success bool) {
logger := common.Logger(ctx)
func (rc *RunContext) setJobResult(ctx context.Context, success bool) {
success = success && !rc.jobFailed
// Matrix combinations share one *model.Job and run in parallel; serialize the
// read-modify-write of the job result so a failing combination is not lost-updated by a
// concurrent succeeding one.
job := rc.Run.Job()
var continueOnError bool
if !success && !rc.jobCancelled {
// Use a fresh context so an expired job timeout cannot block expression evaluation.
evalCtx := common.WithLogger(context.Background(), common.Logger(ctx))
continueOnError = evaluateJobContinueOnError(evalCtx, rc, job)
continueOnError = evaluateJobContinueOnError(context.WithoutCancel(ctx), rc, job)
}
jobResult := func() string {
defer lockJob(job)()
result := "success"
// we have only one result for a whole matrix build, so we need
// to keep an existing result state if we run a matrix
if len(info.matrix()) > 0 && job.Result != "" {
result = job.Result
}
// cancelled is sticky, so a sibling combination finishing last cannot mask it
switch {
case rc.jobCancelled:
result = "cancelled"
case !success && result != "cancelled":
result = "failure"
job.SetContinueOnError(continueOnError)
}
info.result(result)
return result
}()
defer lockJob(job)() // matrix combinations share this result and its caller notification
jobResult := "success"
if rc.jobTotal != 1 && job.Result != "" && job.Result != "skipped" {
jobResult = job.Result
}
switch {
case rc.jobCancelled:
jobResult = "cancelled"
case !success && jobResult != "cancelled":
jobResult = "failure"
job.SetContinueOnError(continueOnError)
}
job.Result = jobResult
if rc.caller != nil {
// set reusable workflow job result
rc.caller.setReusedWorkflowJobResult(rc.Run.JobID, jobResult) // For Gitea
rc.caller.reportedRuns[rc.callerRunIndex] = rc.Run
return
}
@@ -449,7 +320,7 @@ func setJobResult(ctx context.Context, info jobInfo, rc *RunContext, success boo
jobResultMessage = "cancelled"
}
logger.With("jobResult", jobResult).Infof("Job %s", jobResultMessage)
common.Logger(ctx).With("jobResult", jobResult).Infof("Job %s", jobResultMessage)
}
// evaluateJobEnv returns the workflow and job env evaluated, as far as it got on error, leaving rc.Env raw.
@@ -492,35 +363,49 @@ func evaluateJobEnvAndDefaults(ctx context.Context, rc *RunContext) error {
return model.DecodeEvaluated("container env", rc.containerEnv, rc.ExprEval.shared(ctx).EvaluateYamlNode, &rc.containerSpec.Env)
}
func setJobOutputs(ctx context.Context, rc *RunContext) error {
if rc.caller == nil {
return nil
}
callerOutputs, err := rc.NewExpressionEvaluator(ctx).shared(ctx).EvaluateWorkflowCallOutputs(rc.Run.Workflow.WorkflowCallConfig())
if err != nil {
return fmt.Errorf("unable to interpolate workflow %w", err)
}
type jobTimeout time.Duration
// Matrix combinations of a reusable-workflow caller share the caller's *model.Job;
// serialize the write so parallel combos don't race on its Outputs field.
callerJob := rc.caller.runContext.Run.Job()
defer lockJob(callerJob)()
callerJob.Outputs = callerOutputs
return nil
func (timeout jobTimeout) Error() string {
return fmt.Sprintf("The job has exceeded the maximum execution time of %s", time.Duration(timeout))
}
// applyJobTimeout applies the job-level timeout-minutes to ctx, mirroring the
// step-level evaluateStepTimeout in step.go.
func applyJobTimeout(ctx context.Context, rc *RunContext, job *model.Job) (context.Context, context.CancelFunc) {
timeout, err := rc.ExprEval.Interpolate(ctx, job.TimeoutMinutes)
if err != nil {
common.Logger(ctx).Errorf("An error occurred when attempting to determine the job timeout: %s", err)
} else if timeout != "" {
if timeoutMinutes, err := strconv.ParseInt(timeout, 10, 64); err == nil && timeoutMinutes > 0 {
return context.WithTimeout(ctx, time.Duration(timeoutMinutes)*time.Minute)
func (jobTimeout) Unwrap() error { return context.DeadlineExceeded }
type jobTimeoutCancellation struct{}
func (jobTimeoutCancellation) Error() string { return "The operation was canceled." }
func (jobTimeoutCancellation) Unwrap() error { return context.Canceled }
func (rc *RunContext) markJobInterrupted(ctx context.Context) {
switch ctx.Err() {
case context.Canceled:
rc.markCancelled()
case context.DeadlineExceeded:
if timeout, ok := context.Cause(ctx).(jobTimeout); ok {
if !rc.jobCancelled {
common.Logger(ctx).Errorf("##[error]%s", timeout)
}
rc.markCancelled()
} else {
rc.jobTimedOut = true
rc.markFailed()
}
}
return ctx, func() {}
}
func applyJobTimeout(ctx context.Context, rc *RunContext, job *model.Job) (context.Context, context.CancelFunc, error) {
if raw := job.TimeoutMinutes; raw != "" {
minutes, err := rc.ExprEval.shared(ctx).EvaluateTimeoutMinutes(raw)
if err != nil {
return nil, nil, fmt.Errorf("Error when evaluating 'timeout-minutes' for job '%s'. %w", rc.Run.JobID, err)
}
if minutes > 0 {
timeout := time.Duration(minutes) * time.Minute
ctx, cancel := context.WithTimeoutCause(ctx, timeout, jobTimeout(timeout))
return ctx, cancel, nil
}
}
return ctx, func() {}, nil
}
// evaluateJobContinueOnError evaluates the job-level continue-on-error expression.
@@ -537,70 +422,127 @@ func evaluateJobContinueOnError(ctx context.Context, rc *RunContext, job *model.
return continueOnError
}
func tryUploadJobSummary(ctx context.Context, rc *RunContext) {
if rc == nil || rc.JobContainer == nil || rc.Config == nil {
type stepSummaryUpload struct {
done chan struct{}
status int
err error
}
type stepSummaryUploads struct {
ctx context.Context
cancel context.CancelFunc
steps []*stepSummaryUpload
}
func newStepSummaryUploads(ctx context.Context) *stepSummaryUploads {
uploadCtx, cancel := context.WithCancel(context.WithoutCancel(ctx))
return &stepSummaryUploads{ctx: uploadCtx, cancel: cancel}
}
func (uploads *stepSummaryUploads) wait(ctx context.Context) {
defer uploads.cancel()
if len(uploads.steps) == 0 {
return
}
// Bound the whole upload phase so a slow or unreachable endpoint cannot consume
// the job cleanup budget reserved for stopping and removing the container.
ctx, cancel := context.WithTimeout(ctx, jobSummaryUploadPhaseTimeout)
ctx, cancel := context.WithTimeout(ctx, jobSummaryUploadPhaseTimeout) // A slow endpoint must leave time for teardown.
defer cancel()
env := rc.GetEnv()
logger := common.Logger(ctx)
for _, upload := range uploads.steps {
select {
case <-upload.done:
if upload.err != nil {
logger.WithError(upload.err).Warn("job summary upload failed")
} else if upload.status/100 != 2 {
logger.Warnf("job summary upload failed: status=%d", upload.status)
}
case <-ctx.Done():
logger.WithError(ctx.Err()).Warn("job summary upload timed out")
return
}
}
}
func processStepSummary(ctx context.Context, rc *RunContext, summaryPath string) {
job := rc.topLevelRunContext()
uploads := job.summaryUploads
if uploads == nil {
return
}
env := job.GetEnv()
if !hasJobSummaryCapability(env["GITEA_ACTIONS_CAPABILITIES"]) {
// Server did not advertise support. Do not attempt upload.
return
}
if rc != job {
job.Masks = appendUniqueMasks(slices.Clip(job.Masks), rc.Masks) // composite masks must survive later writes to the child's slice
return
}
runtimeURL := strings.TrimSpace(env["ACTIONS_RUNTIME_URL"])
runtimeToken := strings.TrimSpace(env["ACTIONS_RUNTIME_TOKEN"])
runID := strings.TrimSpace(env["GITEA_RUN_ID"])
if runtimeURL == "" || runtimeToken == "" || runID == "" {
return
}
if rc.Run == nil || rc.Run.Job() == nil {
return
}
// The numeric ActionRunJob ID is not exposed in the proto Task message or task context,
// but the server signs it into the ACTIONS_RUNTIME_TOKEN JWT claims. We decode the
// unverified claims to retrieve it; the server re-verifies the token on the request.
jobID := extractJobIDFromRuntimeToken(runtimeToken)
if jobID <= 0 {
if runtimeURL == "" || runID == "" || jobID <= 0 {
return
}
base := strings.TrimRight(runtimeURL, "/") + "/_apis/pipelines/workflows/" + runID +
"/jobs/" + strconv.FormatInt(jobID, 10) + "/steps/"
actPath := rc.JobContainer.GetActPath()
// Reuse a single client across all step uploads so connections can be pooled.
client := &http.Client{Timeout: jobSummaryUploadRequestTimeout, Transport: rc.Config.instanceTransportFor(base)}
maskers := rc.secretMaskers()
longestMask := 0
for i := 0; i < len(maskers); i += 2 {
longestMask = max(longestMask, len(maskers[i]))
body := readStepSummary(ctx, rc, summaryPath)
if len(body) == 0 {
return
}
url := fmt.Sprintf("%s/_apis/pipelines/workflows/%s/jobs/%d/steps/%d/summary", strings.TrimRight(runtimeURL, "/"), runID, jobID, rc.CurrentStepIndex)
transport := rc.Config.instanceTransportFor(url)
var previousDone <-chan struct{}
if last := len(uploads.steps) - 1; last >= 0 {
previousDone = uploads.steps[last].done
}
upload := &stepSummaryUpload{done: make(chan struct{})}
uploads.steps = append(uploads.steps, upload)
uploadCtx := uploads.ctx
go func() {
defer close(upload.done)
defer common.RecoverPanic(&upload.err)
if previousDone != nil {
select {
case <-previousDone:
case <-uploadCtx.Done():
return
}
}
if uploadCtx.Err() == nil {
upload.status, upload.err = uploadJobSummary(uploadCtx, &http.Client{Timeout: 5 * time.Second, Transport: transport}, url, runtimeToken, body)
}
}()
}
func readStepSummary(ctx context.Context, rc *RunContext, summaryPath string) []byte {
ctx, cancel := context.WithTimeout(ctx, jobSummaryUploadPhaseTimeout)
defer cancel()
var maskers []string
limit := protocol.MaxStepSummarySize
body, _ := readContainerFile(ctx, rc.JobContainer, summaryPath, func() int64 {
maskers = rc.secretMaskers()
for i := 0; i < len(maskers); i += 2 {
limit = max(limit, protocol.MaxStepSummarySize+len(maskers[i]))
}
return int64(limit + 1)
})
if len(body) == 0 {
return nil
}
masker := NewSecretReplacer(maskers)
limit := maxJobSummaryBytes + longestMask
for i := range rc.Run.Job().Steps {
summaryPath := container.JoinPath(actPath, "workflow", "step-summary-"+strconv.Itoa(i)+".md")
body, ok := readSingleFileFromContainerArchive(ctx, rc.JobContainer, summaryPath, int64(limit+1))
if !ok || len(body) == 0 {
continue
masked := masker.Replace(string(body))
split := len(body) > limit
if split { // the read can end inside a secret, so keep only what masks alike without the lookahead
unsplit := masker.Replace(string(body[:protocol.MaxStepSummarySize]))
kept := 0
for kept < len(unsplit) && kept < len(masked) && unsplit[kept] == masked[kept] {
kept++
}
masked := masker.Replace(string(body))
split := len(body) > limit
if split { // the read can end inside a secret, so keep only what masks alike without the lookahead
unsplit := masker.Replace(string(body[:maxJobSummaryBytes]))
kept := 0
for kept < len(unsplit) && kept < len(masked) && unsplit[kept] == masked[kept] {
kept++
}
for kept > 0 && kept < len(masked) && !utf8.RuneStart(masked[kept]) {
kept--
}
masked = masked[:kept]
for kept > 0 && kept < len(masked) && !utf8.RuneStart(masked[kept]) {
kept--
}
body = truncateJobSummary(ctx, []byte(masked), summaryPath, maxJobSummaryBytes, split)
uploadJobSummary(ctx, client, base+strconv.Itoa(i)+"/summary", runtimeToken, body)
masked = masked[:kept]
}
return truncateJobSummary(ctx, []byte(masked), summaryPath, protocol.MaxStepSummarySize, split)
}
// For Gitea
@@ -638,37 +580,17 @@ func hasJobSummaryCapability(caps string) bool {
}), "job-summary")
}
func uploadJobSummary(ctx context.Context, client *http.Client, url, runtimeToken string, body []byte) {
logger := common.Logger(ctx)
var lastStatus int
var lastErr error
for attempt := 0; attempt < 2; attempt++ {
status, err := putJobSummary(ctx, client, url, runtimeToken, body)
if err == nil && status/100 == 2 {
return
}
lastStatus = status
lastErr = err
if attempt == 1 || !isTransientJobSummaryUploadFailure(status, err) {
break
}
timer := time.NewTimer(jobSummaryUploadRetryDelay)
select {
case <-ctx.Done():
timer.Stop()
lastErr = ctx.Err()
attempt = 1
case <-timer.C:
}
func uploadJobSummary(ctx context.Context, client *http.Client, url, runtimeToken string, body []byte) (int, error) {
status, err := putJobSummary(ctx, client, url, runtimeToken, body)
if !isTransientJobSummaryUploadFailure(status, err) {
return status, err
}
// Best-effort only; do not fail job, but log because capability was advertised.
if lastErr != nil {
logger.WithError(lastErr).Warn("job summary upload failed")
return
select {
case <-ctx.Done():
return status, ctx.Err()
case <-time.After(time.Second):
return putJobSummary(ctx, client, url, runtimeToken, body)
}
logger.Warnf("job summary upload failed: status=%d", lastStatus)
}
func putJobSummary(ctx context.Context, client *http.Client, url, runtimeToken string, body []byte) (int, error) {
@@ -693,6 +615,10 @@ func isTransientJobSummaryUploadFailure(status int, err error) bool {
}
func readSingleFileFromContainerArchive(ctx context.Context, env container.ExecutionsEnvironment, p string, maxBytes int64) ([]byte, bool) {
return readContainerFile(ctx, env, p, func() int64 { return maxBytes })
}
func readContainerFile(ctx context.Context, env container.ExecutionsEnvironment, p string, limit func() int64) ([]byte, bool) {
rc, err := env.GetContainerArchive(ctx, p)
if err != nil {
return nil, false
@@ -713,7 +639,10 @@ func readSingleFileFromContainerArchive(ctx context.Context, env container.Execu
if entryName != requestedPath && entryName != path.Base(requestedPath) {
continue
}
b, err := io.ReadAll(io.LimitReader(transform.NewReader(tr, unicodeencoding.BOMOverride(unicodeencoding.UTF8.NewDecoder())), maxBytes))
if header.Size == 0 {
return []byte{}, true
}
b, err := io.ReadAll(io.LimitReader(transform.NewReader(tr, unicodeencoding.BOMOverride(unicodeencoding.UTF8.NewDecoder())), limit()))
if err != nil {
return nil, false
}

File diff suppressed because it is too large Load Diff

View File

@@ -10,31 +10,11 @@ import (
"gitea.dev/actionslib/pkg/model"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.yaml.in/yaml/v4"
)
func TestMaxParallelStrategy(t *testing.T) {
for _, tt := range []struct {
name string
maxParallelString string
expectedMaxParallel int
}{
{"max-parallel-1", "1", 1},
{"max-parallel-2", "2", 2},
{"max-parallel-default", "", 4},
{"max-parallel-10-clamped-to-combinations", "10", 5},
{"max-parallel-invalid-falls-back-to-default", "tow", 4},
} {
t.Run(tt.name, func(t *testing.T) {
var rawMatrix yaml.Node
require.NoError(t, rawMatrix.Encode(map[string][]any{"version": {1, 2, 3, 4, 5}}))
job := &model.Job{Strategy: &model.Strategy{MaxParallelString: tt.maxParallelString, RawMatrix: rawMatrix}}
matrixes, err := job.GetMatrixes()
require.NoError(t, err)
require.Len(t, matrixes, 5)
assert.Equal(t, tt.expectedMaxParallel, maxParallelFor(job.Strategy, len(matrixes)))
})
for limit, want := range map[string]int{"1": 1, "": 4, "10": 5, "tow": 4} {
assert.Equal(t, want, maxParallelFor(&model.Strategy{MaxParallelString: limit}, 5), limit)
}
t.Run("deferred strategy", func(t *testing.T) {
@@ -59,29 +39,20 @@ jobs:
}
func TestNewPlanExecutorInvalidMatrix(t *testing.T) {
var rawMatrix yaml.Node
require.NoError(t, rawMatrix.Encode(map[string]any{
"config": map[string]any{"nested": "value"},
}))
plan := &model.Plan{Stages: []*model.Stage{{Runs: []*model.Run{{
Workflow: &model.Workflow{Jobs: map[string]*model.Job{
"test": {Strategy: &model.Strategy{RawMatrix: rawMatrix}},
}},
JobID: "test",
}}}}}
runner := &runnerImpl{config: &Config{Env: testCheckoutEnv()}}
require.ErrorContains(t, runner.NewPlanExecutor(plan)(t.Context()), "could not get job matrix:")
for _, strategy := range []string{
`${{ fromJSON('invalid') }}`,
`${{ '${{ inputs.unresolved }}' }}`,
for strategy, want := range map[string]string{
`{matrix: {config: {nested: value}}}`: "could not get job matrix:",
`${{ fromJSON('invalid') }}`: "job strategy",
`${{ '${{ inputs.unresolved }}' }}`: "job strategy",
`{matrix: {x: [a, "${{ fromJSON('not json') }}"]}}`: "Error when evaluating 'strategy' for job 'job1'.",
} {
t.Run(strategy, func(t *testing.T) {
workflow, err := model.ReadWorkflow(strings.NewReader("jobs:\n test:\n strategy: " + strategy))
workflow, err := model.ReadWorkflow(strings.NewReader("jobs:\n job1:\n strategy: " + strategy))
require.NoError(t, err)
require.Error(t, runner.NewPlanExecutor(&model.Plan{Stages: []*model.Stage{{Runs: []*model.Run{{Workflow: workflow, JobID: "test"}}}}})(t.Context()))
plan, err := model.CombineWorkflowPlanner(workflow).PlanAll()
require.NoError(t, err)
require.ErrorContains(t, runner.NewPlanExecutor(plan)(t.Context()), want)
assert.Equal(t, "failure", workflow.Jobs["job1"].Result)
})
}
}

447
act/runner/node.go Normal file
View File

@@ -0,0 +1,447 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package runner
import (
"archive/tar"
"cmp"
"compress/gzip"
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json/v2"
"errors"
"fmt"
"io"
"net/http"
"os"
"path"
"path/filepath"
"runtime"
"slices"
"strings"
"sync"
"time"
"gitea.com/gitea/runner/act/common"
"gitea.com/gitea/runner/act/common/logging"
"gitea.com/gitea/runner/act/container"
"golang.org/x/sync/singleflight"
)
type nodeBuild struct{ goos, goarch, loader, name, version, sha256 string }
func (build nodeBuild) release() string { return "node-v" + build.version + "-" + build.name }
var nodeBuilds = []nodeBuild{
// renovate: datasource=custom.nodejs
{"linux", "amd64", "/lib64/ld-linux-x86-64.so.2", "linux-x64", "24.22.3", "061ec3e3062115705b56b51fa9cc330ab50d34b6969387d4e4b1a50c6809acc2"},
// renovate: datasource=custom.nodejs
{"linux", "arm64", "/lib/ld-linux-aarch64.so.1", "linux-arm64", "24.22.3", "261af2af250dfd7e9f25cf151d1b2713a0adf8f10a9ad116c4947f68627affe8"},
// renovate: datasource=custom.alpine-nodejs
{"linux", "amd64", "/lib/ld-musl-x86_64.so.1", "alpine-x64", "24.22.3", "07fae3d6173ae8bc6529df8a4b3c070d80f94e95bd816982c4af253acf7c2b51"},
// renovate: datasource=custom.nodejs
{"darwin", "amd64", "", "darwin-x64", "24.22.3", "977614af0504c81045e7fd85596dbca0e5f951b96681516dadafedcca8c447f7"},
// renovate: datasource=custom.nodejs
{"darwin", "arm64", "", "darwin-arm64", "24.22.3", "ff6e17d4874b76d272212b908cc020d6e815fba5a6c7eaaa06add725840307fd"},
// renovate: datasource=custom.nodejs
{"windows", "amd64", "", "win-x64", "24.22.3", "86fc4785327db5f5c7558dc6156c543b433c313e813a222e088086222ab4afa6"},
// renovate: datasource=custom.nodejs
{"windows", "arm64", "", "win-arm64", "24.22.3", "172e320db179ce416fc012b96b9917dacfb442beb081de57c4deaed7b5a24644"},
}
// nodeBuildsFor returns the pinned builds, or for a runner.node_version override the same builds at that version.
func nodeBuildsFor(version string) []nodeBuild {
if version == "" {
return nodeBuilds
}
builds := slices.Clone(nodeBuilds)
for i := range builds {
builds[i].version, builds[i].sha256 = version, ""
}
return builds
}
func (c *Config) nodeVolume() string {
return nodeVolumePrefix + cmp.Or(c.NodeVersion, nodeBuilds[0].version) // the other builds' releases join it under their own names
}
const (
nodeVolumePrefix = "gitea-runner-node-v"
nodeComplete = "complete" // the last entry of a node tar, so a binary beside it is whole
)
var (
nodeDownloads singleflight.Group
nodeFailures sync.Map // binary path to the time.Time its download last failed
nodeSeeding = make(chan struct{}, 1)
)
// PrefetchNode starts downloading the builds the runner's jobs need, so jobs find them cached.
func PrefetchNode(cacheDir, version string, host, docker, kubernetes bool) {
for _, build := range nodeBuildsFor(version) {
linux := build.goarch == runtime.GOARCH && strings.HasPrefix(build.name, "linux-")
if host && nodeFitsHost(build) || (docker || kubernetes) && linux {
go func() {
binary, err := downloadNode(context.Background(), filepath.Join(cacheDir, "node"), build)
if err == nil && kubernetes && linux {
_, _ = nodeArchive(binary, build.release())
}
}()
}
}
}
func (rc *RunContext) node(ctx context.Context) string {
job := rc.topLevelRunContext()
if job.nodePath != "" {
return job.nodePath
}
node := job.provisionNode(ctx)
if ctx.Err() == nil { // a cancelled first use must not pin the fallback on later steps
job.nodePath = node
}
return node
}
func (rc *RunContext) provisionNode(ctx context.Context) string {
_, host := rc.JobContainer.(*container.HostEnvironment)
seeder, seeds := rc.JobContainer.(interface {
SeedVolume(volume, prefix, marker string, write func(io.Writer) error) common.Executor
})
extractor, extracts := rc.JobContainer.(interface {
ExtractTarGz(destPath, archive string) common.Executor
})
if rc.Config.NoNodeDownload || common.Dryrun(ctx) || !host && !seeds && !extracts {
return "node"
}
cache, dir := filepath.Join(rc.ActionCacheDir(), "node"), path.Join(rc.JobContainer.GetActPath(), "node")
reason := errors.New("no build matches the job's platform")
for _, build := range nodeBuildsFor(rc.Config.NodeVersion) {
if !rc.nodeFits(ctx, host, build) {
continue
}
release := build.release()
node := path.Join(dir, release, "bin", "node")
if host {
if node, reason = downloadNode(ctx, cache, build); reason != nil {
continue
}
}
probe := rc.JobContainer.Exec([]string{node, "--version"}, map[string]string{"NODE_OPTIONS": ""}, "", "")
install := probe
switch {
case seeds:
install = func(ctx context.Context) error {
if probe(ctx) == nil {
return nil
}
binary, err := downloadNode(ctx, cache, build)
if err != nil {
return err
}
select {
case nodeSeeding <- struct{}{}:
defer func() { <-nodeSeeding }()
case <-ctx.Done():
return ctx.Err()
}
return seeder.SeedVolume(rc.Config.nodeVolume(), nodeVolumePrefix, path.Join(release, nodeComplete), func(out io.Writer) error { return writeNodeTar(out, binary, release) }).Then(probe)(ctx)
}
case extracts:
install = func(ctx context.Context) error {
binary, err := downloadNode(ctx, cache, build)
if err != nil {
return err
}
archive, err := nodeArchive(binary, release)
if err != nil {
return err
}
return extractor.ExtractTarGz(dir, archive).Then(probe)(ctx)
}
}
stdout, stderr := rc.JobContainer.ReplaceLogWriter(io.Discard, io.Discard)
reason = install(ctx)
rc.JobContainer.ReplaceLogWriter(stdout, stderr)
if reason == nil {
return node
}
}
logging.Infof("%s: the runner's Node.js is unavailable: %v", rc, reason) // the job log gets no reason, it may hold host paths
common.Logger(ctx).Infof("JavaScript actions use the node on PATH, the runner's Node.js is unavailable")
return "node"
}
func (rc *RunContext) nodeFits(ctx context.Context, host bool, build nodeBuild) bool {
if host {
return nodeFitsHost(build)
}
return build.goos == "linux" && rc.containerHas(ctx, build.loader)
}
func (rc *RunContext) containerHas(ctx context.Context, file string) bool {
archive, err := rc.JobContainer.GetContainerArchive(ctx, file)
if err == nil {
_ = archive.Close()
}
return err == nil
}
func nodeFitsHost(build nodeBuild) bool {
_, err := os.Stat(build.loader)
return build.goos == runtime.GOOS && build.goarch == runtime.GOARCH && (build.loader == "" || err == nil)
}
func downloadNode(ctx context.Context, dir string, build nodeBuild) (string, error) {
dir, err := filepath.Abs(dir)
if err != nil {
return "", err
}
pruneNode(dir)
version := filepath.Join(dir, build.release())
binary := filepath.Join(version, "bin", "node")
if build.goos == "windows" {
binary += ".exe"
}
if _, err := os.Stat(binary); err == nil {
now := time.Now()
_ = os.Chtimes(version, now, now)
return binary, nil
}
failed, retry := nodeFailures.Load(binary)
if failedAt, _ := failed.(time.Time); time.Since(failedAt) < 10*time.Minute {
return "", errors.New("its download failed recently")
}
download := nodeDownloads.DoChan(binary, func() (any, error) {
if _, err := os.Stat(binary); err == nil {
return binary, nil
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
defer cancel()
if err := fetchNode(ctx, dir, binary, build); err != nil {
nodeFailures.Store(binary, time.Now())
logging.Warnf("downloading Node.js %s for JavaScript actions failed: %v", build.version, err)
return nil, err
}
return binary, nil
})
if retry { // jobs wait only for a first download and at most a minute, so a slow or failing mirror holds up no later job
return "", errors.New("its download failed before")
}
select {
case result := <-download:
return binary, result.Err
case <-time.After(time.Minute):
return "", errors.New("still downloading")
case <-ctx.Done():
return "", ctx.Err()
}
}
// pruneNode removes other versions no runner used for a week, and downloads abandoned for an hour.
func pruneNode(dir string) {
entries, _ := os.ReadDir(dir)
for _, entry := range entries {
info, err := entry.Info()
if err != nil || slices.ContainsFunc(nodeBuilds, func(build nodeBuild) bool { return build.release() == entry.Name() }) {
continue
}
age := time.Since(info.ModTime())
if strings.HasPrefix(entry.Name(), "node-v") && age > 7*24*time.Hour || strings.HasPrefix(entry.Name(), ".node-") && age > time.Hour {
_ = os.RemoveAll(filepath.Join(dir, entry.Name()))
}
}
}
func nodeBase(build nodeBuild) string {
return strings.TrimSuffix(cmp.Or(os.Getenv("NODEJS_ORG_MIRROR"), "https://nodejs.org/dist"), "/") + "/v" + build.version + "/"
}
func nodeSource(build nodeBuild) (url, entry string) {
name := build.release() + ".tar.gz"
switch {
case build.name == "alpine-x64": // nodejs.org's musl build needs libstdc++, GitHub's links it statically
return "https://github.com/actions/alpine_nodejs/releases/download/v" + build.version + "/" + name, "bin/node"
case build.goos == "windows":
return nodeBase(build) + build.name + "/node.exe", ""
default:
return nodeBase(build) + name, build.release() + "/bin/node"
}
}
// nodeSum returns the pinned SHA-256 of build, or for a runner.node_version override the one published beside it.
func nodeSum(ctx context.Context, build nodeBuild, url string) (string, error) {
if build.sha256 != "" {
return build.sha256, nil
}
if build.name == "alpine-x64" {
body, err := nodeGet(ctx, "https://api.github.com/repos/actions/alpine_nodejs/releases/tags/v"+build.version)
if err != nil {
return "", err
}
defer body.Close()
var release struct {
Assets []struct {
Name string `json:"name"`
Digest string `json:"digest"`
} `json:"assets"`
}
if err := json.UnmarshalRead(body, &release); err != nil {
return "", err
}
for _, asset := range release.Assets {
if sum, ok := strings.CutPrefix(asset.Digest, "sha256:"); ok && asset.Name == path.Base(url) {
return sum, nil
}
}
} else {
body, err := nodeGet(ctx, nodeBase(build)+"SHASUMS256.txt")
if err != nil {
return "", err
}
defer body.Close()
sums, err := io.ReadAll(body)
if err != nil {
return "", err
}
for line := range strings.Lines(string(sums)) {
if sum, ok := strings.CutSuffix(strings.TrimSpace(line), " "+strings.TrimPrefix(url, nodeBase(build))); ok {
return sum, nil
}
}
}
return "", fmt.Errorf("no SHA-256 is published for %s", path.Base(url))
}
func fetchNode(ctx context.Context, dir, binary string, build nodeBuild) error {
url, entry := nodeSource(build)
sum, err := nodeSum(ctx, build, url)
if err != nil {
return err
}
body, err := nodeGet(ctx, url)
if err != nil {
return err
}
defer body.Close()
if err := os.MkdirAll(dir, 0o755); err != nil {
return err
}
tmp, err := os.CreateTemp(dir, ".node-*")
if err != nil {
return err
}
defer os.Remove(tmp.Name())
defer tmp.Close()
if err := tmp.Chmod(0o755); err != nil {
return err
}
hash := sha256.New()
node := io.TeeReader(body, hash)
if entry != "" {
if node, err = gzipTarEntry(node, entry); err != nil {
return err
}
}
if _, err := io.Copy(tmp, node); err != nil {
return err
}
if _, err := io.Copy(hash, body); err != nil {
return err
}
if got := hex.EncodeToString(hash.Sum(nil)); got != sum {
return fmt.Errorf("%s has checksum %s, %s is expected", build.release(), got, sum)
}
if err := tmp.Close(); err != nil {
return err
}
if err := os.MkdirAll(filepath.Dir(binary), 0o755); err != nil {
return err
}
if err := os.Rename(tmp.Name(), binary); err != nil {
if _, statErr := os.Stat(binary); statErr != nil { // Windows cannot replace a node.exe another runner installed and runs
return err
}
}
return nil
}
// nodeArchive compresses the binary once for all Kubernetes jobs, which extract it in their pods.
func nodeArchive(binary, release string) (string, error) {
archive := binary + ".tar.gz"
_, err, _ := nodeDownloads.Do(archive, func() (any, error) {
if _, err := os.Stat(archive); err == nil {
return archive, nil
}
tmp, err := os.CreateTemp(filepath.Dir(binary), ".node-*")
if err != nil {
return nil, err
}
defer os.Remove(tmp.Name())
compressed := gzip.NewWriter(tmp)
if err := errors.Join(tmp.Chmod(0o644), writeNodeTar(compressed, binary, release), compressed.Close(), tmp.Close()); err != nil {
return nil, err
}
return archive, os.Rename(tmp.Name(), archive)
})
return archive, err
}
func gzipTarEntry(archive io.Reader, name string) (io.Reader, error) {
unzipped, err := gzip.NewReader(archive)
if err != nil {
return nil, err
}
files := tar.NewReader(unzipped)
for {
header, err := files.Next()
if err != nil {
return nil, fmt.Errorf("finding %s: %w", name, err)
}
if strings.TrimPrefix(header.Name, "./") == name && header.Typeflag == tar.TypeReg {
return files, nil
}
}
}
func writeNodeTar(out io.Writer, binary, release string) error {
file, err := os.Open(binary)
if err != nil {
return err
}
defer file.Close()
info, err := file.Stat()
if err != nil {
return err
}
writer := tar.NewWriter(out)
if err := writer.WriteHeader(&tar.Header{Typeflag: tar.TypeReg, Name: release + "/bin/node", Mode: 0o755, Size: info.Size()}); err != nil {
return err
}
if _, err := io.Copy(writer, file); err != nil {
return err
}
if err := writer.WriteHeader(&tar.Header{Typeflag: tar.TypeReg, Name: release + "/" + nodeComplete, Mode: 0o644}); err != nil {
return err
}
return writer.Close()
}
func nodeGet(ctx context.Context, url string) (io.ReadCloser, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
_ = resp.Body.Close()
return nil, fmt.Errorf("GET %s: %s", req.URL.Redacted(), resp.Status)
}
return resp.Body, nil
}

116
act/runner/node_test.go Normal file
View File

@@ -0,0 +1,116 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package runner
import (
"archive/tar"
"bytes"
"compress/gzip"
"crypto/sha256"
"encoding/hex"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
"gitea.com/gitea/runner/act/common"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
)
type tarCopyingContainer struct{ containerMock }
func (*tarCopyingContainer) ExtractTarGz(_destPath, _archive string) common.Executor { return nil }
func TestNodeUsesPATHWhenDisabledOrUnsupported(t *testing.T) {
noLoader := &tarCopyingContainer{}
noLoader.On("GetContainerArchive", mock.Anything, mock.Anything).Return(nil, os.ErrNotExist)
for _, rc := range []*RunContext{
{Config: &Config{NoNodeDownload: true}},
{Config: &Config{}, JobContainer: noLoader},
} {
assert.Equal(t, "node", rc.node(t.Context()))
}
noLoader.AssertCalled(t, "GetContainerArchive", mock.Anything, mock.Anything)
}
func TestDownloadNodeVerifiesChecksumPrunesAndArchivesOnlyTheBinary(t *testing.T) {
name := "node-v24.0.0-linux-x64"
var archive bytes.Buffer
gz, err := gzip.NewWriterLevel(&archive, gzip.NoCompression)
require.NoError(t, err)
_, err = gz.Write(tarArchive(t, tarEntry{name: name + "/bin/node", body: "node binary"}, tarEntry{name: name + "/README.md", body: strings.Repeat("tail", 1<<15)}))
require.NoError(t, err)
require.NoError(t, gz.Close())
sum, exeSum := sha256.Sum256(archive.Bytes()), sha256.Sum256([]byte("node.exe binary"))
linux := nodeBuild{goos: "linux", name: "linux-x64", version: "24.0.0", sha256: hex.EncodeToString(sum[:])}
server := httptest.NewServer(http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) {
switch request.URL.Path {
case "/v24.0.0/" + name + ".tar.gz":
_, _ = response.Write(archive.Bytes())
case "/v24.0.0/win-x64/node.exe":
_, _ = io.WriteString(response, "node.exe binary")
case "/v24.0.0/SHASUMS256.txt":
_, _ = io.WriteString(response, hex.EncodeToString(exeSum[:])+" win-x64/node.exe\n")
default:
http.NotFound(response, request)
}
}))
defer server.Close()
t.Setenv("NODEJS_ORG_MIRROR", server.URL+"/")
dir := t.TempDir()
stale, abandoned, unrelated := filepath.Join(dir, "node-v1.0.0-linux-x64"), filepath.Join(dir, ".node-123"), filepath.Join(dir, "reports")
for _, old := range []string{stale, abandoned, unrelated} {
require.NoError(t, os.Mkdir(old, 0o755))
require.NoError(t, os.Chtimes(old, time.Time{}, time.Now().Add(-8*24*time.Hour)))
}
binary, err := downloadNode(t.Context(), dir, linux)
require.NoError(t, err)
assert.NoDirExists(t, stale)
assert.NoDirExists(t, abandoned)
assert.DirExists(t, unrelated)
assert.Equal(t, filepath.Join(dir, name, "bin", "node"), binary)
archived, err := nodeArchive(binary, name)
require.NoError(t, err)
cached, err := os.Open(archived)
require.NoError(t, err)
defer cached.Close()
unzipped, err := gzip.NewReader(cached)
require.NoError(t, err)
reader := tar.NewReader(unzipped)
header, err := reader.Next()
require.NoError(t, err)
assert.Equal(t, name+"/bin/node", header.Name)
assert.Equal(t, int64(0o755), header.Mode)
body, err := io.ReadAll(reader)
require.NoError(t, err)
assert.Equal(t, "node binary", string(body))
header, err = reader.Next()
require.NoError(t, err)
assert.Equal(t, name+"/"+nodeComplete, header.Name)
_, err = reader.Next()
require.ErrorIs(t, err, io.EOF)
binary, err = downloadNode(t.Context(), dir, nodeBuild{goos: "windows", name: "win-x64", version: "24.0.0"})
require.NoError(t, err)
assert.Equal(t, filepath.Join(dir, "node-v24.0.0-win-x64", "bin", "node.exe"), binary)
body, err = os.ReadFile(binary)
require.NoError(t, err)
assert.Equal(t, "node.exe binary", string(body))
linux.sha256 = strings.Repeat("0", 64)
dir = t.TempDir()
_, err = downloadNode(t.Context(), dir, linux)
require.ErrorContains(t, err, "checksum")
entries, err := os.ReadDir(dir)
require.NoError(t, err)
assert.Empty(t, entries)
}

View File

@@ -5,197 +5,152 @@
package runner
import (
"cmp"
"context"
"fmt"
"net/url"
"path"
"os"
"path/filepath"
"regexp"
"gitea.com/gitea/runner/act/common"
"gitea.com/gitea/runner/act/common/git"
"gitea.dev/actionslib/pkg/expreval"
"gitea.dev/actionslib/pkg/exprparser"
"gitea.dev/actionslib/pkg/model"
)
func newLocalReusableWorkflowExecutor(rc *RunContext) common.Executor {
localWorkflow, err := model.ParseReusableWorkflowUses(rc.Run.Job().Uses)
if err != nil {
return common.NewErrorExecutor(err)
}
preset := rc.Config.PresetGitHubContext
if preset == nil {
// resolve the local workflow against the workspace root, not the process
// working directory, so it is found regardless of where the runner is invoked
return newReusableWorkflowExecutor(rc, rc.Config.Workdir, localWorkflow.Path, false)
}
uses := fmt.Sprintf("%s/%s@%s", preset.Repository, localWorkflow.Path, preset.Sha)
remoteReusableWorkflow, err := newRemoteReusableWorkflow(rc.Config.GitHubInstance, uses)
if err != nil {
return common.NewErrorExecutor(err)
}
workflowDir := fmt.Sprintf("%s/%s", rc.ActionCacheDir(), safeFilename(uses))
return common.NewPipelineExecutor(
cloneRemoteReusableWorkflow(rc, remoteReusableWorkflow.CloneURL(), remoteReusableWorkflow.Ref, workflowDir),
newReusableWorkflowExecutor(rc, workflowDir, remoteReusableWorkflow.Path, true),
)
}
func newRemoteReusableWorkflowExecutor(rc *RunContext) common.Executor {
remoteReusableWorkflow, err := newRemoteReusableWorkflow(rc.Config.GitHubInstance, rc.Run.Job().Uses)
if err != nil {
return common.NewErrorExecutor(err)
}
// uses with safe filename makes the target directory look something like this {owner}-{repo}-.github-workflows-{filename}@{ref}
// instead we will just use {owner}-{repo}@{ref} as our target directory. This should also improve performance when we are using
// multiple reusable workflows from the same repository and ref since for each workflow we won't have to clone it again
filename := fmt.Sprintf("%s/%s@%s", remoteReusableWorkflow.Owner, remoteReusableWorkflow.Repo, remoteReusableWorkflow.Ref)
workflowDir := fmt.Sprintf("%s/%s", rc.ActionCacheDir(), safeFilename(filename))
return common.NewPipelineExecutor(
cloneRemoteReusableWorkflow(rc, remoteReusableWorkflow.CloneURL(), remoteReusableWorkflow.Ref, workflowDir),
newReusableWorkflowExecutor(rc, workflowDir, remoteReusableWorkflow.Path, true),
)
}
// cloneRemoteReusableWorkflow always invokes the clone executor — moving refs
// (branches, tags) must be re-resolved each run, matching GitHub Actions.
//
// Callers must not change remoteReusableWorkflow.URL, because:
// 1. Gitea doesn't support specifying GithubContext.ServerURL by the GITHUB_SERVER_URL env
// 2. Gitea has already full URL with rc.Config.GitHubInstance when calling newRemoteReusableWorkflow
//
// remoteReusableWorkflow.URL = rc.getGithubContext(ctx).ServerURL
func cloneRemoteReusableWorkflow(rc *RunContext, cloneURL, ref, targetDirectory string) common.Executor {
return func(ctx context.Context) error {
interpolatedURL, err := rc.NewExpressionEvaluator(ctx).Interpolate(ctx, cloneURL)
if err != nil {
return fmt.Errorf("unable to interpolate the workflow clone URL: %w", err)
}
return git.NewGitCloneExecutor(rc.Config.withInstanceAuth(git.NewGitCloneExecutorInput{
URL: interpolatedURL,
Ref: ref,
Dir: targetDirectory,
OfflineMode: rc.Config.ActionOfflineMode,
Depth: rc.Config.ActionCloneDepth,
}, rc.Config.GetToken()))(ctx)
}
}
func newReusableWorkflowExecutor(rc *RunContext, directory, workflow string, cached bool) common.Executor {
return func(ctx context.Context) error {
planner, err := func() (model.WorkflowPlanner, error) {
if cached {
unlock, err := git.AcquireCloneLock(ctx, directory)
if err != nil {
return nil, err
}
defer unlock()
}
return model.NewWorkflowPlanner(path.Join(directory, workflow), true)
}()
if err != nil {
return err
}
plan, err := planner.PlanEvent("workflow_call")
if err != nil {
return err
}
runner, err := (&runnerImpl{
config: rc.Config,
caller: &caller{
runContext: rc,
reusedWorkflowJobResults: map[string]string{},
},
}).configure()
if err != nil {
return err
}
return common.NewPipelineExecutor( // For Gitea
runner.NewPlanExecutor(plan),
setReusedWorkflowCallerResult(rc, runner),
)(ctx)
}
}
type remoteReusableWorkflow struct {
*model.ReusableWorkflowUses
URL string
}
func (r *remoteReusableWorkflow) CloneURL() string {
return fmt.Sprintf("%s/%s/%s", withHTTPS(r.URL), r.Owner, r.Repo)
}
var absoluteReusableWorkflowURLRegex = regexp.MustCompile(`^(https?://.*)/([^/]+/[^/]+/\.[^/]+/workflows/[^@]+@.*)$`)
// For Gitea
// newRemoteReusableWorkflow parses a remote `uses`, an absolute URL up to `{owner}/{repo}/.{git_platform}/workflows/` replaces baseURL
func newRemoteReusableWorkflow(baseURL, uses string) (*remoteReusableWorkflow, error) {
func (c *caller) loadReusableWorkflow(ctx context.Context, instance, uses string) (*model.Plan, error) {
rc := c.runContext
if matches := absoluteReusableWorkflowURLRegex.FindStringSubmatch(uses); matches != nil {
baseURL, uses = matches[1], matches[2]
instance, uses = matches[1], matches[2]
}
parsed, err := model.ParseReusableWorkflowUses(uses)
workflow, err := model.ParseReusableWorkflowUses(uses)
if err != nil {
return nil, err
}
if parsed.IsLocal() {
return nil, fmt.Errorf("expected a remote reusable workflow, got %q", uses)
depth := 1
for parent := rc.caller; parent != nil; parent = parent.runContext.caller {
depth++
}
return &remoteReusableWorkflow{ReusableWorkflowUses: parsed, URL: baseURL}, nil
if depth >= model.MaxWorkflowCallDepth {
return nil, fmt.Errorf("reusable workflow %q exceeds the limit of %d workflows including the root", workflow.Path, model.MaxWorkflowCallDepth)
}
if rc.caller != nil {
c.checkout = rc.caller.checkout
}
cacheDir := "workflows"
if preset := rc.Config.PresetGitHubContext; workflow.IsLocal() && c.checkout.Dir == "" && preset != nil {
cacheDir = "local-workflows" // a same-repository checkout must never answer another repository's call unauthenticated
workflow, err = model.ParseReusableWorkflowUses(fmt.Sprintf("%s/%s@%s", preset.Repository, workflow.Path, preset.Sha))
if err != nil {
return nil, err
}
}
if !workflow.IsLocal() {
cloneURL, err := rc.ExprEval.Interpolate(ctx, withHTTPS(instance)+"/"+workflow.Owner+"/"+workflow.Repo)
if err != nil {
return nil, fmt.Errorf("unable to interpolate the workflow clone URL: %w", err)
}
c.checkout = rc.Config.withInstanceAuth(git.NewGitCloneExecutorInput{
URL: cloneURL,
Ref: workflow.Ref,
Dir: filepath.Join(rc.ActionCacheDir(), cacheDir, model.UsesHash(cloneURL+"@"+workflow.Ref), "git"),
}, rc.Config.GetToken())
}
if c.checkout.Dir != "" {
unlock, err := git.AcquireCloneLock(ctx, filepath.Dir(c.checkout.Dir))
if err != nil {
return nil, err
}
defer unlock()
if err := git.NewGitCloneExecutor(c.checkout)(ctx); err != nil {
return nil, err
}
if !workflow.IsLocal() {
c.checkout.Ref, err = git.FindGitRevision(ctx, c.checkout.Dir)
if err != nil {
return nil, err
}
c.checkout.OfflineMode = true
}
}
file, err := os.Open(filepath.Join(cmp.Or(c.checkout.Dir, rc.Config.Workdir), workflow.Path))
if err != nil {
return nil, err
}
defer file.Close()
planner, err := model.NewSingleWorkflowPlanner(filepath.Base(workflow.Path), file)
if err != nil {
return nil, err
}
return planner.PlanEvent("workflow_call")
}
// For Gitea
func setReusedWorkflowCallerResult(rc *RunContext, runner *runnerImpl) common.Executor {
return func(ctx context.Context) error {
hasFailure := false
for _, result := range runner.caller.reusedWorkflowJobResults {
if result == "pending" {
return nil
}
if result == "failure" {
hasFailure = true
}
func (rc *RunContext) runReusableWorkflow(ctx context.Context) error {
call := &caller{runContext: rc}
plan, err := call.loadReusableWorkflow(ctx, rc.Config.GitHubInstance, rc.Run.Job().Uses)
if err == nil && len(plan.Stages) > 0 {
if err = call.resolveInputs(ctx, plan.Stages[0].Runs[0].Workflow); err == nil {
err = (&runnerImpl{config: rc.Config, eventJSON: rc.EventJSON, caller: call}).NewPlanExecutor(plan)(ctx)
}
if err := setJobOutputs(ctx, rc); err != nil { // a bad output fails this job, as for ordinary jobs
common.Logger(ctx).Errorf("##[error]%s", EscapeCommandData(err.Error()))
hasFailure = true
}
reusedWorkflowJobResult := "success"
reusedWorkflowJobResultMessage := "succeeded"
if hasFailure {
reusedWorkflowJobResult = "failure"
reusedWorkflowJobResultMessage = "failed"
}
// Serialize this shared Job.Result write against the other matrix combos
// and setJobResult (same lockJob key).
unlock := lockJob(rc.Run.Job())
rc.result(reusedWorkflowJobResult)
unlock()
if rc.caller != nil {
rc.caller.setReusedWorkflowJobResult(rc.Run.JobID, reusedWorkflowJobResult)
} else {
common.Logger(ctx).With("jobResult", reusedWorkflowJobResult).Infof("Job %s", reusedWorkflowJobResultMessage)
}
return nil
}
call.finishWorkflowCall(ctx, err)
return cmp.Or(ctx.Err(), err)
}
func (c *caller) finishWorkflowCall(ctx context.Context, planErr error) {
rc := c.runContext
config := c.workflowCallConfig
var jobs map[string]*model.WorkflowCallResult
if config != nil && len(config.Outputs) > 0 && (planErr == nil || len(c.reportedRuns) > 0) {
jobs = make(map[string]*model.WorkflowCallResult, len(c.reportedRuns))
}
failed := planErr != nil
for _, run := range c.reportedRuns {
if run == nil {
failed = true
continue
}
job := run.Job()
switch job.NeedsResult() {
case "failure":
failed = true
case "cancelled":
rc.markCancelled()
}
if jobs != nil {
jobs[run.JobID] = &model.WorkflowCallResult{Outputs: job.Outputs}
}
}
if jobs != nil {
interpreter := exprparser.NewInterpeter(&exprparser.EvaluationEnvironment{
Github: rc.getGithubContext(ctx),
Vars: rc.Config.Vars,
Jobs: &jobs,
Inputs: c.inputs,
}, exprparser.Config{})
outputs, err := expreval.New(interpreter.Evaluate).EvaluateWorkflowCallOutputs(config) // unlogged, the caller's log lacks the called jobs' masks
if err != nil {
common.Logger(ctx).Errorf("##[error]unable to interpolate workflow %s", EscapeCommandData(err.Error()))
failed = true
} else if len(rc.Matrix) == 0 || (!failed && !rc.jobCancelled) {
mergeJobOutputs(rc.Run.Job(), outputs)
}
}
rc.markJobInterrupted(ctx)
rc.setJobResult(ctx, !failed)
}
// For Gitea
// withInstanceAuth passes instance credentials only to clones from this Gitea instance, and runner.insecure only to its registered address.
func (c Config) withInstanceAuth(input git.NewGitCloneExecutorInput, token string) git.NewGitCloneExecutorInput {
input.Depth, input.OfflineMode = c.ActionCloneDepth, c.ActionOfflineMode
u, err := url.Parse(input.URL)
if err != nil || !onInstanceHost(u.Host, c.GitHubInstance, c.trustedActionInstance()) {
return input

View File

@@ -8,118 +8,95 @@ import (
"crypto/tls"
"crypto/x509"
"encoding/pem"
"fmt"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"testing"
"time"
"testing/synctest"
"gitea.com/gitea/runner/act/common"
"gitea.com/gitea/runner/act/common/git"
"gitea.com/gitea/runner/act/common/logging"
"gitea.com/gitea/runner/act/common/logging/logtest"
"gitea.dev/actionslib/pkg/model"
"github.com/stretchr/testify/require"
)
// Regression test for go-gitea/gitea#37483: a remote reusable workflow at a moving
// ref (branch/tag) must reflect the new tip on every invocation, not stay pinned
// to the cache populated on the first run.
func TestReusableWorkflowCachedBranchRefRefreshes(t *testing.T) {
t.Parallel()
if _, err := exec.LookPath("git"); err != nil {
t.Skip("git not available in PATH")
}
func TestReusableWorkflowCacheRefreshesBranchRefAndIsolatesSameRepoCalls(t *testing.T) {
requireHostTools(t, "git")
remoteDir := t.TempDir()
const instance = "https://workflows.example"
const cloneURL = instance + "/org/repo"
t.Setenv("GIT_CONFIG_GLOBAL", filepath.Join(t.TempDir(), "gitconfig"))
gitMust(t, "", "config", "--global", "url."+remoteDir+".insteadOf", cloneURL)
gitMust(t, "", "config", "--global", "core.longpaths", "true")
gitMust(t, "", "init", "--template=", "--initial-branch=master", remoteDir)
const workflowPath = ".gitea/workflows/reusable.yml"
tmpl := func(tag string) string {
return "name: reusable\non:\n workflow_call:\njobs:\n build:\n runs-on: ubuntu-latest\n steps:\n - run: echo " + tag + "\n"
}
require.NoError(t, os.MkdirAll(filepath.Join(remoteDir, ".gitea/workflows"), 0o755))
require.NoError(t, os.WriteFile(filepath.Join(remoteDir, workflowPath), []byte(tmpl("v1")), 0o644))
gitMust(t, remoteDir, "add", workflowPath)
gitMust(t, remoteDir, "commit", "-m", "v1")
rc := &RunContext{
Config: &Config{Env: testCheckoutEnv()},
Run: &model.Run{
JobID: "j1",
Workflow: &model.Workflow{
Name: "wf",
Jobs: map[string]*model.Job{"j1": {}},
},
},
rc := workflowCaller(t, &Config{ActionCacheDir: t.TempDir(), PresetGitHubContext: &model.GithubContext{Repository: "root/project"}}, "./"+workflowPath)
commit := func(version string) *caller {
t.Helper()
require.NoError(t, os.WriteFile(filepath.Join(remoteDir, workflowPath), []byte(`on:
workflow_call:
outputs: {version: {value: "`+version+`@${{ github.repository }}"}}
jobs:
skip: {if: false, uses: ./unused.yml}
`), 0o644))
gitMust(t, remoteDir, "add", workflowPath)
gitMust(t, remoteDir, "commit", "-m", version)
call := &caller{runContext: rc}
_, err := call.loadReusableWorkflow(t.Context(), instance, "org/repo/"+workflowPath+"@master")
require.NoError(t, err)
return call
}
cacheDir := t.TempDir()
require.NoError(t, cloneRemoteReusableWorkflow(rc, remoteDir, "master", cacheDir)(t.Context()))
got, err := os.ReadFile(filepath.Join(cacheDir, workflowPath))
first := commit("v1")
commit("v2")
cacheDir := filepath.Join(rc.ActionCacheDir(), "workflows", model.UsesHash(cloneURL+"@master"))
got, err := os.ReadFile(filepath.Join(cacheDir, "git", workflowPath))
require.NoError(t, err)
require.Equal(t, tmpl("v1"), string(got))
// Branch tip moves; cache key (cacheDir) does not.
require.NoError(t, os.WriteFile(filepath.Join(remoteDir, workflowPath), []byte(tmpl("v2")), 0o644))
gitMust(t, remoteDir, "commit", "-am", "v2")
require.NoError(t, cloneRemoteReusableWorkflow(rc, remoteDir, "master", cacheDir)(t.Context()))
got, err = os.ReadFile(filepath.Join(cacheDir, workflowPath))
require.Contains(t, string(got), "v2@")
sameRepo := workflowCaller(t, &Config{ActionCacheDir: rc.ActionCacheDir(), PresetGitHubContext: &model.GithubContext{Repository: "org/repo", Sha: "master"}}, "./"+workflowPath)
sameRepoCall := &caller{runContext: sameRepo}
_, err = sameRepoCall.loadReusableWorkflow(t.Context(), instance, "./"+workflowPath)
require.NoError(t, err)
require.Equal(t, tmpl("v2"), string(got), "cached workflow file must reflect the updated branch tip")
}
require.NotEqual(t, cacheDir, filepath.Dir(sameRepoCall.checkout.Dir))
func TestNewReusableWorkflowExecutorHoldsCloneLock(t *testing.T) {
workflowDir := t.TempDir()
require.NoError(t, os.WriteFile(filepath.Join(workflowDir, "reusable.yml"), []byte("["), 0o644))
require.NoError(t, os.RemoveAll(remoteDir))
require.NoError(t, first.resolveInputs(t.Context(), rc.Run.Workflow))
call := (&runnerImpl{config: rc.Config, caller: first}).NewPlanExecutor(&model.Plan{Stages: []*model.Stage{{Runs: []*model.Run{rc.Run}}}})
require.NoError(t, call(t.Context()))
require.Equal(t, "v1@root/project", rc.Run.Job().Outputs["version"])
unlock, err := git.AcquireCloneLock(t.Context(), workflowDir)
require.NoError(t, err)
unlockOnce := sync.OnceFunc(unlock)
defer unlockOnce()
rc := &RunContext{
Config: &Config{},
Run: &model.Run{Workflow: &model.Workflow{Jobs: map[string]*model.Job{}}},
}
exec := newReusableWorkflowExecutor(rc, workflowDir, "reusable.yml", true)
done := make(chan error, 1)
go func() { done <- exec(context.Background()) }()
select {
case err := <-done:
t.Fatalf("executor returned while clone lock was held: %v", err)
case <-time.After(50 * time.Millisecond):
}
unlockOnce()
select {
case err := <-done:
require.Error(t, err)
case <-time.After(time.Second):
t.Fatal("executor did not return after lock was released")
}
synctest.Test(t, func(t *testing.T) {
unlock, err := git.AcquireCloneLock(t.Context(), cacheDir)
require.NoError(t, err)
defer unlock()
ctx, cancel := context.WithCancel(t.Context())
done := make(chan error, 1)
go func() { done <- call(ctx) }()
synctest.Wait()
cancel()
require.ErrorIs(t, <-done, context.Canceled)
require.Equal(t, "cancelled", rc.Run.Job().Result)
})
}
func TestNewLocalReusableWorkflowExecutorFindsSameRepositoryPaths(t *testing.T) {
workdir := filepath.Join(t.TempDir(), "workspace")
require.NoError(t, os.MkdirAll(filepath.Join(workdir, ".gitea", "workflows"), 0o755))
require.NoError(t, os.Mkdir(workdir+".lock", 0o755))
require.NoError(t, os.WriteFile(filepath.Join(workdir, ".gitea", "workflows", "reusable.yml"), []byte("["), 0o644))
workdir := t.TempDir()
require.NoError(t, os.MkdirAll(filepath.Join(workdir, ".gitea/workflows"), 0o755))
require.NoError(t, os.WriteFile(filepath.Join(workdir, ".gitea/workflows/reusable.yml"), []byte("on: workflow_call\njobs:\n skip: {if: false, uses: ./unused.yml}\n"), 0o644))
for _, uses := range []string{"./.gitea/workflows/reusable.yml", "$/.gitea/workflows/reusable.yml"} {
rc := &RunContext{
Config: &Config{Workdir: workdir, NoSkipCheckout: true},
Run: &model.Run{JobID: "job", Workflow: &model.Workflow{Jobs: map[string]*model.Job{"job": {Uses: uses}}}},
}
err := newLocalReusableWorkflowExecutor(rc)(t.Context())
require.ErrorContains(t, err, "workflow is not valid")
rc := workflowCaller(t, &Config{Workdir: workdir, Env: testCheckoutEnv()}, uses)
require.NoError(t, rc.runReusableWorkflow(t.Context()))
require.Equal(t, "success", rc.Run.Job().Result)
}
}
@@ -141,19 +118,17 @@ func TestCloneRemoteReusableWorkflowSendsInstanceTokenAndClientCertTrustingCA(t
certFile, keyFile := filepath.Join(dir, "client.crt"), filepath.Join(dir, "client.key")
require.NoError(t, os.WriteFile(certFile, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: pair.Certificate[0]}), 0o600))
require.NoError(t, os.WriteFile(keyFile, pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: keyDER}), 0o600))
rc := &RunContext{
Config: &Config{
Env: testCheckoutEnv(),
GitHubInstance: server.URL,
Secrets: map[string]string{"GITEA_TOKEN": "token"},
ClientCertFile: certFile,
ClientKeyFile: keyFile,
CAFile: certFile,
},
Run: &model.Run{JobID: "j1", Workflow: &model.Workflow{Jobs: map[string]*model.Job{"j1": {}}}},
}
rc := workflowCaller(t, &Config{
ActionCacheDir: t.TempDir(),
Env: testCheckoutEnv(),
GitHubInstance: server.URL,
Secrets: map[string]string{"GITEA_TOKEN": "token"},
ClientCertFile: certFile,
ClientKeyFile: keyFile,
CAFile: certFile,
}, server.URL+"/owner/repo/.gitea/workflows/test.yml@main")
err = cloneRemoteReusableWorkflow(rc, server.URL+"/owner/repo", "main", t.TempDir())(t.Context())
err = rc.runReusableWorkflow(t.Context())
require.Error(t, err)
require.True(t, gotCert, "clone failed before receiving a client certificate: %v", err)
require.Equal(t, "token", gotToken)
@@ -176,6 +151,8 @@ func TestInstanceAuthAndTransportOnlyApplyToTheInstance(t *testing.T) {
t.Run(tt.name, func(t *testing.T) {
conf := Config{
GitHubInstance: tt.instanceURL,
ActionCloneDepth: 3,
ActionOfflineMode: true,
DefaultActionInstance: tt.trustedActionInstance,
DefaultActionInstanceIsSelfHosted: tt.trustedActionInstance != "",
InsecureSkipTLS: true,
@@ -184,7 +161,7 @@ func TestInstanceAuthAndTransportOnlyApplyToTheInstance(t *testing.T) {
CAFile: "/ca",
InstanceTransport: &http.Transport{},
}
want := git.NewGitCloneExecutorInput{URL: tt.cloneURL, InsecureSkipTLS: tt.insecure}
want := git.NewGitCloneExecutorInput{URL: tt.cloneURL, Depth: 3, OfflineMode: true, InsecureSkipTLS: tt.insecure}
if tt.insecure {
want.CAFile, want.Transport = conf.CAFile, conf.InstanceTransport
}
@@ -215,16 +192,69 @@ func gitMust(t *testing.T, dir string, args ...string) {
require.NoError(t, err, "git %v: %s", args, string(out))
}
func TestSetReusedWorkflowCallerResultFailsOnBadOutputs(t *testing.T) {
callerWorkflow, err := model.ReadWorkflow(strings.NewReader("jobs:\n call: {uses: ./reuse.yml}\n"))
func workflowCaller(t *testing.T, config *Config, uses string) *RunContext {
t.Helper()
rc, err := (&runnerImpl{config: config}).newRunContext(t.Context(), &model.Run{
JobID: "call", Workflow: &model.Workflow{Jobs: map[string]*model.Job{"call": {Uses: uses}}},
}, nil)
require.NoError(t, err)
called, err := model.ReadWorkflow(strings.NewReader("on:\n workflow_call:\n outputs:\n bad: {value: \"${{ fromJSON('not-json') }}\"}\njobs:\n inner: {uses: ./leaf.yml}\n"))
require.NoError(t, err)
config := &Config{PresetGitHubContext: &model.GithubContext{}}
parent, err := (&runnerImpl{config: config}).newRunContext(t.Context(), &model.Run{Workflow: callerWorkflow, JobID: "call"}, nil)
require.NoError(t, err)
rc, err := (&runnerImpl{config: config, caller: &caller{runContext: parent, reusedWorkflowJobResults: map[string]string{}}}).newRunContext(t.Context(), &model.Run{Workflow: called, JobID: "inner"}, nil)
require.NoError(t, err)
require.NoError(t, setReusedWorkflowCallerResult(rc, &runnerImpl{caller: &caller{reusedWorkflowJobResults: map[string]string{"leaf": "success"}}})(t.Context()))
require.Equal(t, "failure", rc.Run.Job().Result)
return rc
}
func TestReusableWorkflowBadOutputFailsCallerAndKeepsLastNonemptyMatrixOutput(t *testing.T) {
workdir := t.TempDir()
require.NoError(t, os.WriteFile(filepath.Join(workdir, "callee.yml"), []byte(`on:
workflow_call:
inputs: {value: {type: string}}
outputs: {result: {value: "${{ fromJSON(inputs.value) }}"}}
jobs:
skipped: {if: false, uses: ./unused.yml}
`), 0o644))
root, err := model.ReadWorkflow(strings.NewReader(`on: push
jobs:
call:
strategy: {max-parallel: 1, matrix: {value: [bad, '"one"', '"two"', '""']}}
uses: ./callee.yml
with: {value: "${{ matrix.value }}"}
`))
require.NoError(t, err)
plan, err := model.CombineWorkflowPlanner(root).PlanEvent("push")
require.NoError(t, err)
runner, err := New(&Config{Workdir: workdir, Env: testCheckoutEnv()})
require.NoError(t, err)
require.ErrorContains(t, runner.NewPlanExecutor(plan)(t.Context()), "job 'call' failed")
require.Equal(t, "two", root.Jobs["call"].Outputs["result"])
}
func TestReusableWorkflowKeepsCompletedOutputsOnChildErrorWithoutLoggingThem(t *testing.T) {
workdir := t.TempDir()
require.NoError(t, os.WriteFile(filepath.Join(workdir, "callee.yml"), []byte(`on:
workflow_call:
outputs:
result: {value: "${{ jobs.first.outputs.value }}"}
unrun: {value: "${{ jobs.third.outputs.value }}"}
jobs:
placeholder: {result: cancelled}
first: {runs-on: ubuntu-latest, outputs: {value: from-first}, steps: [{run: echo first}]}
second: {needs: first, runs-on: ubuntu-latest, container: {image: node, ports: [invalid]}, steps: [{run: echo second}]}
third: {needs: second, runs-on: ubuntu-latest, outputs: {value: from-third}, steps: [{run: echo third}]}
`), 0o644))
rc := workflowCaller(t, &Config{Workdir: workdir, Env: testCheckoutEnv(), PlatformPicker: mapPlatformPicker(platforms)}, "./callee.yml")
hook := logtest.NewWithLevel(logging.LevelDebug)
ctx := common.WithLogger(common.WithDryrun(t.Context(), true), logging.New(hook))
require.ErrorContains(t, rc.runReusableWorkflow(ctx), "failed to parse container ports")
require.Equal(t, "failure", rc.Run.Job().Result)
require.Equal(t, map[string]string{"result": "from-first"}, rc.Run.Job().Outputs)
for _, record := range hook.AllRecords() {
require.NotContains(t, record.Message, "from-first")
}
}
func TestReusableWorkflowNestingLimit(t *testing.T) {
workdir := t.TempDir()
for level := 2; level <= model.MaxWorkflowCallDepth; level++ {
require.NoError(t, os.WriteFile(filepath.Join(workdir, fmt.Sprintf("%d.yml", level)), []byte(fmt.Sprintf("on: workflow_call\njobs:\n next: {uses: ./%d.yml}\n", level+1)), 0o644))
}
rc := workflowCaller(t, &Config{Workdir: workdir, Env: testCheckoutEnv()}, "./2.yml")
require.ErrorContains(t, rc.runReusableWorkflow(t.Context()), fmt.Sprintf(`"%d.yml" exceeds the limit of %d`, model.MaxWorkflowCallDepth+1, model.MaxWorkflowCallDepth))
}

View File

@@ -67,6 +67,7 @@ type RunContext struct {
JobContainer container.ExecutionsEnvironment
serviceContainers []*serviceContainer
kubernetes bool
runsOn []string
containerSpec model.ContainerSpec // container:, resolved once with platformImage
containerEnv yaml.Node // container.env of the kept containerSpec, decoded once the job env resolves
defaultEnv map[string]string // ImageOS and the runner CA's NODE_EXTRA_CA_CERTS, beneath any env the job sets
@@ -78,8 +79,8 @@ type RunContext struct {
cleanUpJobContainer common.Executor
taskWorkspace string
deferVolumeCleanup func(common.Executor)
caller *caller // job calling this RunContext (reusable workflows)
workflowCallInputs map[string]any // the caller's with:, resolved once by resolveWorkflowCall
caller *caller // job calling this RunContext (reusable workflows)
callerRunIndex int
workflowCallSecrets map[string]string // the caller's secrets:, resolved once by resolveWorkflowCall
jobRunDefaults model.RunDefaults // defaults.run, resolved once at job setup as GitHub does
platformImage string // container.image or the runs-on pick, resolved once by isEnabled
@@ -90,6 +91,7 @@ type RunContext struct {
jobEnv map[string]string // workflow and job env as evaluated for the container and service specs
dockerActionImages map[*model.Step]string // Dockerfile action images built for this job, removed when it ends
actionDownloads map[string]*actionDownload // remote action repositories by clone URL and ref, fetched once per job
nodePath string
// summaryFileInitialized tracks which per-step summary files (workflow/step-summary-N.md)
// have already been created on the JobContainer. The runner sets up file-command files
@@ -99,6 +101,7 @@ type RunContext struct {
// so writes from later phases and from composite sub-steps append to the same file.
// Only populated on the top-level RunContext; child RCs walk Parent via topLevelRunContext.
summaryFileInitialized map[int]bool
summaryUploads *stepSummaryUploads
// jobCancelled records that this job's run was cancelled (context.Canceled). It makes
// getJobContext report the "cancelled" status so cancelled()/always() evaluate the way
// GitHub Actions does, letting cleanup and always() steps run while normal steps skip.
@@ -158,20 +161,6 @@ func (rc *RunContext) markFailed() {
rc.jobFailed = true
}
// markInterrupted records the job's interruption status from a context error so later step `if` evaluations and the job result observe it,
// keeping the timeout path symmetric with the cancel path:
// - context.Canceled (server cancel) marks the job cancelled, matching GitHub's "only always()/cancelled() run on cancel".
// - context.DeadlineExceeded (job timeout-minutes) evaluates later steps as cancelled like GitHub, but reports the job failed.
func (rc *RunContext) markInterrupted(err error) {
switch {
case errors.Is(err, context.Canceled):
rc.markCancelled()
case errors.Is(err, context.DeadlineExceeded):
rc.jobTimedOut = true
rc.markFailed()
}
}
// AddMask also hands the mask to the job logger's extra handler, which receives records unmasked.
func (rc *RunContext) AddMask(ctx context.Context, mask string) {
rc.Masks = append(rc.Masks, mask)
@@ -183,8 +172,6 @@ func (rc *RunContext) AddMask(ctx context.Context, mask string) {
func (rc *RunContext) String() string {
name := fmt.Sprintf("%s/%s", rc.Run.Workflow.Name, rc.Name)
if rc.caller != nil {
// prefix the reusable workflow with the caller job
// this is required to create unique container names
name = fmt.Sprintf("%s/%s", rc.caller.runContext.Name, name)
}
return name
@@ -223,12 +210,8 @@ func (rc *RunContext) setActionEnv(env map[string]string) {
}
func (rc *RunContext) jobContainerName() string {
// The job id, never evaluated, keeps two jobs apart when masking collapses their names.
nameParts := []string{rc.Config.ContainerNamePrefix, "WORKFLOW-" + rc.Run.Workflow.Name, "JOB-" + rc.Run.JobID, rc.Name}
if rc.caller != nil {
nameParts = append(nameParts, "CALLED-BY-"+rc.caller.runContext.JobName)
}
return createContainerName(nameParts...) // For Gitea
job := rc.topLevelRunContext()
return createContainerName(job.Config.ContainerNamePrefix, "WORKFLOW-"+job.Run.Workflow.Name, "JOB-"+job.Run.JobID, job.Name, job.runnerTrackingID())
}
// networkNameForGitea return the name of the network
@@ -272,7 +255,7 @@ func (rc *RunContext) validVolumes() []string {
name := rc.jobContainerName()
volumes := slices.Clone(rc.Config.ValidVolumes)
if hostEnv, ok := rc.JobContainer.(*container.HostEnvironment); ok {
volumes = append(volumes, hostEnv.Path, hostEnv.GetActPath())
volumes = append(volumes, hostEnv.HostPath(hostEnv.Path), hostEnv.GetActPath())
}
if rc.Config.SharedToolCache {
volumes = append(volumes, rc.toolCacheVolume())
@@ -284,6 +267,9 @@ func (rc *RunContext) validVolumes() []string {
volumes = append(volumes, rc.dockerProxy.Socket)
}
volumes = append(volumes, rc.Config.containerVolumeSources()...)
if !rc.Config.NoNodeDownload {
volumes = append(volumes, rc.Config.nodeVolume()+":ro")
}
// TODO: add a new configuration to control whether the docker daemon can be mounted
return append(volumes, name, name+"-env",
getDockerDaemonSocketMountPath(rc.containerDaemonSocket()))
@@ -406,7 +392,7 @@ func (rc *RunContext) GetBindsAndMounts(ctx context.Context) ([]string, map[stri
}
}
if hostEnv, ok := rc.JobContainer.(*container.HostEnvironment); ok {
binds = append(binds, hostEnv.Path+":"+hostEnv.Path, hostEnv.GetActPath()+":"+hostEnv.GetActPath())
binds = append(binds, hostEnv.HostPath(hostEnv.Path)+":"+hostEnv.Path, hostEnv.GetActPath()+":"+hostEnv.GetActPath())
}
mounts[name+"-env"] = ext.GetActPath() // runner-internal, never overridable
@@ -469,7 +455,7 @@ func (rc *RunContext) startHostEnvironment() common.Executor {
if err := os.MkdirAll(toolCache, 0o777); err != nil {
return err
}
rc.JobContainer = &container.HostEnvironment{
hostEnv := &container.HostEnvironment{
Path: path,
TmpDir: runnerTmp,
ToolCache: toolCache,
@@ -480,7 +466,13 @@ func (rc *RunContext) startHostEnvironment() common.Executor {
StdOut: logWriter,
AllocatePTY: rc.Config.AllocatePTY,
}
rc.cleanUpJobContainer = rc.JobContainer.Remove()
rc.JobContainer = hostEnv
rc.cleanUpJobContainer = hostEnv.Remove()
if preset := rc.Config.PresetGitHubContext; rc.Config.StableHostWorkdir && preset != nil {
if err := hostEnv.UseWorkspace(filepath.Join(cacheDir, "workspaces"), preset.Repository); err != nil {
common.Logger(ctx).Warnf("host.stable_workdir needs Linux and CAP_SYS_ADMIN, using a random workspace path: %v", err)
}
}
rc.setRunnerContextEnv(ctx)
rc.importHostEnv(os.Environ())
@@ -553,7 +545,7 @@ func (rc *RunContext) startKubernetesPod() common.Executor {
}
var options container.KubernetesOptions
if rc.Config.KubernetesPicker != nil {
options = rc.Config.KubernetesPicker(rc.runsOnPlatformNames(ctx))
options = rc.Config.KubernetesPicker(rc.runsOn)
}
options.MaxLifetime, options.ForcePull = rc.Config.ContainerMaxLifetime, rc.Config.ForcePull
pod, err := container.NewKubernetesPod(options)
@@ -671,7 +663,6 @@ func (rc *RunContext) startJobContainer() common.Executor {
Name: name,
Env: envList,
NetworkMode: networkName,
NetworkAliases: []string{rc.Name},
ExposedPorts: exposedPorts,
PortBindings: portBindings,
Stdout: logWriter,
@@ -699,6 +690,9 @@ func (rc *RunContext) startJobContainer() common.Executor {
rc.startDockerProxy(ctx)
var taskWorkspace string
containerInput.Binds, containerInput.Mounts, taskWorkspace = rc.GetBindsAndMounts(ctx)
if !rc.Config.NoNodeDownload {
containerInput.Binds = append(containerInput.Binds, rc.Config.nodeVolume()+":"+ext.GetActPath()+"/node:ro,nocopy")
}
containerInput.ValidVolumes = rc.validVolumes()
rc.jobNetworkName = networkName
@@ -1321,14 +1315,17 @@ func (rc *RunContext) interpolateOutputs() common.Executor {
if err := model.DecodeEvaluated("job outputs", job.RawOutputs, rc.NewExpressionEvaluator(ctx).shared(ctx).EvaluateYamlNode, &outputs); err != nil {
return err
}
// Matrix combinations share the job, so as on GitHub a failure publishes nothing and the last non-empty value wins.
maps0.DeleteFunc(outputs, func(_, value string) bool { return value == "" })
defer lockJob(job)()
job.Outputs = mergeMaps(job.Outputs, outputs)
mergeJobOutputs(job, outputs)
return nil
}
}
func mergeJobOutputs(job *model.Job, outputs map[string]string) {
maps0.DeleteFunc(outputs, func(_name, value string) bool { return value == "" }) // The last non-empty value wins across matrix combinations.
defer lockJob(job)()
job.Outputs = mergeMaps(job.Outputs, outputs)
}
func (rc *RunContext) startContainer() common.Executor {
return func(ctx context.Context) error {
var err error
@@ -1374,14 +1371,6 @@ func (rc *RunContext) closeContainer() common.Executor {
}
}
func (rc *RunContext) matrix() map[string]any {
return rc.Matrix
}
func (rc *RunContext) result(result string) {
rc.Run.Job().Result = result
}
func (rc *RunContext) steps() []*model.Step {
// Return per-job copies of the steps. Matrix combinations run in parallel and share the
// workflow model, but step execution mutates per-job fields and evaluates the If/Env nodes
@@ -1416,64 +1405,31 @@ func (rc *RunContext) Executor() (common.Executor, error) {
switch jobType {
case model.JobTypeDefault:
executor = newJobExecutor(rc, &stepFactoryImpl{}, rc)
case model.JobTypeReusableWorkflowLocal:
executor = newLocalReusableWorkflowExecutor(rc)
case model.JobTypeReusableWorkflowRemote:
executor = newRemoteReusableWorkflowExecutor(rc)
case model.JobTypeReusableWorkflowLocal, model.JobTypeReusableWorkflowRemote:
executor = rc.runReusableWorkflow
case model.JobTypeInvalid:
return nil, err
}
return func(ctx context.Context) error {
res, err := rc.isEnabled(ctx)
if err != nil {
// Record the failure so a job that cannot start gets a stop time. rc.caller is only set for reusable workflows.
rc.result("failure")
if rc.caller != nil { // For Gitea
rc.caller.setReusedWorkflowJobResult(rc.Run.JobID, "failure")
}
if enabled, err := rc.isEnabled(ctx); !enabled {
return err
}
if res {
return executor(ctx)
jobCtx, cancel, err := applyJobTimeout(ctx, rc, rc.Run.Job())
if err != nil {
common.Logger(ctx).Errorf("##[error]%s", EscapeCommandData(err.Error()))
rc.setJobResult(ctx, false)
return nil
}
return nil
defer cancel()
err = executor(jobCtx)
if rc.jobCancelled {
return ctx.Err() // downstream jobs still evaluate their conditions after a job timeout
}
return err
}, nil
}
func (rc *RunContext) runsOnImage(ctx context.Context) (string, error) {
runsOn := rc.Run.Job().RunsOn()
for i, v := range runsOn {
var err error
if runsOn[i], err = rc.ExprEval.Interpolate(ctx, v); err != nil {
return "", fmt.Errorf("unable to interpolate runs-on: %w", err)
}
}
if rc.Config.PlatformPicker != nil {
return rc.Config.PlatformPicker(runsOn), nil
}
return "", nil
}
func (rc *RunContext) runsOnPlatformNames(ctx context.Context) []string {
job := rc.Run.Job()
if job.RunsOn() == nil {
return []string{}
}
// Evaluate a copy: RawRunsOn is shared across parallel matrix jobs, so interpolating it in
// place would race and leak one matrix combination's runs-on into the others.
rawRunsOn := model.CloneYamlNode(job.RawRunsOn)
if err := rc.ExprEval.EvaluateYamlNode(ctx, &rawRunsOn); err != nil {
common.Logger(ctx).Errorf("Error while evaluating runs-on: %v", err)
return []string{}
}
return model.RunsOnFromNode(rawRunsOn)
}
// resolvePlatformImage evaluates the job's container once for every consumer, skipping one whose image is empty as GitHub does.
func (rc *RunContext) resolvePlatformImage(ctx context.Context) error {
rc.jobEnv, _ = evaluateJobEnv(ctx, rc) // a broken env fails the job at setup instead
@@ -1486,9 +1442,14 @@ func (rc *RunContext) resolvePlatformImage(ctx context.Context) error {
if spec.Image != "" || imagelessContainer(withoutEnv) {
rc.containerSpec, rc.containerEnv = spec, env
}
image, err := rc.runsOnImage(ctx)
if err != nil {
return err
runsOn := model.CloneYamlNode(rc.Run.Job().RawRunsOn)
if err := rc.ExprEval.EvaluateYamlNode(ctx, &runsOn); err != nil {
return fmt.Errorf("unable to evaluate runs-on: %w", err)
}
rc.runsOn = model.RunsOnFromNode(runsOn)
var image string
if rc.Config.PlatformPicker != nil {
image = rc.Config.PlatformPicker(rc.runsOn)
}
image, rc.kubernetes = strings.CutPrefix(image, "kubernetes://")
rc.platformImage = cmp.Or(rc.containerSpec.Image, image)
@@ -1533,39 +1494,38 @@ func (rc *RunContext) isEnabled(ctx context.Context) (bool, error) {
job := rc.Run.Job()
l := common.Logger(ctx)
runJob, runJobErr := EvalBool(ctx, rc.ExprEval, job.If.Value, exprparser.DefaultStatusCheckSuccess)
jobType, jobTypeErr := job.Type()
if runJobErr != nil {
l.Errorf("Error when evaluating 'if' for job '%s'. %v", rc.Run.JobID, runJobErr)
}
if jobType == model.JobTypeInvalid {
return false, jobTypeErr
}
if !runJob {
if rc.caller != nil { // For Gitea
rc.caller.setReusedWorkflowJobResult(rc.Run.JobID, "skipped")
return false, nil
if runJob {
if job.Uses != "" {
return true, nil
}
l.With("jobResult", "skipped").Debugf("Skipping job '%s' due to '%s'", job.Name, job.If.Value)
return false, nil
}
if jobType != model.JobTypeDefault {
return true, nil
}
if err := rc.resolvePlatformImage(ctx); err != nil {
return false, err
}
if rc.platformImage == "" {
for _, platformName := range rc.runsOnPlatformNames(ctx) {
if err := rc.resolvePlatformImage(ctx); err != nil {
rc.setJobResult(ctx, false)
return false, err
}
if rc.platformImage != "" {
return true, nil
}
for _, platformName := range rc.runsOn {
l.Infof("Skipping unsupported platform -- Try running with `-P %+v=...`", platformName)
}
return false, nil
if len(job.Steps) == 0 { // Gitea's needs placeholders carry the result from the server
return false, nil
}
} else if rc.caller == nil {
l.With("jobResult", "skipped").Debugf("Skipping job '%s' due to '%s'", job.Name, job.If.Value)
}
return true, nil
defer lockJob(job)()
if rc.jobTotal == 1 || job.Result == "" {
job.Result = "skipped"
}
if rc.caller != nil {
rc.caller.reportedRuns[rc.callerRunIndex] = rc.Run
}
return false, nil
}
// proxyBuildArgs returns the job's proxy variables as docker build args. The docker CLI
@@ -1681,8 +1641,11 @@ func (rc *RunContext) getGithubContext(ctx context.Context) *model.GithubContext
ghc := &model.GithubContext{
Event: make(map[string]any),
Workflow: rc.Run.Workflow.Name,
WorkflowRef: rc.Config.Env["GITHUB_WORKFLOW_REF"],
WorkflowSha: rc.Config.Env["GITHUB_WORKFLOW_SHA"],
RunID: cmp.Or(rc.Config.Env["GITHUB_RUN_ID"], "1"),
RunNumber: cmp.Or(rc.Config.Env["GITHUB_RUN_NUMBER"], "1"),
RunAttempt: cmp.Or(rc.Config.Env["GITHUB_RUN_ATTEMPT"], "1"),
Actor: cmp.Or(rc.Config.Actor, "nektos/act"), // for configs that require a default rather than being run as a cmd
EventName: rc.Config.EventName,
Action: rc.CurrentStep,

View File

@@ -330,6 +330,7 @@ jobs:
redis, job := inputs[0], inputs[1]
require.Equal(t, "redis:latest", redis.Image)
require.Empty(t, job.NetworkAliases)
require.Equal(t, map[string]string{"data": "/data"}, redis.Mounts)
require.Equal(t, []string{"TITLE=${{ github.job }}"}, redis.Env)
require.Equal(t, "${{ github.job }}", redis.Password)
@@ -358,6 +359,7 @@ jobs:
env: {TEXT: "${{ env.TEXT }}"}
options: --volumes-from ${{ env.JOB_CONTAINER_NAME }}
`, &Config{Vars: map[string]string{"REG_USER": "user", "TEXT": "${{ 'literal' }}"}})
require.NotEqual(t, job.Name, inputs[1].Name)
redis, job = inputs[0], inputs[1]
require.Equal(t, "user", job.Username)
require.Equal(t, "8080", job.PortBindings["80/tcp"][0].HostPort)
@@ -969,7 +971,10 @@ func TestGetGitHubContext(t *testing.T) {
EventName: "push",
Workdir: cwd,
Env: map[string]string{
"GITHUB_REPOSITORY": "nektos/act",
"GITHUB_REPOSITORY": "nektos/act",
"GITHUB_RUN_ATTEMPT": "2",
"GITHUB_WORKFLOW_REF": "owner/repo/.github/workflows/build.yml@refs/heads/main",
"GITHUB_WORKFLOW_SHA": "local-workflow-sha",
},
},
Run: &model.Run{
@@ -1006,6 +1011,9 @@ func TestGetGitHubContext(t *testing.T) {
assert.Equal(t, "1", ghc.RunID)
assert.Equal(t, "1", ghc.RunNumber)
assert.Equal(t, "2", ghc.RunAttempt)
assert.Equal(t, rc.Config.Env["GITHUB_WORKFLOW_REF"], ghc.WorkflowRef)
assert.Equal(t, "local-workflow-sha", ghc.WorkflowSha)
assert.Equal(t, "0", ghc.RetentionDays)
assert.Equal(t, actor, ghc.Actor)
assert.Equal(t, repo, ghc.Repository)
@@ -1144,7 +1152,7 @@ func createJob(t *testing.T, input, result string) *model.Job {
return job
}
func TestRunContextRunsOnPlatformNames(t *testing.T) {
func TestResolvePlatformImagePassesEvaluatedRunsOnLabelsToPicker(t *testing.T) {
for _, testcase := range []struct {
job string
want []string
@@ -1153,14 +1161,18 @@ func TestRunContextRunsOnPlatformNames(t *testing.T) {
{"runs-on: ${{ 'ubuntu-latest' }}", []string{"ubuntu-latest"}},
{"runs-on: [self-hosted, my-runner]", []string{"self-hosted", "my-runner"}},
{`runs-on: [self-hosted, "${{ 'my-runner' }}"]`, []string{"self-hosted", "my-runner"}},
{`runs-on: ${{ fromJSON('["ubuntu-latest"]') }}`, []string{"ubuntu-latest"}},
{"name: something", []string{}},
{"runs-on: {mapping: value}", []string{}},
{"runs-on: ${{ invalid expression }}", []string{}},
{`runs-on: ${{ fromJSON('["self-hosted","my-runner"]') }}`, []string{"self-hosted", "my-runner"}},
{"name: something", nil},
{"runs-on: {mapping: value}", nil},
} {
t.Run(testcase.job, func(t *testing.T) {
rc := createIfTestRunContext(map[string]*model.Job{"job1": createJob(t, testcase.job, "")})
assert.Equal(t, testcase.want, rc.runsOnPlatformNames(t.Context()))
rc := makeTestRC(t, testcase.job)
rc.Config.PlatformPicker = func(labels []string) string {
assert.Equal(t, testcase.want, labels)
return "ubuntu-latest"
}
require.NoError(t, rc.resolvePlatformImage(t.Context()))
assert.Equal(t, "ubuntu-latest", rc.platformImage)
})
}
}

View File

@@ -16,6 +16,7 @@ import (
"time"
"gitea.com/gitea/runner/act/common"
"gitea.com/gitea/runner/act/common/git"
"gitea.com/gitea/runner/act/common/logging"
"gitea.com/gitea/runner/act/container"
"gitea.com/gitea/runner/act/ghcontext"
@@ -78,13 +79,17 @@ type Config struct {
// AppURL. It is never set for github.com or a GithubMirror, so the token stays on-instance.
DefaultActionInstanceIsSelfHosted bool
PlatformPicker func(labels []string) string
ReplaceUses func(uses string) string // rewrites each step's uses before it is resolved
KubernetesPicker func(labels []string) container.KubernetesOptions
InstanceTransport http.RoundTripper
JobLoggerLevel *logging.Level // the level of job logger
ValidVolumes []string // only volumes (and bind mounts) in this slice can be mounted on the job container or service containers
ContainerVolumes []string // mounted into every job, service and docker action container
NoNodeDownload bool // run JavaScript actions and hashFiles with the node on PATH, never one the runner downloads
NodeVersion string // the Node.js version to download instead of the pinned one, checked against its published SHA-256
SharedToolCache bool // keeps the tool cache across jobs instead of one per job
ToolCacheSlot string // keeps concurrent tasks' tool caches apart, empty for slot 0 and in exec
StableHostWorkdir bool // host jobs run at a stable path per repository, see HostEnvironment.UseWorkspace
InsecureSkipTLS bool // whether to skip verifying TLS certificate of the Gitea instance
ClientCertFile, ClientKeyFile string // PEM client certificate for the Gitea instance
CAFile string // PEM CA certificates the Gitea instance's certificate chains to
@@ -117,10 +122,11 @@ func (c Config) DefaultActionURL() string {
}
type caller struct {
runContext *RunContext
updateResultLock sync.Mutex // For Gitea
reusedWorkflowJobResults map[string]string // For Gitea
runContext *RunContext
checkout git.NewGitCloneExecutorInput
workflowCallConfig *model.WorkflowCall
inputs map[string]any
reportedRuns []*model.Run
}
type runnerImpl struct {
@@ -216,6 +222,10 @@ func (runner *runnerImpl) NewPlanExecutor(plan *model.Plan) common.Executor {
logging.Debugf("Job.With: %v", job.With)
logging.Debugf("Job.Result: %v", job.Result)
failStrategy := func(err error) error {
job.Result = "failure"
return fmt.Errorf("Error when evaluating 'strategy' for job '%s'. %w", run.JobID, err)
}
if job.Strategy != nil || job.RawStrategy.Kind == yaml.ScalarNode {
strategyRc, err := runner.newRunContext(ctx, run, nil)
if err != nil {
@@ -223,28 +233,29 @@ func (runner *runnerImpl) NewPlanExecutor(plan *model.Plan) common.Executor {
}
if job.RawStrategy.Kind == yaml.ScalarNode {
if err := model.DecodeEvaluated("job strategy", job.RawStrategy, strategyRc.ExprEval.shared(ctx).EvaluateYamlNode, &job.Strategy); err != nil {
return err
return failStrategy(err)
}
} else {
logging.Debugf("Job.Strategy.FailFast: %v", job.Strategy.GetFailFast())
logging.Debugf("Job.Strategy.FailFastString: %v", job.Strategy.FailFastString)
logging.Debugf("Job.Strategy.MaxParallelString: %v", job.Strategy.MaxParallelString)
logging.Debugf("Job.Strategy.RawMatrix: %v", job.Strategy.RawMatrix)
// An unevaluated expression is left in place, which GetMatrixes below rejects.
if err := strategyRc.NewExpressionEvaluator(ctx).EvaluateYamlNode(ctx, &job.Strategy.RawMatrix); err != nil {
logging.Errorf("Error while evaluating matrix: %v", err)
if err := strategyRc.ExprEval.EvaluateYamlNode(ctx, &job.Strategy.RawMatrix); err != nil {
return failStrategy(err)
}
for _, value := range []*string{&job.Strategy.FailFastString, &job.Strategy.MaxParallelString} {
if evaluated, err := strategyRc.ExprEval.Interpolate(ctx, *value); err == nil {
*value = evaluated
evaluated, err := strategyRc.ExprEval.Interpolate(ctx, *value)
if err != nil {
return failStrategy(err)
}
*value = evaluated
}
}
}
matrixes, err := job.GetMatrixes()
if err != nil {
return fmt.Errorf("could not get job matrix: %w", err)
return failStrategy(fmt.Errorf("could not get job matrix: %w", err))
}
logging.Debugf("Job Matrices: %v", matrixes)
@@ -252,6 +263,7 @@ func (runner *runnerImpl) NewPlanExecutor(plan *model.Plan) common.Executor {
logging.Infof("Running job with maxParallel=%d for %d matrix combinations", maxParallel, len(matrixes))
var callerRunIndex int
for i, matrix := range matrixes {
index, total := i, len(matrixes)
if runner.caller == nil && runner.config.PresetGitHubContext != nil && len(matrix) > 0 {
@@ -271,20 +283,19 @@ func (runner *runnerImpl) NewPlanExecutor(plan *model.Plan) common.Executor {
rc.Name = fmt.Sprintf("%s-%d", rc.Name, i+1)
}
maxJobNameLen = max(maxJobNameLen, len(rc.String()))
if rc.caller != nil { // For Gitea
rc.caller.setReusedWorkflowJobResult(rc.Run.JobID, "pending")
if i == 0 && runner.caller != nil {
callerRunIndex = len(runner.caller.reportedRuns)
runner.caller.reportedRuns = append(runner.caller.reportedRuns, nil)
}
rc.callerRunIndex = callerRunIndex
stageExecutor = append(stageExecutor, func(ctx context.Context) error {
jobName := fmt.Sprintf("%-*s", maxJobNameLen, rc.String())
executor, err := rc.Executor()
if err != nil {
return err
}
jobCtx := common.WithJobErrorContainer(WithJobLogger(ctx, rc.Run.JobID, jobName, rc.Config, &rc.Masks, matrix))
jobCtx, cancelTimeout := applyJobTimeout(jobCtx, rc, job)
defer cancelTimeout()
return executor(jobCtx)
ctx = WithJobLogger(ctx, rc.Run.JobID, fmt.Sprintf("%-*s", maxJobNameLen, rc.String()), rc.Config, &rc.Masks, matrix)
return executor(common.WithJobErrorContainer(ctx))
})
}
// Run all matrix combinations of this job, then drop its aggregation mutex: the
@@ -336,15 +347,20 @@ func (runner *runnerImpl) NewPlanExecutor(plan *model.Plan) common.Executor {
}
func handleFailure(plan *model.Plan) common.Executor {
return func(ctx context.Context) error {
return func(_ctx context.Context) error {
var failure error
for _, stage := range plan.Stages {
for _, run := range stage.Runs {
if run.Job().Result == "failure" && !run.Job().ContinueOnError {
return fmt.Errorf("job '%s' failed", run.String())
job := run.Job()
if job.Result == "cancelled" && (len(job.Steps) > 0 || job.Uses != "") {
return jobTimeoutCancellation{}
}
if failure == nil && job.NeedsResult() == "failure" {
failure = fmt.Errorf("job '%s' failed", run.String())
}
}
}
return nil
return failure
}
}
@@ -379,11 +395,3 @@ func (runner *runnerImpl) newCombinationRunContext(ctx context.Context, run *mod
return rc, nil
}
// For Gitea
// Keyed by job id, not name: only the values are read, and masking can collapse two names into one.
func (c *caller) setReusedWorkflowJobResult(jobID, result string) {
c.updateResultLock.Lock()
defer c.updateResultLock.Unlock()
c.reusedWorkflowJobResults[jobID] = result
}

View File

@@ -7,7 +7,6 @@ package runner
import (
"bytes"
"context"
"crypto/rand"
"fmt"
"os"
"path/filepath"
@@ -15,10 +14,13 @@ import (
"strings"
"sync"
"testing"
"testing/synctest"
"time"
"gitea.com/gitea/runner/act/common"
"gitea.com/gitea/runner/act/common/logging"
"gitea.com/gitea/runner/act/common/logging/logtest"
"gitea.com/gitea/runner/act/container"
"gitea.com/gitea/runner/act/ghcontext"
"gitea.dev/actionslib/pkg/model"
@@ -33,7 +35,6 @@ var (
logLevel = logging.LevelDebug
workdir = "testdata"
secrets map[string]string
testRunID = strings.ToLower(rand.Text()[:8]) // keeps docker names apart from concurrent test processes on one daemon
testCheckoutPins sync.Map
)
@@ -170,6 +171,51 @@ func TestNewPlanExecutorRequiresRunsOnBeforeRunningAnyJob(t *testing.T) {
assert.Equal(t, "success", workflow.Jobs["build"].Result)
}
func TestLocalPlanContinuesAfterCancellationAndInvalidJobTimeout(t *testing.T) {
workflow, err := model.ReadWorkflow(strings.NewReader(`
jobs:
upstream: {}
timed: {needs: upstream, if: always(), runs-on: ubuntu-latest, timeout-minutes: 1, steps: [run: exit 1]}
skipped:
needs: timed
runs-on: ubuntu-latest
timeout-minutes: ${{ fromJSON('invalid') }}
steps: [run: exit 1]
unsupported: {needs: timed, if: always(), runs-on: unknown, steps: [run: exit 1]}
invalid:
needs: timed
if: always()
runs-on: ubuntu-latest
timeout-minutes: ${{ fromJSON('"abc"') }}
steps: [run: exit 1]
downstream: {needs: invalid, runs-on: ubuntu-latest, steps: [run: exit 1]}
`))
require.NoError(t, err)
workflow.Jobs["upstream"].Result = "failure"
plan, err := model.CombineWorkflowPlanner(workflow).PlanAll()
require.NoError(t, err)
slow := &containerMock{}
slow.On("Pull", false).Return(func(ctx context.Context) error {
<-ctx.Done()
return ctx.Err()
})
slow.On("Remove").Return(noopExecutor)
slow.On("Close").Return(noopExecutor)
original := newContainer
newContainer = func(_input *container.NewContainerInput) container.ExecutionsEnvironment { return slow }
t.Cleanup(func() { newContainer = original })
runner := &runnerImpl{config: &Config{Env: testCheckoutEnv(), PlatformPicker: mapPlatformPicker(platforms)}}
hook := logtest.NewWithLevel(logging.LevelError)
synctest.Test(t, func(t *testing.T) {
ctx := common.WithLoggerHandler(common.WithDryrun(t.Context(), true), hook)
require.ErrorIs(t, runner.NewPlanExecutor(plan)(ctx), context.Canceled)
})
for jobID, want := range map[string]string{"timed": "cancelled", "skipped": "skipped", "unsupported": "skipped", "invalid": "failure", "downstream": "skipped"} {
assert.Equal(t, want, workflow.Jobs[jobID].Result, jobID)
}
assert.Contains(t, hook.LastRecord().Message, "Error when evaluating 'timeout-minutes' for job 'invalid'. Unexpected value 'abc'")
}
func TestGraphEvent(t *testing.T) {
planner, err := model.NewWorkflowPlanner("testdata/basic", true)
assert.NoError(t, err) //nolint:testifylint // pre-existing issue from nektos/act
@@ -237,8 +283,6 @@ func (j *TestJobFileInfo) runTest(ctx context.Context, t *testing.T, cfg *Config
EventName: j.eventName,
EventPath: cfg.EventPath,
PlatformPicker: mapPlatformPicker(j.platforms),
// fixtures reuse workflow and job names, so parallel tests would collide without this
ContainerNamePrefix: strings.ReplaceAll(t.Name(), "/", "-") + "-" + testRunID,
// 0 would run jobs runtime.NumCPU()-wide, making the network peak machine-dependent
MaxParallel: 2,
Env: cfg.Env,
@@ -297,7 +341,7 @@ func TestRunEvent(t *testing.T) {
{workdir, "local-action-docker-url", "push", "", platforms, secrets},
{workdir, "local-action-dockerfile", "push", "", platforms, secrets},
{workdir, "local-action-via-composite-dockerfile", "push", "", platforms, secrets},
{workdir, "local-action-js", "push", "", platforms, secrets},
{workdir, "local-action-js", "push", "", map[string]string{"ubuntu-latest": "ubuntu:24.04"}, secrets},
// Uses
{workdir, "uses-composite", "push", "", platforms, secrets},
@@ -367,7 +411,7 @@ func TestRunEvent(t *testing.T) {
config := &Config{
Secrets: table.secrets,
Env: map[string]string{"GITHUB_REPOSITORY": t.Name() + "-" + testRunID},
Env: map[string]string{"GITHUB_REPOSITORY": t.Name()},
}
eventFile := filepath.Join(workdir, table.workflowPath, "event.json")

View File

@@ -5,6 +5,7 @@
package runner
import (
"cmp"
"context"
"fmt"
maps0 "maps"
@@ -163,7 +164,8 @@ func runStepExecutor(step step, stage stepStage, executor common.Executor) commo
topRC := rc.topLevelRunContext()
stepSummaryIndex := topRC.CurrentStepIndex
summaryFileCommand := path.Join("workflow", "step-summary-"+strconv.Itoa(stepSummaryIndex)+".md")
(*step.getEnv())["GITHUB_STEP_SUMMARY"] = container.JoinPath(actPath, summaryFileCommand)
summaryPath := container.JoinPath(actPath, summaryFileCommand)
(*step.getEnv())["GITHUB_STEP_SUMMARY"] = summaryPath
aliasGiteaEnv(*step.getEnv())
// Reset the per-phase file-command files. GITHUB_STEP_SUMMARY is intentionally
@@ -188,11 +190,12 @@ func runStepExecutor(step step, stage stepStage, executor common.Executor) commo
fileCommandInitErr = rc.JobContainer.Copy(actPath, files...)(ctx) // a broken summary must not block the resets
}
timeoutctx, cancelTimeOut := evaluateStepTimeout(ctx, step)
defer cancelTimeOut()
timeoutCtx, cancelTimeout := evaluateStepTimeout(ctx, step, stage, stepString)
defer cancelTimeout()
err = fileCommandInitErr
if err == nil {
err = rc.runWithCommands(timeoutctx, *step.getEnv(), executor)
err = rc.runWithCommands(timeoutCtx, *step.getEnv(), executor)
err = cmp.Or(context.Cause(timeoutCtx), err)
}
fileCommandCtx := ctx
if ctx.Err() != nil { // an interrupted step still records its file commands, a live deadline stays in force
@@ -213,11 +216,15 @@ func runStepExecutor(step step, stage stepStage, executor common.Executor) commo
if fileErr := rc.UpdateExtraPath(fileCommandCtx, container.JoinPath(actPath, pathFileCommand)); fileErr != nil && err == nil {
err = fileErr
}
processStepSummary(fileCommandCtx, rc, summaryPath)
}
_ = rc.JobContainer.Copy(actPath, files...)(fileCommandCtx)
if err == nil {
logger.With("stepResult", stepResult.Conclusion).Infof("Success - %s %s", stage, stepString)
} else if _, timedOut := context.Cause(ctx).(jobTimeout); timedOut || ctx.Err() == context.Canceled {
stepResult.Outcome, stepResult.Conclusion = model.StepStatusFailure, model.StepStatusFailure
logger.With("stepResult", "cancelled").Infof("Cancelled - %s %s", stage, stepString)
} else {
stepResult.Outcome = model.StepStatusFailure
@@ -245,16 +252,24 @@ func runStepExecutor(step step, stage stepStage, executor common.Executor) commo
}
}
func evaluateStepTimeout(ctx context.Context, step step) (context.Context, context.CancelFunc) {
if step.getStepModel().TimeoutMinutes == "" {
return ctx, func() {}
}
timeout, err := step.getRunContext().NewStepExpressionEvaluator(ctx, step).Interpolate(ctx, step.getStepModel().TimeoutMinutes)
if err != nil {
common.Logger(ctx).Errorf("An error occurred when attempting to determine the step timeout: %s", err)
} else if timeout != "" {
if timeOutMinutes, err := strconv.ParseInt(timeout, 10, 64); err == nil && timeOutMinutes > 0 {
return context.WithTimeout(ctx, time.Duration(timeOutMinutes)*time.Minute)
type stepTimeout string
func (timeout stepTimeout) Error() string { return string(timeout) }
func (stepTimeout) Unwrap() error { return context.DeadlineExceeded }
func evaluateStepTimeout(ctx context.Context, step step, stage stepStage, name string) (context.Context, context.CancelFunc) {
if raw := step.getStepModel().TimeoutMinutes; raw != "" {
minutes, err := step.getRunContext().NewStepExpressionEvaluator(ctx, step).shared(ctx).EvaluateTimeoutMinutes(raw)
if err != nil {
logger := common.Logger(ctx)
logger.Error("##[error]An error occurred when attempting to determine the step timeout.")
logger.Errorf("##[error]%s", EscapeCommandData(err.Error()))
} else if minutes > 0 {
name = model.StepDisplayName(step.getStepModel(), name)
if stage != stepStageMain {
name = stage.String() + " " + name
}
return context.WithTimeoutCause(ctx, time.Duration(minutes)*time.Minute, stepTimeout(fmt.Sprintf("The action '%s' has timed out after %d minutes.", name, minutes)))
}
}
return ctx, func() {}
@@ -315,7 +330,7 @@ func isStepEnabled(ctx context.Context, expr string, step step, stage stepStage)
if rc.Parent != nil && stage == stepStageMain && jobContext.Status != "cancelled" {
jobContext.Status = rc.ownStatus()
}
runStep, err := EvalBool(ctx, rc.newStepExpressionEvaluator(ctx, step, rc.actionInputs, jobContext, rc.getGithubContext(ctx)), expr, defaultStatusCheck)
runStep, err := EvalBool(ctx, rc.newExpressionEvaluator(ctx, *step.getEnv(), jobContext, rc.getGithubContext(ctx), "step"), expr, defaultStatusCheck)
if err != nil {
return false, fmt.Errorf("if-expression %q evaluation failed: %s", expr, err)
}

View File

@@ -83,12 +83,12 @@ func (sal *stepActionLocal) main() common.Executor {
sal.action = actionModel
return sal.runAction(sal, actionDir, nil)(ctx)
return sal.runAction(sal)(ctx)
})
}
func (sal *stepActionLocal) post() common.Executor {
return runStepExecutor(sal, stepStagePost, runPostStep(sal)).If(hasPostStep(sal)).If(shouldRunPostStep(sal))
return runStepExecutor(sal, stepStagePost, runActionHook(sal, stepStagePost)).If(hasPostStep(sal)).If(shouldRunPostStep(sal))
}
func (sal *stepActionLocal) getRunContext() *RunContext {
@@ -117,18 +117,13 @@ func (sal *stepActionLocal) getActionModel() *model.Action {
return sal.action
}
func (sal *stepActionLocal) getCompositeRunContext(ctx context.Context) (*RunContext, error) {
func (sal *stepActionLocal) getCompositeRunContext(ctx context.Context, inputs map[string]string) *RunContext {
if sal.compositeRunContext == nil {
_, containerActionDir := getContainerActionPaths(sal)
compositeRunContext, err := newCompositeRunContext(ctx, sal.RunContext, sal, containerActionDir)
if err != nil {
return nil, err
}
sal.compositeRunContext = compositeRunContext
sal.compositeSteps = compositeRunContext.compositeExecutor(sal.action)
sal.compositeRunContext = newCompositeRunContext(ctx, sal.RunContext, sal, containerActionDir, inputs)
sal.compositeSteps = sal.compositeRunContext.compositeExecutor(sal.action)
}
return sal.compositeRunContext, nil
return sal.compositeRunContext
}
func (sal *stepActionLocal) getCompositeSteps() *compositeSteps {

View File

@@ -25,8 +25,8 @@ type stepActionMocks struct {
mock.Mock
}
func (salm *stepActionMocks) runAction(step actionStep, actionDir string, remoteAction *remoteAction) common.Executor {
args := salm.Called(step, actionDir, remoteAction)
func (salm *stepActionMocks) runAction(step actionStep) common.Executor {
args := salm.Called(step)
return args.Get(0).(func(context.Context) error)
}
@@ -89,7 +89,7 @@ func TestStepActionLocalTest(t *testing.T) {
expectStepFileCommands(t, cm)
salm.On("runAction", sal, filepath.Clean("/tmp/path/to/action"), (*remoteAction)(nil)).Return(func(ctx context.Context) error {
salm.On("runAction", sal).Return(func(ctx context.Context) error {
sal.RunContext.setOutput(ctx, map[string]string{"name": "value"}, "ran")
return nil
})

View File

@@ -46,11 +46,9 @@ var stepActionRemoteFetch = git.FetchAction
func (sar *stepActionRemote) fetchAction(ctx context.Context, remote *remoteAction, token string) (string, string, error) {
cloneURL := remote.CloneURL(sar.RunContext.Config.DefaultActionURL())
return stepActionRemoteFetch(ctx, sar.RunContext.Config.withInstanceAuth(git.NewGitCloneExecutorInput{
URL: cloneURL,
Ref: remote.Ref,
Dir: filepath.Join(sar.RunContext.ActionCacheDir(), model.UsesHash(remote.downloadKey(sar.RunContext.Config.DefaultActionURL()))),
OfflineMode: sar.RunContext.Config.ActionOfflineMode,
Depth: sar.RunContext.Config.ActionCloneDepth,
URL: cloneURL,
Ref: remote.Ref,
Dir: filepath.Join(sar.RunContext.ActionCacheDir(), model.UsesHash(remote.downloadKey(sar.RunContext.Config.DefaultActionURL()))),
}, token))
}
@@ -145,7 +143,7 @@ func (sar *stepActionRemote) pre() common.Executor {
sar.prepareActionExecutor(),
runStepExecutor(sar, stepStagePre, func(ctx context.Context) error {
sar.preStepStarted = true
return runPreStep(sar)(ctx)
return runActionHook(sar, stepStagePre)(ctx)
}).If(hasPreStep(sar)).If(shouldRunPreStep(sar)))
}
@@ -164,13 +162,13 @@ func (sar *stepActionRemote) main() common.Executor {
return sar.RunContext.JobContainer.CopyDir(copyToPath, sar.RunContext.Config.Workdir+string(filepath.Separator)+".", sar.RunContext.Config.UseGitIgnore, false)(ctx)
}
return sar.runAction(sar, sar.actionDir, sar.remoteAction)(ctx)
return sar.runAction(sar)(ctx)
}),
)
}
func (sar *stepActionRemote) post() common.Executor {
return runStepExecutor(sar, stepStagePost, runPostStep(sar)).If(hasPostStep(sar)).If(shouldRunPostStep(sar))
return runStepExecutor(sar, stepStagePost, runActionHook(sar, stepStagePost)).If(hasPostStep(sar)).If(shouldRunPostStep(sar))
}
func (sar *stepActionRemote) containerKey() string {
@@ -217,16 +215,11 @@ func (sar *stepActionRemote) getActionModel() *model.Action {
return sar.action
}
func (sar *stepActionRemote) getCompositeRunContext(ctx context.Context) (*RunContext, error) {
func (sar *stepActionRemote) getCompositeRunContext(ctx context.Context, inputs map[string]string) *RunContext {
if sar.compositeRunContext == nil {
_, containerActionDir := getContainerActionPaths(sar)
compositeRunContext, err := newCompositeRunContext(ctx, sar.RunContext, sar, containerActionDir)
if err != nil {
return nil, err
}
sar.compositeRunContext = compositeRunContext
sar.compositeSteps = compositeRunContext.compositeExecutor(sar.action)
sar.compositeRunContext = newCompositeRunContext(ctx, sar.RunContext, sar, containerActionDir, inputs)
sar.compositeSteps = sar.compositeRunContext.compositeExecutor(sar.action)
} else {
// Re-evaluate environment here. For remote actions the environment
// need to be re-created for every stage (pre, main, post) as there
@@ -234,14 +227,10 @@ func (sar *stepActionRemote) getCompositeRunContext(ctx context.Context) (*RunCo
// stages are executed. (e.g. the output of another action is the
// input for this action during the main stage, but the env
// was already created during the pre stage)
env, err := evaluateCompositeInputAndEnv(ctx, sar.RunContext, sar)
if err != nil {
return nil, err
}
sar.compositeRunContext.setCompositeActionEnv(env)
sar.compositeRunContext.setCompositeActionEnv(sar.env, inputs)
sar.compositeRunContext.ExtraPath = sar.RunContext.ExtraPath
}
return sar.compositeRunContext, nil
return sar.compositeRunContext
}
func (sar *stepActionRemote) getCompositeSteps() *compositeSteps {

View File

@@ -114,7 +114,7 @@ func TestStepActionRemote(t *testing.T) {
sarm.On("readAction", sar.Step, actionDir, "", mock.Anything, mock.Anything).Return(&model.Action{}, nil)
if tt.status != model.StepStatusSkipped {
sarm.On("runAction", sar, actionDir, mustNewRemoteAction(t, sar.Step.Uses)).Return(func(_ctx context.Context) error { return tt.runError })
sarm.On("runAction", sar).Return(func(_ctx context.Context) error { return tt.runError })
expectStepFileCommands(t, cm)
}
@@ -133,17 +133,15 @@ func TestStepActionRemote(t *testing.T) {
t.Run("refreshes composite inputs without leaking environment", func(t *testing.T) {
step := &stepActionRemote{
Step: &model.Step{Uses: "org/composite@v1", With: map[string]string{"SHARED": "first"}},
Step: &model.Step{Uses: "org/composite@v1"},
RunContext: &RunContext{Config: &Config{ActionCacheDir: t.TempDir(), PresetGitHubContext: &model.GithubContext{}}, Run: &model.Run{JobID: "job", Workflow: &model.Workflow{Jobs: map[string]*model.Job{"job": {}}}}, JobContainer: &jobContainerMock{}},
action: &model.Action{Inputs: map[string]model.Input{"shared": {}}},
env: map[string]string{},
action: &model.Action{},
env: map[string]string{"INPUT_SHARED": "stale", "INPUT_UNDECLARED": "stale"},
remoteAction: mustNewRemoteAction(t, "org/composite@v1"),
}
for _, value := range []string{"first", "second"} {
step.env["INPUT_SHARED"] = value
composite, err := step.getCompositeRunContext(t.Context())
require.NoError(t, err)
composite := step.getCompositeRunContext(t.Context(), map[string]string{"SHARED": value})
assert.Equal(t, map[string]any{"shared": value}, composite.actionInputs)
assert.NotContains(t, composite.Env, "INPUT_SHARED")
}
@@ -238,8 +236,8 @@ func TestStepActionRemotePreCleanup(t *testing.T) {
_, actionDir := getContainerActionPaths(sar)
expectStepFileCommands(t, cm)
cm.On("CopyDir", actionDir+"/", sar.actionDir+"/", false, true).Return(noopExecutor)
cm.On("Exec", nodeActionCommand(path.Join(actionDir, "pre.js")), mock.Anything, "", "").Return(func(_ctx context.Context) error { return test.preError }).Once()
cm.On("Exec", nodeActionCommand(path.Join(actionDir, "post.js")), mock.Anything, "", "").Return(noopExecutor).Once()
cm.On("Exec", nodeActionCommand("node", path.Join(actionDir, "pre.js")), mock.Anything, "", "").Return(func(_ctx context.Context) error { return test.preError }).Once()
cm.On("Exec", nodeActionCommand("node", path.Join(actionDir, "post.js")), mock.Anything, "", "").Return(noopExecutor).Once()
}
assert.Equal(t, test.preError, sar.pre()(t.Context()))

View File

@@ -6,6 +6,8 @@ package runner
import (
"context"
"errors"
"fmt"
"strings"
"gitea.com/gitea/runner/act/common"
@@ -26,7 +28,7 @@ func (sd *stepDocker) pre() common.Executor { return common.NewPipelineExecutor(
func (sd *stepDocker) main() common.Executor {
sd.env = map[string]string{}
return runStepExecutor(sd, stepStageMain, sd.runUsesContainer())
return runStepExecutor(sd, stepStageMain, sd.runUsesContainer)
}
func (sd *stepDocker) post() common.Executor { return common.NewPipelineExecutor() }
@@ -47,37 +49,38 @@ func (sd *stepDocker) getIfExpression(_ context.Context, _ stepStage) string {
return sd.Step.If.Value
}
func (sd *stepDocker) runUsesContainer() common.Executor {
func (sd *stepDocker) runUsesContainer(ctx context.Context) error {
rc := sd.RunContext
step := sd.Step
return func(ctx context.Context) error {
if rc.isWindowsHost() {
return errWindowsHostContainer
}
if rc.kubernetes {
return errKubernetesDocker
}
image := strings.TrimPrefix(step.Uses, "docker://")
cmd, err := shellquote.Split(stepInput(step, "args"))
if err != nil {
return err
}
var entrypoint []string
if entry := stepInput(step, "entrypoint"); entry != "" {
entrypoint = []string{entry}
}
stepContainer := newStepContainer(ctx, sd, image, cmd, entrypoint, "")
return common.NewPipelineExecutor(
stepContainer.Pull(rc.Config.ForcePull),
stepContainer.Remove(),
stepContainer.Create(rc.Config.ContainerCapAdd, rc.Config.ContainerCapDrop),
stepContainer.Start(true),
).Finally(stepContainer.Close())(ctx)
if rc.isWindowsHost() {
return errWindowsHostContainer
}
if rc.kubernetes {
return errKubernetesDocker
}
cmd, err := shellquote.Split(stepInput(sd.Step, "args"))
if err != nil {
return err
}
var entrypoint []string
if entry := stepInput(sd.Step, "entrypoint"); entry != "" {
entrypoint = []string{entry}
}
input := stepContainerInput(ctx, sd, strings.TrimPrefix(sd.Step.Uses, "docker://"), cmd, entrypoint, "")
return rc.runStepContainer(ctx, ContainerNewContainer(input), nil, rc.Config.ForcePull)
}
func (rc *RunContext) runStepContainer(ctx context.Context, stepContainer container.Container, prepImage common.Executor, forcePull bool) error {
if stepContainer == nil {
return fmt.Errorf("running a Docker action: %w", errors.ErrUnsupported)
}
return common.NewPipelineExecutor(
prepImage,
stepContainer.Pull(forcePull),
stepContainer.Remove(),
stepContainer.Create(rc.Config.ContainerCapAdd, rc.Config.ContainerCapDrop),
stepContainer.Start(true),
).Finally(stepContainer.Close())(ctx)
}
var ContainerNewContainer = container.NewContainer

View File

@@ -5,8 +5,8 @@
package runner
import (
"errors"
"slices"
"strings"
"testing"
"gitea.com/gitea/runner/act/container"
@@ -43,28 +43,14 @@ func TestStepDockerMain(t *testing.T) {
"DOCKER_PASSWORD": "docker-password",
},
},
Run: &model.Run{
JobID: "1",
Workflow: &model.Workflow{
Jobs: map[string]*model.Job{
"1": {
Defaults: model.Defaults{
Run: model.RunDefaults{
Shell: "bash",
},
},
},
},
},
},
Run: &model.Run{JobID: "1", Workflow: &model.Workflow{Jobs: map[string]*model.Job{"1": {}}}},
JobContainer: cm,
Env: map[string]string{"GITHUB_ACTION_REPOSITORY": "other/composite", "GITHUB_ACTION_REF": "v1"},
},
Step: &model.Step{
ID: "1",
Uses: "docker://node:14",
WorkingDirectory: "workdir",
If: yaml.Node{Value: "github.action_repository == 'other/composite' && github.action_ref == 'v1'"},
ID: "1",
Uses: "docker://node:14",
If: yaml.Node{Value: "github.action_repository == 'other/composite' && github.action_ref == 'v1'"},
},
}
require.NoError(t, sd.Step.RawWith.Encode(map[string]string{"args": "identity:${{ github.action_repository }}:${{ github.action_ref }}"}))
@@ -95,67 +81,35 @@ func TestStepDockerMain(t *testing.T) {
assert.True(t, input.AutoRemove)
cm.AssertExpectations(t)
ContainerNewContainer = func(_input *container.NewContainerInput) container.ExecutionsEnvironment { return nil }
require.ErrorIs(t, sd.runUsesContainer(ctx), errors.ErrUnsupported)
}
func TestStepDockerNewStepContainer(t *testing.T) {
inheritedPath := (&container.LinuxContainerEnvironmentExtensions{}).DefaultPathVariable()
for _, test := range []struct {
name, platform, image, path, greeting string
allocPTY, expectDefault, keepsPath bool
name, platform, path, network string
allocPTY, keepsPath bool
}{
{name: "allocate PTY/off", platform: "node:14", image: "node:14", greeting: "hi"},
{name: "allocate PTY/on", platform: "node:14", image: "node:14", greeting: "hi", allocPTY: true},
{name: "docker mode attaches to job container network", platform: "node:14", image: "alpine:3.20", path: inheritedPath, greeting: "hello", keepsPath: true},
{name: "host mode uses default network and the image's PATH", platform: "-self-hosted", image: "alpine:3.20", path: inheritedPath, greeting: "hello", expectDefault: true},
{name: "host mode keeps a PATH that is not the runner's", platform: "-self-hosted", image: "alpine:3.20", path: "/custom/bin", greeting: "hello", expectDefault: true, keepsPath: true},
{name: "docker mode attaches to job container network", platform: "node:14", path: inheritedPath, network: "job-network", allocPTY: true, keepsPath: true},
{name: "host mode uses default network and the image's PATH", platform: "-self-hosted", path: inheritedPath, network: "default"},
{name: "host mode keeps a PATH that is not the runner's", platform: "-self-hosted", path: "/custom/bin", network: "default", keepsPath: true},
} {
t.Run(test.name, func(t *testing.T) {
cm := &containerMock{}
var captured *container.NewContainerInput
origContainerNewContainer := ContainerNewContainer
ContainerNewContainer = func(input *container.NewContainerInput) container.ExecutionsEnvironment {
captured = input
return cm
job := &RunContext{
Config: &Config{AllocatePTY: test.allocPTY},
Run: &model.Run{Workflow: &model.Workflow{}},
jobNetworkName: "job-network",
}
defer func() {
ContainerNewContainer = origContainerNewContainer
}()
ctx := t.Context()
sd := &stepDocker{
RunContext: &RunContext{
StepResults: map[string]*model.StepResult{},
Config: &Config{
PresetGitHubContext: &model.GithubContext{},
AllocatePTY: test.allocPTY,
PlatformPicker: func(_platforms []string) string {
return test.platform
},
},
Run: &model.Run{JobID: "1", Workflow: &model.Workflow{Jobs: map[string]*model.Job{"1": {}}}},
JobContainer: cm,
},
Step: &model.Step{ID: "1", Uses: "docker://" + test.image},
}
sd.RunContext.ExprEval = sd.RunContext.NewExpressionEvaluator(ctx)
if test.path != "" {
sd.env = map[string]string{"PATH": test.path}
require.NoError(t, sd.RunContext.resolvePlatformImage(ctx))
assert.Equal(t, test.expectDefault, sd.RunContext.IsHostEnv(), "IsHostEnv mismatch for platform %q", test.platform)
}
newStepContainer(ctx, sd, test.image, []string{"echo", test.greeting}, nil, "")
assert.Equal(t, test.allocPTY, captured.AllocatePTY)
if test.path != "" {
assert.Equal(t, test.keepsPath, slices.Contains(captured.Env, "PATH="+test.path))
if test.expectDefault {
assert.Equal(t, "default", captured.NetworkMode,
"host-mode step container must use 'default' network, got %q", captured.NetworkMode)
} else {
assert.True(t, strings.HasPrefix(captured.NetworkMode, "container:"),
"docker-mode step container must attach to job container network, got %q", captured.NetworkMode)
}
step := &stepDocker{
RunContext: &RunContext{Parent: job, Config: job.Config, JobContainer: &containerMock{}, platformImage: test.platform},
Step: &model.Step{},
env: map[string]string{"PATH": test.path},
}
input := stepContainerInput(t.Context(), step, "alpine", nil, nil, "")
assert.Equal(t, test.network, input.NetworkMode)
assert.Equal(t, test.allocPTY, input.AllocatePTY)
assert.Equal(t, test.keepsPath, slices.Contains(input.Env, "PATH="+test.path))
})
}
}
@@ -181,10 +135,10 @@ func TestWindowsHostContainerActions(t *testing.T) {
wantError = errWindowsHostContainer.Error()
}
t.Run("docker step", func(t *testing.T) {
require.EqualError(t, (&stepDocker{RunContext: rc}).runUsesContainer()(t.Context()), wantError)
require.EqualError(t, (&stepDocker{RunContext: rc}).runUsesContainer(t.Context()), wantError)
})
t.Run("container action", func(t *testing.T) {
require.EqualError(t, execAsDocker(t.Context(), &stepActionRemote{RunContext: rc}, "action", "", "", false, stepStageMain), wantError)
require.EqualError(t, execAsDocker(t.Context(), &stepActionRemote{RunContext: rc}, stepStageMain, nil, "", ""), wantError)
})
})
}

View File

@@ -17,6 +17,9 @@ type stepFactory interface {
type stepFactoryImpl struct{}
func (sf *stepFactoryImpl) newStep(stepModel *model.Step, rc *RunContext) (step, error) {
if stepModel.Uses != "" && stepModel.Run == "" && rc.Config.ReplaceUses != nil {
stepModel.Uses = rc.Config.ReplaceUses(stepModel.Uses)
}
switch stepModel.Type() {
case model.StepTypeInvalid:
return nil, fmt.Errorf("invalid run/uses syntax for job:%s step:%+v", rc.Name, stepModel)

View File

@@ -5,6 +5,7 @@
package runner
import (
"cmp"
"testing"
"gitea.dev/actionslib/pkg/model"
@@ -12,7 +13,9 @@ import (
"github.com/stretchr/testify/require"
)
func TestStepFactoryNewStep(t *testing.T) {
func TestStepFactoryNewStepAppliesReplaceUsesToUsesOnly(t *testing.T) {
replacements := map[string]string{"": "docker://image:tag", "remote/replaced@v1": "docker://image:tag"}
rc := &RunContext{Config: &Config{ReplaceUses: func(uses string) string { return cmp.Or(replacements[uses], uses) }}}
for _, test := range []struct {
name string
model *model.Step
@@ -21,21 +24,23 @@ func TestStepFactoryNewStep(t *testing.T) {
{"StepRemoteAction", &model.Step{Uses: "remote/action@v1"}, &stepActionRemote{}},
{"StepLocalAction", &model.Step{Uses: "./action@v1"}, &stepActionLocal{}},
{"StepDocker", &model.Step{Uses: "docker://image:tag"}, &stepDocker{}},
{"StepReplaced", &model.Step{Uses: "remote/replaced@v1"}, &stepDocker{}},
{"StepRun", &model.Step{Run: "cmd"}, &stepRun{}},
} {
t.Run(test.name, func(t *testing.T) {
step, err := (&stepFactoryImpl{}).newStep(test.model, &RunContext{})
step, err := (&stepFactoryImpl{}).newStep(test.model, rc)
require.NoError(t, err)
assert.IsType(t, test.want, step)
})
}
}
func TestStepFactoryInvalidStep(t *testing.T) {
func TestStepFactoryInvalidStepStaysInvalidWhenReplaceUsesEmptiesUses(t *testing.T) {
rc := &RunContext{Name: "build", Config: &Config{ReplaceUses: func(string) string { return "" }}}
for _, stepModel := range []*model.Step{
{Uses: "remote/action@v1", Run: "cmd"},
} {
_, err := (&stepFactoryImpl{}).newStep(stepModel, &RunContext{Name: "build"})
_, err := (&stepFactoryImpl{}).newStep(stepModel, rc)
assert.ErrorContains(t, err, "job:build ", stepModel.Uses)
}
}

View File

@@ -88,27 +88,23 @@ func (sr *stepRun) printRunScriptActionDetails(ctx context.Context) {
// printRunActionHeader mirrors actions/runner's "Run <action>" header for `uses:` steps,
// including the with: inputs and the step-level env: block.
func printRunActionHeader(ctx context.Context, step *model.Step, action *model.Action, env map[string]string, rc *RunContext) {
if step == nil {
return
}
rawLogger := common.Logger(ctx).With(rawOutputField, true)
rawLogger.Infof("::group::Run %s", EscapeCommandData(step.Uses))
inputs := map[string]string{}
maps.Copy(inputs, step.With)
if action != nil {
inputs := step.With
if action != nil && len(action.Inputs) != 0 {
inputs = mergeMaps(inputs)
for name := range action.Inputs {
if _, provided := common.LookupFold(step.With, name, true); !provided {
inputs[name] = env[inputEnvKey(name)]
}
}
}
maps.DeleteFunc(inputs, func(_name, value string) bool { return value == "" })
if len(inputs) > 0 {
rawLogger.Infof("with:")
for _, k := range slices.Sorted(maps.Keys(inputs)) {
logKeyedValue(rawLogger, k, inputs[k])
rawLogger := common.Logger(ctx).With(rawOutputField, true)
rawLogger.Infof("::group::Run %s", EscapeCommandData(step.Uses))
names := slices.DeleteFunc(slices.Sorted(maps.Keys(inputs)), func(name string) bool { return inputs[name] == "" })
if len(names) > 0 {
rawLogger.Info("with:")
for _, name := range names {
logKeyedValue(rawLogger, name, inputs[name])
}
}

View File

@@ -15,6 +15,7 @@ import (
"testing/synctest"
"gitea.com/gitea/runner/act/common"
"gitea.com/gitea/runner/act/common/logging"
"gitea.com/gitea/runner/act/common/logging/logtest"
"gitea.com/gitea/runner/act/container"
"gitea.com/gitea/runner/internal/pkg/telemetry"
@@ -179,7 +180,7 @@ func TestSetupEnv(t *testing.T) {
"GITHUB_JOB": "1",
"GITHUB_REF_PROTECTED": "false",
"GITHUB_RETENTION_DAYS": "0",
"GITHUB_RUN_ATTEMPT": "",
"GITHUB_RUN_ATTEMPT": "1",
"GITHUB_RUN_ID": "runId",
"GITHUB_RUN_NUMBER": "1",
"GITHUB_WORKFLOW": "",
@@ -235,7 +236,7 @@ jobs:
t.Parallel()
rc, err := (&runnerImpl{config: &Config{PresetGitHubContext: &model.GithubContext{}}}).newRunContext(t.Context(), &model.Run{Workflow: workflow, JobID: "test"}, map[string]any{"env": `{"WORKFLOW":"` + value + `${{ github.job }}","PRIORITY":"workflow"}`, "priority": "${{ github.job }}", "defaults": `{"shell":"` + value + `"}`})
require.NoError(t, err)
rc.workflowCallInputs = map[string]any{"args": `{"name":"` + value + `${{ github.job }}","fetch-depth":1234567}`}
rc.Config.WorkflowCallInputs = map[string]any{"args": `{"name":"` + value + `${{ github.job }}","fetch-depth":1234567}`}
enabled, err := rc.isEnabled(t.Context())
require.NoError(t, err)
require.True(t, enabled)
@@ -263,7 +264,7 @@ jobs:
require.NoError(t, err)
rc, err := (&runnerImpl{config: &Config{PresetGitHubContext: &model.GithubContext{}}}).newRunContext(t.Context(), &model.Run{Workflow: workflow, JobID: "test"}, nil)
require.NoError(t, err)
rc.workflowCallInputs = map[string]any{"args": "${{ inputs.unresolved }}"}
rc.Config.WorkflowCallInputs = map[string]any{"args": "${{ inputs.unresolved }}"}
require.ErrorContains(t, setupInputs(t.Context(), &stepRun{RunContext: rc, Step: workflow.Jobs["test"].Steps[0].Clone(), env: map[string]string{}}), "with:")
})
@@ -541,11 +542,13 @@ func TestRunStepExecutorParity(t *testing.T) {
t.Run("file commands survive a job timeout", func(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
step := newStep(t, &model.Step{ID: "interrupted"})
ctx, cancel := applyJobTimeout(t.Context(), step.RunContext, &model.Job{TimeoutMinutes: "1"})
step := newStep(t, &model.Step{ID: "interrupted", RawContinueOnError: "true"})
logger, hook := logtest.NewLogger()
ctx, cancel, err := applyJobTimeout(common.WithLogger(t.Context(), logger), step.RunContext, &model.Job{TimeoutMinutes: "1"})
require.NoError(t, err)
defer cancel()
step.RunContext.JobContainer = &fileCommandTestContainer{step.RunContext.JobContainer.(*container.HostEnvironment)}
err := runStepExecutor(step, stepStageMain, func(execCtx context.Context) error {
err = runStepExecutor(step, stepStageMain, func(execCtx context.Context) error {
for name, content := range map[string]string{
"GITHUB_ENV": "KEPT_ENV=value\n", "GITHUB_STATE": "saved=value\n",
"GITHUB_OUTPUT": "kept=value\n", "GITHUB_PATH": "/kept/bin\n",
@@ -556,6 +559,7 @@ func TestRunStepExecutorParity(t *testing.T) {
return execCtx.Err()
})(ctx)
require.ErrorIs(t, err, context.DeadlineExceeded)
assert.Equal(t, "cancelled", lastRecordAttr(hook, "stepResult"))
assert.Equal(t, "value", step.RunContext.Env["KEPT_ENV"])
assert.Equal(t, "value", step.RunContext.IntraActionState[step.Step.ID]["saved"])
assert.Equal(t, "value", step.RunContext.StepResults[step.Step.ID].Outputs["kept"])
@@ -612,23 +616,43 @@ func TestRunStepExecutorParity(t *testing.T) {
assert.Contains(t, ended[3].Attributes(), semconv.CICDPipelineTaskRunResultFailure)
})
t.Run("timeout must be positive", func(t *testing.T) {
for timeout, wantDeadline := range map[string]bool{"-1": false, "0": false, "1": true} {
ctx, cancel := evaluateStepTimeout(t.Context(), newStep(t, &model.Step{TimeoutMinutes: timeout}))
t.Run("nonpositive or invalid timeouts leave the step deadline unset", func(t *testing.T) {
for timeout, wantError := range map[string]string{
"-1": "",
"0": "",
`${{ '1' }}`: "##[error]Unexpected value '1'",
} {
hook := logtest.NewWithLevel(logging.LevelError)
ctx, cancel := evaluateStepTimeout(common.WithLogger(t.Context(), logging.New(hook)),
newStep(t, &model.Step{TimeoutMinutes: timeout}), stepStageMain, "")
_, hasDeadline := ctx.Deadline()
cancel()
assert.Equal(t, wantDeadline, hasDeadline, timeout)
assert.False(t, hasDeadline, timeout)
records := hook.AllRecords()
if wantError == "" {
assert.Empty(t, records, timeout)
} else {
require.Len(t, records, 2)
assert.Equal(t, "##[error]An error occurred when attempting to determine the step timeout.", records[0].Message)
assert.Equal(t, wantError, records[1].Message)
}
}
})
t.Run("timeout reads step environment", func(t *testing.T) {
step := newStep(t, &model.Step{ID: "timeout", TimeoutMinutes: "${{ fromJSON(env.STEP_TIMEOUT) }}"})
require.NoError(t, step.Step.Env.Encode(map[string]string{"STEP_TIMEOUT": "1"}))
require.NoError(t, runStepExecutor(step, stepStageMain, func(ctx context.Context) error {
_, hasDeadline := ctx.Deadline()
assert.True(t, hasDeadline)
return nil
})(t.Context()))
synctest.Test(t, func(t *testing.T) {
step := newStep(t, &model.Step{ID: "timeout", Run: "echo first\necho second", TimeoutMinutes: "${{ fromJSON(env.STEP_TIMEOUT) }}"})
require.NoError(t, step.Step.Env.Encode(map[string]string{"STEP_TIMEOUT": "1"}))
err := runStepExecutor(step, stepStageMain, func(ctx context.Context) error {
_, ok := ctx.Deadline()
require.True(t, ok)
<-ctx.Done()
return nil
})(t.Context())
require.EqualError(t, err, "The action 'Run echo first' has timed out after 1 minutes.")
require.ErrorIs(t, err, context.DeadlineExceeded)
assert.Equal(t, model.StepStatusFailure, step.RunContext.StepResults[step.Step.ID].Conclusion)
})
})
}

View File

@@ -6,6 +6,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: test -n '${{ hashFiles('local-action-js/push.yml') }}'
- uses: ./actions/node24
with:
who-to-greet: 'Mona the Octocat'

View File

@@ -1,4 +1,12 @@
# Host-mode background processes
# Host mode
## Stable workspace
Host jobs run in a random `<host.workdir_parent>/<16 hex>/hostexecutor` directory. With `host.stable_workdir: true`, Linux host jobs run in `<host.workdir_parent>/workspaces/<owner>/<repo>/<repo>` instead, like GitHub's `_work/<repo>/<repo>`. This needs `CAP_SYS_ADMIN`, so run the runner as root or with `AmbientCapabilities=CAP_SYS_ADMIN` in its systemd unit. Steps don't get the capability. Without it, jobs keep the random directory and log a warning.
Concurrent jobs of a repository use the same path, each with its own files, through a private mount namespace. On the host, the path shows the files of one of them, so processes started outside a job, like containers from `docker run -v "$PWD:/src"` or systemd services, only see the right files there in that job. Every job starts with an empty workspace.
## Background processes
Host jobs clean up background step processes at job completion. A step can opt out:

View File

@@ -51,7 +51,7 @@ Job pods mount no service account token unless the template sets `automountServi
## Copying files over the pod network
The runner copies files into the job container, such as the actions a step uses, with `tar` over `pods/exec`. That data goes through the API server, which on a managed cluster often sits in other zones than the nodes, so each byte can cross zones twice. With `transfer.mode` set to `auto` or `direct`, the job container instead fetches directories, such as actions and workspaces, and other copies of 64 KiB or more gzipped from the runner pod. Smaller ones, like step scripts, stay on `pods/exec`, as do copies out of the job container and step output.
The runner copies files into the job container, such as the actions a step uses, with `tar` over `pods/exec`. That data goes through the API server, which on a managed cluster often sits in other zones than the nodes, so each byte can cross zones twice. With `transfer.mode` set to `auto` or `direct`, the job container instead fetches directories, such as actions and workspaces, and other copies of 64 KiB or more gzipped from the runner pod. Smaller ones, like step scripts, stay on `pods/exec`, as do copies out of the job container and step output. The runner's Node.js is copied the same way.
```yaml
kubernetes:

View File

@@ -32,14 +32,17 @@ func testFailurePaths(t *testing.T, m mode) {
func testJobTimeout(t *testing.T) {
t.Parallel()
api, repo, _ := startIsolatedScenario(t, "timeout.yml", "e2e-timeout", runnerOptions{timeout: 15 * time.Second})
const timeout = 15 * time.Second
api, repo, _ := startIsolatedScenario(t, "timeout.yml", "e2e-timeout", runnerOptions{timeout: timeout})
wfRun := waitForRun(t, api, repo)
completed, err := api.WaitForRunConclusion(t.Context(), repo, wfRun.ID, runTimeout)
if err != nil {
dumpRunLogs(t, api, repo, wfRun.ID)
t.Fatalf("wait for run: %v", err)
}
if logs := runLogs(t, api, repo, wfRun.ID); completed.Conclusion != "failure" || commandRow(logs, "e2e-timeout-started") == "" {
t.Errorf("run concluded %q, want failure after the job started, logs:\n%s", completed.Conclusion, logs)
logs := runLogs(t, api, repo, wfRun.ID)
if completed.Conclusion != "failure" || commandRow(logs, "e2e-timeout-started") == "" ||
commandRow(logs, "job exceeded runner.timeout of "+timeout.String()) == "" {
t.Errorf("run concluded %q, want failure after the job started and exceeded runner.timeout, logs:\n%s", completed.Conclusion, logs)
}
}

View File

@@ -24,6 +24,7 @@ RestartSec=5s
# Allow running jobs to finish before the runner is stopped. Keep this in sync
# with runner.shutdown_timeout in the config.
KillMode=mixed
TimeoutStopSec=3h
[Install]

10
go.mod
View File

@@ -6,19 +6,19 @@ toolchain go1.27.4
require (
connectrpc.com/connect/v2 v2.0.2
gitea.dev/actionslib v1.6.0
gitea.dev/actionslib v1.7.1
github.com/bmatcuk/doublestar/v4 v4.10.4
github.com/coder/websocket v1.8.15
github.com/containerd/errdefs v1.0.0
github.com/creack/pty v1.1.24
github.com/distribution/reference v0.6.0
github.com/docker/cli v29.9.3+incompatible
github.com/docker/cli v29.10.0+incompatible
github.com/docker/go-connections v0.8.2
github.com/docker/go-units v0.5.0
github.com/joho/godotenv v1.5.1
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51
github.com/moby/moby/api v1.56.1
github.com/moby/moby/client v0.6.2
github.com/moby/moby/api v1.57.0
github.com/moby/moby/client v0.6.3
github.com/moby/patternmatcher v0.6.1
github.com/opencontainers/image-spec v1.1.1
github.com/prometheus/client_golang v1.25.0
@@ -33,7 +33,7 @@ require (
go.opentelemetry.io/otel/trace v1.47.0
go.opentelemetry.io/proto/otlp v1.11.1
go.yaml.in/yaml/v4 v4.0.0
golang.org/x/net v0.62.0
golang.org/x/net v0.63.0
golang.org/x/sync v0.25.0
golang.org/x/sys v0.50.0
golang.org/x/term v0.48.0

22
go.sum
View File

@@ -1,7 +1,7 @@
connectrpc.com/connect/v2 v2.0.2 h1:PoPDmOlhc46elsuCdKCKTxjNBb3HJlKF+s/sP2oucPw=
connectrpc.com/connect/v2 v2.0.2/go.mod h1:N32OLrstcPUzkykFynnefFro3+xzSdOrZlK2jHmS/xo=
gitea.dev/actionslib v1.6.0 h1:1xKhGyJzL9CYHJ+ESqFdxetbAU+2U7YIEuPYtsS3Fuk=
gitea.dev/actionslib v1.6.0/go.mod h1:i8wUQMnvGwT13f2re2ZTMCFL/TyauQLeOb1L4ngjtPk=
gitea.dev/actionslib v1.7.1 h1:vOSV4K99kK5RBdMnTVRuwJCisL3egpNbvGpA7XhPXdA=
gitea.dev/actionslib v1.7.1/go.mod h1:i8wUQMnvGwT13f2re2ZTMCFL/TyauQLeOb1L4ngjtPk=
github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=
github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
@@ -21,8 +21,8 @@ github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s=
github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE=
github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk=
github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E=
github.com/docker/cli v29.9.3+incompatible h1:SBaMp7ecohadEHMDrUJg22t9I3awqsAVhnJ7GOcWpfE=
github.com/docker/cli v29.9.3+incompatible/go.mod h1:JLrzqnKDaYBop7H2jaqPtU4hHvMKP+vjCwu2uszcLI8=
github.com/docker/cli v29.10.0+incompatible h1:lCL+clBUJnHsmjBCr6TwvfQFkmBidPxi5SkuXCoYxc0=
github.com/docker/cli v29.10.0+incompatible/go.mod h1:JLrzqnKDaYBop7H2jaqPtU4hHvMKP+vjCwu2uszcLI8=
github.com/docker/go-connections v0.8.2 h1:9d9DEokx5W7qlr0shkFXIxEA7+TTD+llwzcykSlxMNc=
github.com/docker/go-connections v0.8.2/go.mod h1:no1qkHdjq7kLMGUXYAduOhYPSJxxvgWBh7ogVvptn3Q=
github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4=
@@ -50,10 +50,10 @@ github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0=
github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo=
github.com/moby/moby/api v1.56.1 h1:PpWkvVPB7Fr/No8w+TfyJ/I6rWZ2YPZhT3JorIg+06c=
github.com/moby/moby/api v1.56.1/go.mod h1:sZ+THbVWkjOmBPPfbnzdD/G1LuIexWhqlSHHPTDQ1Uk=
github.com/moby/moby/client v0.6.2 h1:ekSPlMccrZGcw6Scb8T9D39qE0mB+XupU/yS0zNw9N4=
github.com/moby/moby/client v0.6.2/go.mod h1:DGcnO7qmPJrqobx/ggQgQ/AUk+2wgVdQv7uxB0/mEsc=
github.com/moby/moby/api v1.57.0 h1:K2ykv5UZjwFCtmtL486T+SUEVrQ46w3v7isf214RCcw=
github.com/moby/moby/api v1.57.0/go.mod h1:pRZ1QRtx6AVhdckeFYo4DUX4ASNF0SCllhyY6aj2mgg=
github.com/moby/moby/client v0.6.3 h1:XJn2T8YdXBdMgQl7JrOx09NEBuzIpVXcsN2KDHufAKY=
github.com/moby/moby/client v0.6.3/go.mod h1:7CXNAnAhcwwqjwjXqLembJczRorLfM+5mu0d5363lCc=
github.com/moby/patternmatcher v0.6.1 h1:qlhtafmr6kgMIJjKJMDmMWq7WLkKIo23hsrpR3x084U=
github.com/moby/patternmatcher v0.6.1/go.mod h1:hDPoyOpDY7OrrMDLaYoY3hf52gNCR/YOUYxkhApJIxc=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
@@ -111,8 +111,8 @@ go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
go.yaml.in/yaml/v4 v4.0.0 h1:/LG1pNO84Z4l603j/xMn69CcS5OYhMQ/f7l2LoQUGuw=
go.yaml.in/yaml/v4 v4.0.0/go.mod h1:aZqd9kCMsGL7AuUv/m/PvWLdg5sjJsZ4oHDEnfPPfY0=
golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY=
golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=
golang.org/x/net v0.63.0 h1:HCoTmNh9EpD1PpK8gBNFY4gcTY4N+KQEO8ylfIKqFJ0=
golang.org/x/net v0.63.0/go.mod h1:15JLg3IX1bLjHK264EZQEbIpTiR/KVLuo9CTRWd0pig=
golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs=
golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs=
@@ -126,5 +126,3 @@ google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gotest.tools/v3 v3.5.2 h1:7koQfIKdy+I8UTetycgUqXWSDwpgv193Ka+qRsmBY8Q=
gotest.tools/v3 v3.5.2/go.mod h1:LtdLGcnqToBH83WByAAi/wiwSFCArdFIUV/xxN4pcjA=
pgregory.net/rapid v1.2.0 h1:keKAYRcjm+e1F0oAuU5F5+YPAWcyxNNRK2wud503Gnk=
pgregory.net/rapid v1.2.0/go.mod h1:PY5XlDGj0+V1FCq0o192FdRhpKHGTRIWBgqjDBTrq04=

View File

@@ -19,6 +19,7 @@ import (
"time"
"gitea.com/gitea/runner/act/common/logging"
actrunner "gitea.com/gitea/runner/act/runner"
"gitea.com/gitea/runner/internal/app/poll"
"gitea.com/gitea/runner/internal/app/run"
"gitea.com/gitea/runner/internal/pkg/client"
@@ -180,6 +181,12 @@ func runDaemon(ctx context.Context, daemArgs *daemonArgs, configFile *string) fu
cfg.Runner.ExtraHeaders,
)
if cfg.Runner.NodeDownload == nil || *cfg.Runner.NodeDownload {
has := func(scheme string) bool {
return slices.ContainsFunc(ls, func(label *labels.Label) bool { return label.Schema == scheme })
}
actrunner.PrefetchNode(filepath.FromSlash(cfg.Host.WorkdirParent), cfg.Runner.NodeVersion, has(labels.SchemeHost), has(labels.SchemeDocker), has(labels.SchemeKubernetes))
}
runner := run.NewRunner(cfg, reg, cli)
defer func() {
if err := runner.Close(); err != nil {
@@ -295,21 +302,19 @@ type daemonArgs struct {
// resolveLabels picks the labels to run with: --labels/GITEA_RUNNER_LABELS > config > .runner.
// The flag lets a registered runner change its labels without deleting the .runner file.
func resolveLabels(argLabels string, cfgLabels, regLabels []string) []string {
if lbls := splitLabels(argLabels); len(lbls) > 0 {
lbls := trimLabels(strings.Split(argLabels, ","))
if lbls = slices.DeleteFunc(lbls, func(label string) bool { return label == "" }); len(lbls) > 0 {
return lbls
}
if len(cfgLabels) > 0 {
return cfgLabels
regLabels = cfgLabels
}
return regLabels
return trimLabels(slices.Clone(regLabels))
}
func splitLabels(s string) []string {
var lbls []string
for l := range strings.SplitSeq(s, ",") {
if l = strings.TrimSpace(l); l != "" {
lbls = append(lbls, l)
}
func trimLabels(lbls []string) []string {
for i := range lbls {
lbls[i] = strings.TrimSpace(lbls[i])
}
return lbls
}

View File

@@ -39,9 +39,9 @@ func TestResolveLabels(t *testing.T) {
reg []string
want []string
}{
{"flag wins", "flag:host,other", cfgLabels, regLabels, []string{"flag:host", "other"}},
{"config wins over registration", "", cfgLabels, regLabels, cfgLabels},
{"registration is the fallback", "", nil, regLabels, regLabels},
{"flag wins", "flag:host, , other", cfgLabels, regLabels, []string{"flag:host", "other"}},
{"config wins over registration", "", []string{" cfg:host "}, regLabels, cfgLabels},
{"registration is the fallback", "", nil, []string{" reg:host "}, regLabels},
{"blank flag is ignored", " , ", cfgLabels, regLabels, cfgLabels},
{"nothing configured", "", nil, nil, nil},
}
@@ -131,7 +131,7 @@ func TestDaemonRetriesDeclareOutagesAndRemovesOnlyConsumedEphemeralRegistration(
dir := t.TempDir()
regFile := filepath.Join(dir, "registration.json")
configFile := filepath.Join(dir, "config.yaml")
require.NoError(t, os.WriteFile(configFile, []byte("runner:\n file: "+regFile+"\n idle_cleanup_interval: 0s\ncache:\n enabled: false\n"), 0o600))
require.NoError(t, os.WriteFile(configFile, []byte("runner:\n file: "+regFile+"\n idle_cleanup_interval: 0s\n node_download: false\ncache:\n enabled: false\n"), 0o600))
for _, tc := range []struct {
name string

View File

@@ -67,6 +67,7 @@ type executeArgs struct {
artifactServerAddr string
artifactServerPort string
noSkipCheckout bool
noNodeDownload bool
debug bool
dryrun bool
image string
@@ -387,6 +388,7 @@ func (i *executeArgs) runnerConfig(eventName string, env, proxyEnv map[string]st
ArtifactServerPort: i.artifactServerPort,
ArtifactServerAddr: i.artifactServerAddr,
NoSkipCheckout: i.noSkipCheckout,
NoNodeDownload: i.noNodeDownload,
EventName: eventName,
EventJSON: eventJSON,
ContainerNamePrefix: "GITEA-ACTIONS-TASK-" + eventName,
@@ -587,6 +589,7 @@ func loadExecCmd(ctx context.Context) *cobra.Command {
execCmd.PersistentFlags().StringVarP(&execArg.artifactServerPort, "artifact-server-port", "", "34567", "Defines the port where the artifact server listens")
execCmd.PersistentFlags().StringVarP(&execArg.defaultActionsURL, "default-actions-url", "", "https://github.com", "Defines the default url of action instance.")
execCmd.PersistentFlags().BoolVarP(&execArg.noSkipCheckout, "no-skip-checkout", "", false, "Do not skip actions/checkout")
execCmd.PersistentFlags().BoolVarP(&execArg.noNodeDownload, "no-node-download", "", false, "Run JavaScript actions and hashFiles() with the node on PATH instead of a downloaded Node.js")
execCmd.PersistentFlags().BoolVarP(&execArg.debug, "debug", "d", false, "enable debug log")
execCmd.PersistentFlags().BoolVarP(&execArg.dryrun, "dryrun", "n", false, "dryrun mode")
execCmd.PersistentFlags().StringVarP(&execArg.image, "image", "i", config.DefaultImage, "Docker image to use. Use \"kubernetes://<image>\" to run it as a pod, \"-self-hosted\" to run directly on the host.")

View File

@@ -162,7 +162,7 @@ func (r *registerInputs) assignToNext(stage registerStage, value string, cfg *co
// if there are some labels configured in config file, skip input labels stage
if len(cfg.Runner.Labels) > 0 {
ls := make([]string, 0, len(cfg.Runner.Labels))
for _, l := range cfg.Runner.Labels {
for _, l := range trimLabels(cfg.Runner.Labels) {
_, err := labels.Parse(l)
if err != nil {
logging.WithError(err).Warnf("ignored invalid label %q", l)
@@ -180,7 +180,7 @@ func (r *registerInputs) assignToNext(stage registerStage, value string, cfg *co
case StageInputLabels:
r.Labels = defaultLabels
if value != "" {
r.Labels = strings.Split(value, ",")
r.Labels = trimLabels(strings.Split(value, ","))
}
if validateLabels(r.Labels) != nil {
@@ -216,10 +216,8 @@ func initInputs(regArgs *registerArgs) (*registerInputs, error) {
RunnerName: strings.TrimSpace(regArgs.RunnerName),
Ephemeral: regArgs.Ephemeral,
}
regArgs.Labels = strings.TrimSpace(regArgs.Labels)
// command line flag.
if regArgs.Labels != "" {
inputs.Labels = strings.Split(regArgs.Labels, ",")
if labels := strings.TrimSpace(regArgs.Labels); labels != "" {
inputs.Labels = trimLabels(strings.Split(labels, ","))
}
return inputs, nil
}
@@ -303,10 +301,10 @@ func registerNoInteractive(ctx context.Context, configFile string, regArgs *regi
}
// specify labels in config file.
if len(cfg.Runner.Labels) > 0 {
if regArgs.Labels != "" {
if len(inputs.Labels) > 0 {
logging.Warn("Labels from command will be ignored, use labels defined in config file.")
}
inputs.Labels = cfg.Runner.Labels
inputs.Labels = trimLabels(cfg.Runner.Labels)
}
if len(inputs.Labels) == 0 {
inputs.Labels = defaultLabels

View File

@@ -144,7 +144,7 @@ func TestRegisterInputsAssignToNext(t *testing.T) {
t.Run("labels from config skip the labels stage", func(t *testing.T) {
cfg := &config.Config{}
cfg.Runner.Labels = []string{"ubuntu:host", "", "pool:e57e18d4"}
cfg.Runner.Labels = []string{" ubuntu:host ", " ", "pool:e57e18d4"}
inputs := &registerInputs{}
require.Equal(t, StageWaitingForRegistration, inputs.assignToNext(StageInputRunnerName, "runner", cfg))
require.Equal(t, []string{"ubuntu:host", "pool:e57e18d4"}, inputs.Labels)
@@ -158,13 +158,13 @@ func TestRegisterInputsAssignToNext(t *testing.T) {
t.Run("invalid labels input loops back", func(t *testing.T) {
inputs := &registerInputs{}
require.Equal(t, StageInputLabels, inputs.assignToNext(StageInputLabels, "ubuntu:host,,bad", emptyCfg))
require.Equal(t, StageInputLabels, inputs.assignToNext(StageInputLabels, "ubuntu:host, ,bad", emptyCfg))
require.Nil(t, inputs.Labels)
})
t.Run("labels containing a colon are accepted", func(t *testing.T) {
inputs := &registerInputs{}
require.Equal(t, StageWaitingForRegistration, inputs.assignToNext(StageInputLabels, "pool:e57e18d4,ubuntu:host", emptyCfg))
require.Equal(t, StageWaitingForRegistration, inputs.assignToNext(StageInputLabels, "pool:e57e18d4 , ubuntu:host", emptyCfg))
require.Equal(t, []string{"pool:e57e18d4", "ubuntu:host"}, inputs.Labels)
})
@@ -245,7 +245,7 @@ func TestInitInputs(t *testing.T) {
require.Equal(t, tc.wantToken, inputs.Token)
require.Equal(t, "runner", inputs.RunnerName)
require.True(t, inputs.Ephemeral)
require.Equal(t, []string{"ubuntu:host ", " ubuntu:docker://node:18"}, inputs.Labels)
require.Equal(t, []string{"ubuntu:host", "ubuntu:docker://node:18"}, inputs.Labels)
})
}

View File

@@ -49,14 +49,12 @@ func TestRunPostTaskScriptNonZeroExitDoesNotPanic(t *testing.T) {
cfg.Runner.PostTaskScript = scriptPath
r := &Runner{cfg: cfg}
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
task := &runnerv1.Task{Id: 1, Context: &structpb.Struct{}}
reporter := report.NewReporter(ctx, cancel, nil, task, cfg)
reporter := report.NewReporter(t.Context(), nil, nil, task, cfg)
require.NotPanics(t, func() {
r.runPostTaskScript(ctx, reporter, task, "/workspace/owner/repo")
r.runPostTaskScript(t.Context(), reporter, task, "/workspace/owner/repo")
})
require.NotNil(t, hook.LastRecord())
assert.Contains(t, hook.LastRecord().Message, "exited with code 2")
@@ -92,16 +90,13 @@ func TestPostTaskScriptEnv(t *testing.T) {
envs: map[string]string{"BASE": "1"},
}
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
taskCtx, err := structpb.NewStruct(map[string]any{
"run_id": "99",
"repository": "acme/widget",
})
require.NoError(t, err)
task := &runnerv1.Task{Id: 3, Context: taskCtx}
reporter := report.NewReporter(ctx, cancel, nil, task, cfg)
reporter := report.NewReporter(t.Context(), nil, nil, task, cfg)
setReporterJobResult(t, reporter, runnerv1.Result_RESULT_FAILURE)
env := r.postTaskScriptEnv(reporter, task, "/tmp/workspace")
@@ -134,14 +129,11 @@ func TestRunPostTaskScriptIntegration(t *testing.T) {
envs: map[string]string{"CUSTOM": "runner-env"},
}
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
task := &runnerv1.Task{Id: 11, Context: &structpb.Struct{}}
reporter := report.NewReporter(ctx, cancel, nil, task, cfg)
reporter := report.NewReporter(t.Context(), nil, nil, task, cfg)
setReporterJobResult(t, reporter, runnerv1.Result_RESULT_SUCCESS)
r.runPostTaskScript(ctx, reporter, task, "/workspace/acme/repo")
r.runPostTaskScript(t.Context(), reporter, task, "/workspace/acme/repo")
content, err := os.ReadFile(outFile)
require.NoError(t, err)

View File

@@ -73,8 +73,8 @@ type Runner struct {
cacheHandler *artifactcache.Handler
capabilities string
isolatedCacheContainer func(cacheURL string) string
instanceTransport http.RoundTripper
cacheIsolation func(cacheURL string) container.CacheIsolation
instanceTransport http.RoundTripper
runningTasks sync.Map
runningCount atomic.Int64
@@ -141,7 +141,7 @@ func NewRunner(cfg *config.Config, reg *config.Registration, cli client.Client)
now: time.Now,
runHealthCheck: executeHealthCheck,
}
runner.isolatedCacheContainer = lastResult(runner.detectIsolatedCacheContainer)
runner.cacheIsolation = lastResult(runner.detectCacheIsolation)
runner.instanceTransport = instanceTransport
return runner
}
@@ -196,7 +196,7 @@ func (r *Runner) cleanupOrphanDockerResources(ctx context.Context) {
return
}
cutoff := r.now().Add(-orphanDockerResourceAge)
if err := removeOrphanNetworks(ctx, r.uuid, r.isolatedCacheContainer(r.cacheHandler.ExternalURL()), cutoff); err != nil {
if err := removeOrphanNetworks(ctx, r.uuid, r.cacheIsolation(r.cacheHandler.ExternalURL()).ContainerID, cutoff); err != nil {
logging.Warnf("failed to clean up networks left behind by earlier jobs: %v", err)
}
if err := removeOrphanJobVolumes(ctx, r.uuid, cutoff); err != nil {
@@ -300,11 +300,12 @@ func (r *Runner) Run(ctx context.Context, task *runnerv1.Task) (err error) {
start := time.Now()
ctx, cancel := context.WithTimeout(ctx, r.cfg.Runner.Timeout)
ctx, cancel := context.WithTimeoutCause(ctx, r.cfg.Runner.Timeout, fmt.Errorf("job exceeded runner.timeout of %s", r.cfg.Runner.Timeout))
defer cancel()
ctx, cancelJob := context.WithCancelCause(ctx)
ctx, endJob := telemetry.StartJob(ctx, task)
// A proxy URL may carry credentials, and every job is given it; keep them out of the log.
reporter := report.NewReporter(ctx, cancel, r.client, task, r.cfg, proxyPasswords(r.envs)...)
reporter := report.NewReporter(ctx, cancelJob, r.client, task, r.cfg, proxyPasswords(r.envs)...)
var volumeCleanup []common.Executor
var volumeCleanupMu sync.Mutex
if r.cfg.Runner.PostTaskScript == "" {
@@ -316,11 +317,7 @@ func (r *Runner) Run(ctx context.Context, task *runnerv1.Task) (err error) {
}
var runErr error
defer func() {
lastWords := ""
if runErr != nil {
lastWords = runErr.Error()
}
err = reporter.Close(lastWords)
err = reporter.Close(runErr)
if err := cleanupJobVolumes(ctx, volumeCleanup); err != nil {
logging.Warnf("task %d volume cleanup after reporting: %v", task.Id, err)
}
@@ -331,6 +328,9 @@ func (r *Runner) Run(ctx context.Context, task *runnerv1.Task) (err error) {
}()
reporter.RunDaemon()
runErr = r.run(ctx, task, reporter)
if ctx.Err() != nil && errors.Is(runErr, ctx.Err()) {
runErr = context.Cause(ctx)
}
return nil
}
@@ -519,6 +519,9 @@ func (r *Runner) run(ctx context.Context, task *runnerv1.Task, reporter *report.
preset := model.GithubContextFromMap(task.Context.AsMap())
preset.Token = cmp.Or(task.Secrets["GITEA_TOKEN"], task.Secrets["GITHUB_TOKEN"], preset.Token)
if task.Secrets == nil {
task.Secrets = make(map[string]string)
}
if actionsIDTokenRequestURL := taskContext["actions_id_token_request_url"].GetStringValue(); actionsIDTokenRequestURL != "" {
envs["ACTIONS_ID_TOKEN_REQUEST_URL"] = actionsIDTokenRequestURL
envs["ACTIONS_ID_TOKEN_REQUEST_TOKEN"] = taskContext["actions_id_token_request_token"].GetStringValue()
@@ -627,13 +630,17 @@ func (r *Runner) run(ctx context.Context, task *runnerv1.Task, reporter *report.
DefaultActionInstance: r.getDefaultActionsURL(task),
DefaultActionInstanceIsSelfHosted: r.isSelfHostedActionsURL(task),
PlatformPicker: platformPicker,
ReplaceUses: r.cfg.Runner.ReplaceUses,
JobStartedHook: r.cfg.Runner.Hooks.JobStarted,
JobCompletedHook: r.cfg.Runner.Hooks.JobCompleted,
Vars: task.Vars,
ValidVolumes: r.cfg.Container.ValidVolumes,
ContainerVolumes: r.cfg.Container.Volumes,
NoNodeDownload: r.cfg.Runner.NodeDownload != nil && !*r.cfg.Runner.NodeDownload,
NodeVersion: r.cfg.Runner.NodeVersion,
SharedToolCache: r.cfg.Runner.ToolCacheMode == config.ToolCacheModeShared,
ToolCacheSlot: toolCacheSlot(r.cfg.Runner.ToolCacheMode, slot),
StableHostWorkdir: r.cfg.Host.StableWorkdir,
InsecureSkipTLS: r.cfg.Runner.Insecure,
ClientCertFile: r.cfg.Runner.ClientCertFile,
ClientKeyFile: r.cfg.Runner.ClientKeyFile,
@@ -647,8 +654,6 @@ func (r *Runner) run(ctx context.Context, task *runnerv1.Task, reporter *report.
if err != nil {
return err
}
executor := rr.NewPlanExecutor(plan)
reporter.Logf("workflow prepared")
// add logger recorders
@@ -658,7 +663,7 @@ func (r *Runner) run(ctx context.Context, task *runnerv1.Task, reporter *report.
ctx = runner.WithJobLoggerFactory(ctx, NullLogger{})
}
execErr := executor(ctx)
execErr := rr.NewPlanExecutor(plan)(ctx)
reporter.SetOutputs(job.Outputs)
if r.cfg.Container.BindWorkdir {
@@ -673,13 +678,13 @@ func (r *Runner) run(ctx context.Context, task *runnerv1.Task, reporter *report.
return execErr
}
func lastResult(compute func(key string) (string, bool)) func(key string) string {
func lastResult[T any](compute func(key string) (T, bool)) func(key string) T {
var (
mu sync.Mutex
lastKey string
result string
result T
)
return func(key string) string {
return func(key string) T {
mu.Lock()
defer mu.Unlock()
if key == lastKey {
@@ -965,10 +970,16 @@ func (r *Runner) cacheForJob(job *model.Job, platform string, logf func(string,
if cacheURL == "" || strings.HasPrefix(platform, labels.SchemeKubernetes+"://") || (jobContainer == nil || jobContainer.Image == "") && platform == labels.SelfHostedPlatform {
return cacheURL, ""
}
if cacheContainer := r.isolatedCacheContainer(cacheURL); cacheContainer != "" {
isolation := r.cacheIsolation(cacheURL)
if isolation.GatewayBridge {
logf("::warning::%s", runner.EscapeCommandData("Cache disabled for this job because it cannot reach the runner's docker_gwbridge address. "+
"Set cache.host to the host's address and publish a fixed cache.port on it in host mode."))
return "", ""
}
if isolation.ContainerID != "" {
isolatedURL, _ := url.Parse(cacheURL)
isolatedURL.Host = net.JoinHostPort(cacheContainer, isolatedURL.Port())
return isolatedURL.String(), cacheContainer
isolatedURL.Host = net.JoinHostPort(isolation.ContainerID, isolatedURL.Port())
return isolatedURL.String(), isolation.ContainerID
}
network, enableIPv6 := r.cfg.Container.Network, r.cfg.Container.NetworkCreateOptions.EnableIPv6
if addr, err := netip.ParseAddr(hostOf(cacheURL)); err == nil && addr.Is6() && r.cfg.Cache.Host == "" &&
@@ -979,19 +990,19 @@ func (r *Runner) cacheForJob(job *model.Job, platform string, logf func(string,
return cacheURL, ""
}
func (r *Runner) detectIsolatedCacheContainer(cacheURL string) (string, bool) {
func (r *Runner) detectCacheIsolation(cacheURL string) (container.CacheIsolation, bool) {
addr, err := netip.ParseAddr(hostOf(cacheURL))
if err != nil {
return "", true
return container.CacheIsolation{}, true
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
cacheContainer, err := container.IsolatedCacheContainer(ctx, addr, r.cfg.Container.Network)
isolation, err := container.DetectCacheIsolation(ctx, addr, r.cfg.Container.Network)
if err != nil {
logging.Warnf("cannot check whether jobs reach the cache server: %v", err)
return "", false
return container.CacheIsolation{}, false
}
return cacheContainer, true
return isolation, true
}
// taskLogFields returns key/value pairs for logging.With.

View File

@@ -341,7 +341,9 @@ func TestRunnerOnIdleRemovesOrphanNetworks(t *testing.T) {
require.NoError(t, err)
r := &Runner{uuid: "runner-1", cfg: cfg, labels: labels.Labels{kubernetesLabel}, now: func() time.Time { return now }}
r.isolatedCacheContainer = func(_cacheURL string) string { return "a1b2c3d4e5f6" }
r.cacheIsolation = func(_cacheURL string) container.CacheIsolation {
return container.CacheIsolation{ContainerID: "a1b2c3d4e5f6"}
}
r.OnIdle(t.Context())
assert.Equal(t, []string{"runner-1"}, swept)
assert.Equal(t, swept, sweptVolumes)
@@ -353,7 +355,7 @@ func TestRunnerOnIdleRemovesOrphanNetworks(t *testing.T) {
dockerReachable = func(context.Context) bool { return false }
t.Cleanup(func() { dockerReachable = origDockerReachable })
hostOnly := &Runner{uuid: "runner-2", cfg: &config.Config{Runner: cfg.Runner}, now: func() time.Time { return now }}
hostOnly.isolatedCacheContainer = func(_cacheURL string) string { return "" }
hostOnly.cacheIsolation = func(_cacheURL string) container.CacheIsolation { return container.CacheIsolation{} }
hostOnly.OnIdle(t.Context())
assert.Equal(t, []string{"runner-1"}, swept)
assert.Equal(t, swept, sweptVolumes)

View File

@@ -124,6 +124,7 @@ func TestRunnerReclaimsVolumesAfterReporting(t *testing.T) {
if response, ok := map[string]string{
"/_ping": "OK",
"/info": `{"Architecture":"amd64","OSType":"linux"}`,
"/version": `{"Os":"linux","Arch":"amd64"}`,
"/containers/json": "[]",
"/networks": "[]",
"/volumes": `{"Volumes":[]}`,
@@ -163,7 +164,7 @@ func TestRunnerReclaimsVolumesAfterReporting(t *testing.T) {
t.Cleanup(daemon.Close)
t.Setenv("DOCKER_HOST", daemon.URL)
require.NoError(t, r.Run(t.Context(), &runnerv1.Task{
Context: &structpb.Struct{},
Context: &structpb.Struct{Fields: map[string]*structpb.Value{"gitea_runtime_token": structpb.NewStringValue("runtime-token")}},
WorkflowPayload: []byte("jobs:\n job:\n runs-on: ubuntu\n steps:\n - run: exit 0\n if: false\n"),
}))
assert.True(t, reported.Load())
@@ -390,7 +391,9 @@ func TestNewRunnerCacheServiceV2(t *testing.T) {
workflow, err := model.ReadWorkflow(strings.NewReader(`jobs: {native: {runs-on: native}, linux: {runs-on: linux}, containerized: {runs-on: native, container: alpine}, empty: {runs-on: native, container: ""}}`))
require.NoError(t, err)
r.isolatedCacheContainer = func(_cacheURL string) string { return "a1b2c3d4e5f6" }
r.cacheIsolation = func(_cacheURL string) container.CacheIsolation {
return container.CacheIsolation{ContainerID: "a1b2c3d4e5f6"}
}
pickPlatform := func(runsOn []string) string { return map[string]string{"native": labels.SelfHostedPlatform}[runsOn[0]] }
for job, isolated := range map[string]bool{"native": false, "linux": true, "containerized": true, "empty": false} {
cacheURL, cacheContainer := r.cacheForJob(workflow.GetJob(job), pickPlatform(workflow.GetJob(job).RunsOn()), t.Logf)
@@ -404,14 +407,14 @@ func TestNewRunnerCacheServiceV2(t *testing.T) {
}
}
func TestCacheForJobIPv6WarningAndIsolationRecheck(t *testing.T) {
func TestCacheForJobWarningsAndIsolationRecheck(t *testing.T) {
handler, err := artifactcache.StartHandler(artifactcache.Options{OutboundIP: "2001:db8::1", Upstream: "http://cache.invalid"})
require.NoError(t, err)
defer handler.Close()
var checked []string
r := &Runner{cfg: &config.Config{}, cacheHandler: handler, isolatedCacheContainer: lastResult(func(cacheURL string) (string, bool) {
r := &Runner{cfg: &config.Config{}, cacheHandler: handler, cacheIsolation: lastResult(func(cacheURL string) (container.CacheIsolation, bool) {
checked = append(checked, cacheURL)
return "", cacheURL != "http://unreachable"
return container.CacheIsolation{}, cacheURL != "http://unreachable"
})}
warnings := 0
logf := func(_format string, _args ...any) { warnings++ }
@@ -434,9 +437,15 @@ func TestCacheForJobIPv6WarningAndIsolationRecheck(t *testing.T) {
r.cacheForJob(workflow.GetJob("containerized"), labels.SelfHostedPlatform, logf)
assert.Equal(t, 3, warnings)
r.isolatedCacheContainer("http://unreachable")
r.isolatedCacheContainer("http://unreachable")
r.cacheIsolation("http://unreachable")
r.cacheIsolation("http://unreachable")
assert.Len(t, checked, 3)
r.cacheIsolation = func(_cacheURL string) container.CacheIsolation { return container.CacheIsolation{GatewayBridge: true} }
cacheURL, cacheContainer := r.cacheForJob(workflow.GetJob("containerized"), labels.SelfHostedPlatform, logf)
assert.Empty(t, cacheURL)
assert.Empty(t, cacheContainer)
assert.Equal(t, 4, warnings)
}
func TestRestoreCalledWorkflowContext(t *testing.T) {

View File

@@ -33,7 +33,7 @@ func generateWorkflow(task *runnerv1.Task) (*model.Workflow, string, error) {
for id, need := range task.Needs {
workflow.Jobs[id] = &model.Job{
Outputs: need.Outputs,
Result: strings.ToLower(strings.TrimPrefix(need.Result.String(), "RESULT_")),
Result: need.Result.Conclusion(),
}
rawNeeds.Content = append(rawNeeds.Content, &yaml.Node{
Kind: yaml.ScalarNode,

View File

@@ -96,6 +96,17 @@ runner:
# and github_mirror is not empty. In this case,
# it replaces https://github.com with the value here, which is useful for some special network environments.
#github_mirror: ''
# Replaces the `uses` of steps whose regex matches it in full, with capture groups as ${1}, ${2} and so on.
# Entries apply in order, each to the result of the previous one.
#action_replacements:
# - regex: 'builtin:checkout'
# replacement: actions/checkout@v6
# - regex: 'actions/checkout@.*'
# replacement: actions/checkout@v6
# - regex: 'actions/setup-node@(.+)'
# replacement: self:actions/setup-node@${1}
# - regex: '(?:https://github\.com/)?actions/(.+)'
# replacement: https://git.example.com/mirror/${1}
# Extra HTTP headers for runner API requests to Gitea, e.g. reverse proxy authentication.
# Not used for action downloads, artifacts, job summaries or jobs. Runner headers take precedence.
# Dropped on redirects to another hostname, or to HTTP if the instance URL uses HTTPS.
@@ -112,6 +123,10 @@ runner:
# written for GitHub work against this instance. Set to false to run them exactly as published,
# at the price of the stock artifact actions refusing and the cache client keeping to v1.
#patch_actions: true
# Whether to download Node.js for JavaScript actions and hashFiles(). False uses the node on PATH.
#node_download: true
# The Node.js version to download, instead of the runner's default.
#node_version: 24.21.0
# The labels of a runner are used to determine which jobs the runner can run, and how to run them.
# Like: "macos-arm64:host" or "ubuntu-latest:docker://docker.gitea.com/runner-images:ubuntu-latest"
# Find more images provided by Gitea at https://gitea.com/gitea/runner-images .
@@ -166,9 +181,8 @@ cache:
# Directory where cache blobs are stored on disk. Default: $HOME/.cache/actcache
# Ignored when external_server is set.
#dir: ""
# Outbound IP or hostname that job containers use to reach this runner's cache server.
# Leave empty to detect automatically. 0.0.0.0 is not valid here.
# A runner container on the jobs' Docker daemon attaches to each job network automatically.
# IP or hostname jobs reach the cache server at, detected when empty. 0.0.0.0 is not valid.
# If jobs cannot reach the detected one, set the host's address and publish a fixed port.
#host: ""
# Port for the built-in cache server. 0 picks a random free port.
#port: 0
@@ -314,6 +328,9 @@ host:
# The parent directory of a job's working directory.
# If it's empty, $HOME/.cache/act/ will be used.
#workdir_parent:
# Run Linux host jobs at workdir_parent/workspaces/<owner>/<repo>/<repo> instead of a random
# directory. Needs CAP_SYS_ADMIN, see docs/host-mode.md.
#stable_workdir: false
# Jobs that run as Kubernetes pods, see docs/kubernetes.md.
kubernetes:

View File

@@ -40,6 +40,8 @@ const DefaultPostTaskScriptTimeout = 5 * time.Minute
var environmentReference = regexp.MustCompile(`\$?\$\{[A-Za-z_][A-Za-z0-9_]*\}`)
var nodeVersionPattern = regexp.MustCompile(`^[0-9]+\.[0-9]+\.[0-9]+$`)
// Minimal is the smallest config file that runs the runner: options it does not
// name keep their default, and it names none.
const Minimal = `# Minimal config file. Every option it does not set keeps its default.
@@ -61,39 +63,42 @@ type LogJob struct {
// Runner represents the configuration for the runner.
type Runner struct {
File string `yaml:"file"` // File specifies the file path for the runner.
Capacity int `yaml:"capacity"` // Capacity specifies the capacity of the runner.
Envs map[string]string `yaml:"envs"` // Envs stores environment variables for the runner.
EnvFile string `yaml:"env_file"` // EnvFile specifies the path to the file containing environment variables for the runner.
Timeout time.Duration `yaml:"timeout"` // Timeout specifies the duration for runner timeout.
ShutdownTimeout time.Duration `yaml:"shutdown_timeout"` // ShutdownTimeout specifies the duration to wait for running jobs to complete during a shutdown of the runner.
Insecure bool `yaml:"insecure"` // Insecure indicates whether the runner operates in an insecure mode.
ClientCertFile string `yaml:"client_cert_file"` // ClientCertFile is the PEM certificate presented to a Gitea instance that requires mutual TLS.
ClientKeyFile string `yaml:"client_key_file"` // ClientKeyFile is the PEM private key paired with ClientCertFile.
CAFile string `yaml:"ca_file"` // CAFile holds PEM CA certificates trusted for the Gitea instance besides the system's.
ExtraHeaders map[string]string `yaml:"extra_headers"` // ExtraHeaders adds HTTP headers to runner API requests to Gitea.
FetchTimeout time.Duration `yaml:"fetch_timeout"` // FetchTimeout specifies the timeout duration for fetching resources.
FetchInterval time.Duration `yaml:"fetch_interval"` // FetchInterval specifies the interval duration for fetching resources.
FetchIntervalMax time.Duration `yaml:"fetch_interval_max"` // FetchIntervalMax specifies the maximum backoff interval when idle.
WorkdirCleanupAge time.Duration `yaml:"workdir_cleanup_age"` // WorkdirCleanupAge removes stale bind-workdir task directories, orphaned host-mode scratch dirs and orphaned Kubernetes job resources older than this duration during idle cleanup.
IdleCleanupInterval time.Duration `yaml:"idle_cleanup_interval"` // IdleCleanupInterval runs the idle cleanup (stale directories, orphaned docker networks and volumes, orphaned job pods) periodically while the runner is idle. Set to 0 to disable cleanup cadence.
LogReportInterval time.Duration `yaml:"log_report_interval"` // LogReportInterval specifies the base interval for periodic log flush.
LogReportMaxLatency time.Duration `yaml:"log_report_max_latency"` // LogReportMaxLatency specifies the max time a log row can wait before being sent.
LogReportBatchSize int `yaml:"log_report_batch_size"` // LogReportBatchSize triggers immediate log flush when buffer reaches this size.
LogReportLevel string `yaml:"log_report_level"` // LogReportLevel is the lowest level of the runner's own messages sent to the job log between steps. Empty, the default, follows log.level.
StateReportInterval time.Duration `yaml:"state_report_interval"` // StateReportInterval specifies the interval for state reporting.
ReportCloseTimeout time.Duration `yaml:"report_close_timeout"` // ReportCloseTimeout caps each RPC attempt when flushing the final logs and task state at job completion, on a detached context so a server cancel can't block the acknowledgement.
Labels []string `yaml:"labels"` // Labels specify the labels of the runner. Labels are declared on each startup
GithubMirror string `yaml:"github_mirror"` // GithubMirror defines what mirrors should be used when using github
ActionShallowClone *bool `yaml:"action_shallow_clone"` // ActionShallowClone clones only the requested ref at depth 1 instead of every branch's full history, for reusable workflows and actions without an archive. It is a pointer to distinguish between false and not set; if not set, it defaults to true.
SetActEnv *bool `yaml:"set_act_env"` // SetActEnv controls whether the ACT=true environment variable is injected into jobs. It is a pointer to distinguish between false and not set; if not set, it defaults to true. Set it to false so workflows gated on `if: ${{ !env.ACT }}` behave like on GitHub.
PatchActions *bool `yaml:"patch_actions"` // PatchActions applies compatibility patches to the actions a job runs, so actions written for GitHub work against Gitea, see act/runner/patch_actions.go. It is a pointer to distinguish between false and not set; if not set, it defaults to true. Set it to false to run every action exactly as published, at the price of the artifact actions refusing.
AllocatePTY bool `yaml:"allocate_pty"` // AllocatePTY allocates a pseudo-TTY for each step's process. Default is false, matching GitHub's actions/runner. Enable only for jobs that need an interactive terminal; tools like docker build emit redrawing progress frames into the captured log when a TTY is present. Applies to both host and docker backends.
DefaultImage string `yaml:"default_image"` // DefaultImage is the image a job runs in when its runs-on matches none of the runner's labels. A runner without docker runs such a job on the host instead.
ToolCacheMode string `yaml:"tool_cache_mode"` // ToolCacheMode is what the runner mounts at RUNNER_TOOL_CACHE on both backends: ToolCacheModeNone or ToolCacheModeShared.
PostTaskScript string `yaml:"post_task_script"` // PostTaskScript is the path to an executable script run on the host after each task's cleanup completes. Empty disables the hook. On Windows use .exe/.bat/.cmd; PowerShell (.ps1) is not supported yet as the configured path.
PostTaskScriptTimeout time.Duration `yaml:"post_task_script_timeout"` // PostTaskScriptTimeout caps how long the post-task script may run. Default is 5m when post_task_script is set.
Hooks RunnerHooks `yaml:"hooks"` // Hooks are scripts run inside the job environment around the job's steps.
File string `yaml:"file"` // File specifies the file path for the runner.
Capacity int `yaml:"capacity"` // Capacity specifies the capacity of the runner.
Envs map[string]string `yaml:"envs"` // Envs stores environment variables for the runner.
EnvFile string `yaml:"env_file"` // EnvFile specifies the path to the file containing environment variables for the runner.
Timeout time.Duration `yaml:"timeout"` // Timeout specifies the duration for runner timeout.
ShutdownTimeout time.Duration `yaml:"shutdown_timeout"` // ShutdownTimeout specifies the duration to wait for running jobs to complete during a shutdown of the runner.
Insecure bool `yaml:"insecure"` // Insecure indicates whether the runner operates in an insecure mode.
ClientCertFile string `yaml:"client_cert_file"` // ClientCertFile is the PEM certificate presented to a Gitea instance that requires mutual TLS.
ClientKeyFile string `yaml:"client_key_file"` // ClientKeyFile is the PEM private key paired with ClientCertFile.
CAFile string `yaml:"ca_file"` // CAFile holds PEM CA certificates trusted for the Gitea instance besides the system's.
ExtraHeaders map[string]string `yaml:"extra_headers"` // ExtraHeaders adds HTTP headers to runner API requests to Gitea.
FetchTimeout time.Duration `yaml:"fetch_timeout"` // FetchTimeout specifies the timeout duration for fetching resources.
FetchInterval time.Duration `yaml:"fetch_interval"` // FetchInterval specifies the interval duration for fetching resources.
FetchIntervalMax time.Duration `yaml:"fetch_interval_max"` // FetchIntervalMax specifies the maximum backoff interval when idle.
WorkdirCleanupAge time.Duration `yaml:"workdir_cleanup_age"` // WorkdirCleanupAge removes stale bind-workdir task directories, orphaned host-mode scratch dirs and orphaned Kubernetes job resources older than this duration during idle cleanup.
IdleCleanupInterval time.Duration `yaml:"idle_cleanup_interval"` // IdleCleanupInterval runs the idle cleanup (stale directories, orphaned docker networks and volumes, orphaned job pods) periodically while the runner is idle. Set to 0 to disable cleanup cadence.
LogReportInterval time.Duration `yaml:"log_report_interval"` // LogReportInterval specifies the base interval for periodic log flush.
LogReportMaxLatency time.Duration `yaml:"log_report_max_latency"` // LogReportMaxLatency specifies the max time a log row can wait before being sent.
LogReportBatchSize int `yaml:"log_report_batch_size"` // LogReportBatchSize triggers immediate log flush when buffer reaches this size.
LogReportLevel string `yaml:"log_report_level"` // LogReportLevel is the lowest level of the runner's own messages sent to the job log between steps. Empty, the default, follows log.level.
StateReportInterval time.Duration `yaml:"state_report_interval"` // StateReportInterval specifies the interval for state reporting.
ReportCloseTimeout time.Duration `yaml:"report_close_timeout"` // ReportCloseTimeout caps each RPC attempt when flushing the final logs and task state at job completion, on a detached context so a server cancel can't block the acknowledgement.
Labels []string `yaml:"labels"` // Labels specify the labels of the runner. Labels are declared on each startup
GithubMirror string `yaml:"github_mirror"` // GithubMirror defines what mirrors should be used when using github
ActionReplacements []ActionReplacement `yaml:"action_replacements"` // ActionReplacements rewrite the `uses` of steps, see ReplaceUses.
ActionShallowClone *bool `yaml:"action_shallow_clone"` // ActionShallowClone clones only the requested ref at depth 1 instead of every branch's full history, for reusable workflows and actions without an archive. It is a pointer to distinguish between false and not set; if not set, it defaults to true.
SetActEnv *bool `yaml:"set_act_env"` // SetActEnv controls whether the ACT=true environment variable is injected into jobs. It is a pointer to distinguish between false and not set; if not set, it defaults to true. Set it to false so workflows gated on `if: ${{ !env.ACT }}` behave like on GitHub.
NodeDownload *bool `yaml:"node_download"` // NodeDownload sets whether to download Node.js for JavaScript actions and hashFiles(). Unset means true, false uses the node on PATH.
NodeVersion string `yaml:"node_version"` // NodeVersion is an exact Node.js version to download instead of the pinned one, checked against its published SHA-256.
PatchActions *bool `yaml:"patch_actions"` // PatchActions applies compatibility patches to the actions a job runs, so actions written for GitHub work against Gitea, see act/runner/patch_actions.go. It is a pointer to distinguish between false and not set; if not set, it defaults to true. Set it to false to run every action exactly as published, at the price of the artifact actions refusing.
AllocatePTY bool `yaml:"allocate_pty"` // AllocatePTY allocates a pseudo-TTY for each step's process. Default is false, matching GitHub's actions/runner. Enable only for jobs that need an interactive terminal; tools like docker build emit redrawing progress frames into the captured log when a TTY is present. Applies to both host and docker backends.
DefaultImage string `yaml:"default_image"` // DefaultImage is the image a job runs in when its runs-on matches none of the runner's labels. A runner without docker runs such a job on the host instead.
ToolCacheMode string `yaml:"tool_cache_mode"` // ToolCacheMode is what the runner mounts at RUNNER_TOOL_CACHE on both backends: ToolCacheModeNone or ToolCacheModeShared.
PostTaskScript string `yaml:"post_task_script"` // PostTaskScript is the path to an executable script run on the host after each task's cleanup completes. Empty disables the hook. On Windows use .exe/.bat/.cmd; PowerShell (.ps1) is not supported yet as the configured path.
PostTaskScriptTimeout time.Duration `yaml:"post_task_script_timeout"` // PostTaskScriptTimeout caps how long the post-task script may run. Default is 5m when post_task_script is set.
Hooks RunnerHooks `yaml:"hooks"` // Hooks are scripts run inside the job environment around the job's steps.
rootCAs *x509.CertPool // the system's and CAFile's, nil for the system's alone
}
@@ -173,6 +178,22 @@ func parseSize(value string) (Size, error) {
return Size(bytes), nil
}
// ActionReplacement replaces a step `uses` that Regex matches in full with Replacement.
type ActionReplacement struct {
Regex string `yaml:"regex"`
Replacement string `yaml:"replacement"`
regex *regexp.Regexp
}
// ReplaceUses applies ActionReplacements to a step `uses` in order, each to the result of the previous.
func (r *Runner) ReplaceUses(uses string) string {
for _, replacement := range r.ActionReplacements {
uses = replacement.regex.ReplaceAllString(uses, replacement.Replacement)
}
return uses
}
// Container represents the configuration for the container.
type Container struct {
Network string `yaml:"network"` // Network specifies the network for the container.
@@ -209,6 +230,7 @@ type ContainerNetworkCreateOptions struct {
// Host represents the configuration for the host.
type Host struct {
WorkdirParent string `yaml:"workdir_parent"` // WorkdirParent specifies the parent directory for the host's working directory.
StableWorkdir bool `yaml:"stable_workdir"` // StableWorkdir runs Linux host jobs at workspaces/<owner>/<repo>/<repo> in WorkdirParent, which needs CAP_SYS_ADMIN.
}
// Kubernetes configures the pods jobs run in.
@@ -327,6 +349,13 @@ func LoadDefault(file string) (*Config, error) {
return nil, err
}
}
for index := range cfg.Runner.ActionReplacements {
replacement := &cfg.Runner.ActionReplacements[index]
if _, err := regexp.Compile(replacement.Regex); err != nil {
return nil, fmt.Errorf("runner.action_replacements[%d].regex: %w", index, err)
}
replacement.regex = regexp.MustCompile(`^(?:` + replacement.Regex + `)$`)
}
for _, spec := range cfg.Container.Volumes {
if parsed, err := container.ParseVolume(spec); err != nil || parsed.Source == "" {
return nil, fmt.Errorf("container.volumes entry %q is not source:target[:options]", spec)
@@ -382,6 +411,9 @@ func LoadDefault(file string) (*Config, error) {
if cfg.Runner.ToolCacheMode == "" {
cfg.Runner.ToolCacheMode = ToolCacheModeNone
}
if cfg.Runner.NodeVersion != "" && !nodeVersionPattern.MatchString(cfg.Runner.NodeVersion) {
return nil, fmt.Errorf("invalid runner.node_version %q: must be an exact version like 24.22.3", cfg.Runner.NodeVersion)
}
if !slices.Contains(ToolCacheModes, cfg.Runner.ToolCacheMode) {
return nil, fmt.Errorf("invalid runner.tool_cache_mode %q: must be one of %q", cfg.Runner.ToolCacheMode, ToolCacheModes)
}

View File

@@ -184,6 +184,17 @@ func TestLoadDefault_ToolCacheMode(t *testing.T) {
assert.Contains(t, err.Error(), "tool_cache_mode")
}
func TestLoadDefault_NodeVersion(t *testing.T) {
path := write(t, "runner:\n node_version: 24.21.0\n")
cfg, err := LoadDefault(path)
require.NoError(t, err)
assert.Equal(t, "24.21.0", cfg.Runner.NodeVersion)
require.NoError(t, os.WriteFile(path, []byte("runner:\n node_version: \"24\"\n"), 0o600))
_, err = LoadDefault(path)
require.ErrorContains(t, err, "node_version")
}
func TestLoadDefault_KubernetesTransferMode(t *testing.T) {
cfg, err := LoadDefault(write(t, "kubernetes:\n transfer:\n host: 10.0.0.5\n"))
require.NoError(t, err)
@@ -202,6 +213,28 @@ func TestLoadDefault_RejectsInvalidLogReportLevel(t *testing.T) {
require.ErrorContains(t, err, "runner.log_report_level")
}
func TestLoadDefault_ActionReplacementsMatchWholeUsesAndChainInOrder(t *testing.T) {
cfg, err := LoadDefault(write(t, `
runner:
action_replacements:
- regex: 'actions/checkout@v4'
replacement: actions/checkout@v6
- regex: 'actions/(.+)'
replacement: https://mirror.example/actions/${1}
`))
require.NoError(t, err)
for uses, want := range map[string]string{
"actions/checkout@v4": "https://mirror.example/actions/checkout@v6",
"actions/checkout@v4.1.0": "https://mirror.example/actions/checkout@v4.1.0",
"my/actions/checkout@v4": "my/actions/checkout@v4",
} {
assert.Equal(t, want, cfg.Runner.ReplaceUses(uses), uses)
}
_, err = LoadDefault(write(t, "runner:\n action_replacements:\n - regex: 'checkout)|(?:x'\n"))
require.ErrorContains(t, err, "runner.action_replacements[0].regex")
}
func TestLoadDefault_LoadsExtraHeaders(t *testing.T) {
path := write(t, "runner:\n extra_headers:\n X-Proxy-Token: proxy-token\n")
cfg, err := LoadDefault(path)

View File

@@ -6,6 +6,7 @@ package config
import (
"encoding/json/jsontext"
"encoding/json/v2"
"errors"
"os"
)
@@ -42,12 +43,15 @@ func LoadRegistration(file string) (*Registration, error) {
}
func SaveRegistration(file string, reg *Registration) error {
f, err := os.Create(file)
f, err := os.OpenFile(file, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600)
if err != nil {
return err
}
defer f.Close()
if err := f.Chmod(0o600); err != nil && !errors.Is(err, os.ErrPermission) {
return err
}
reg.Warning = registrationWarning
if err := json.MarshalWrite(f, reg, jsontext.WithIndent(" ")); err != nil {

View File

@@ -6,6 +6,7 @@ package config
import (
"os"
"path/filepath"
"runtime"
"testing"
"github.com/stretchr/testify/require"
@@ -25,6 +26,14 @@ func TestSaveAndLoadRegistration(t *testing.T) {
}
require.NoError(t, SaveRegistration(file, reg))
require.NoError(t, os.Chmod(file, 0o644))
reg.Name = "new"
require.NoError(t, SaveRegistration(file, reg))
if runtime.GOOS != "windows" {
info, err := os.Stat(file)
require.NoError(t, err)
require.Equal(t, os.FileMode(0o600), info.Mode().Perm())
}
// SaveRegistration stamps the warning onto the in-memory struct
require.Equal(t, registrationWarning, reg.Warning)

View File

@@ -42,10 +42,8 @@ func TestJobLog_MirrorsUploadedRows(t *testing.T) {
require.NoError(t, err)
cfg.Log.Job.Dir = t.TempDir()
ctx, cancel := context.WithCancel(t.Context())
t.Cleanup(cancel)
task := &runnerv1.Task{Id: 41, Context: &structpb.Struct{}, Secrets: map[string]string{"TOKEN": "s3cret-value"}}
reporter := NewReporter(ctx, cancel, client, task, cfg)
reporter := NewReporter(t.Context(), nil, client, task, cfg)
require.NotNil(t, reporter.jobLog)
reporter.RunDaemon()
reporter.ResetSteps(newTestSteps(1))
@@ -60,7 +58,7 @@ func TestJobLog_MirrorsUploadedRows(t *testing.T) {
fire("the token is s3cret-value")
reporter.AddMask("dyn4mic-value")
fire("and dyn4mic-value too")
require.NoError(t, reporter.Close(""))
require.NoError(t, reporter.Close(nil))
job := readJobLog(t, reporter.jobLog)
assert.Contains(t, job, "the token is ***")

View File

@@ -22,6 +22,7 @@ import (
"connectrpc.com/connect/v2"
"gitea.dev/actionslib/pkg/model"
"gitea.dev/actionslib/pkg/protocol"
runnerv1 "gitea.dev/actionslib/runner/v1"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/timestamppb"
@@ -30,12 +31,6 @@ import (
// errOutputsNotSent travels the same return path as transport failures but is not one.
var errOutputsNotSent = errors.New("there are still outputs that have not been sent")
// Size limits for the outputs reported to the server.
const (
maxOutputKeyLen = 255
maxOutputValueLen = 1024 * 1024 // 1 MiB
)
// jobOutput is a job output on its way to the server, sent once the server has acknowledged it.
type jobOutput struct {
value string
@@ -44,7 +39,7 @@ type jobOutput struct {
type Reporter struct {
ctx context.Context
cancel context.CancelFunc
cancel context.CancelCauseFunc
closed bool
client client.Client
@@ -68,10 +63,8 @@ type Reporter struct {
currentReportedStep *runnerv1.StepState
stepModels []*model.Step
// reportFailing keeps an outage to one log line at each end.
reportFailing map[string]bool
// serverResult is what the server decided, e.g. the zombie reaper failing
// the task. Guarded by stateMu.
serverResult runnerv1.Result
reportFailing map[string]bool
serverEndErr error
stateMu sync.RWMutex
outputsMu sync.Mutex
outputs map[string]jobOutput
@@ -102,7 +95,7 @@ type Reporter struct {
// extraMasks are values known before the job starts that are not among its secrets, such as
// the password in the runner's proxy URL.
func NewReporter(ctx context.Context, cancel context.CancelFunc, client client.Client, task *runnerv1.Task, cfg *config.Config, extraMasks ...string) *Reporter {
func NewReporter(ctx context.Context, cancel context.CancelCauseFunc, client client.Client, task *runnerv1.Task, cfg *config.Config, extraMasks ...string) *Reporter {
var oldnew []string
for _, v := range extraMasks {
oldnew = runner.AppendSecretMasker(oldnew, v)
@@ -174,7 +167,7 @@ func (r *Reporter) ResetSteps(steps []*model.Step) {
setup.LogLength = int64(r.logOffset + len(r.logRows)) // the runner's own lines logged before the job was parsed
r.currentReportedStep = setup
for i, step := range steps {
r.addReportedStep(len(r.state.ReportedSteps), runnerv1.StepStage_STEP_STAGE_MAIN, i, r.mask(stepDisplayName(step, "")))
r.addReportedStep(len(r.state.ReportedSteps), runnerv1.StepStage_STEP_STAGE_MAIN, i, r.mask(model.StepDisplayName(step, "")))
}
r.addReportedStep(len(r.state.ReportedSteps), runnerv1.StepStage_STEP_STAGE_CLEANUP, 0, "Complete job")
}
@@ -184,16 +177,6 @@ type reportedStepKey struct {
number int
}
// stepDisplayName names a workflow step like Gitea and GitHub do, prefixing an unnamed one with "Run".
// evaluated is step.String() with its expressions evaluated, empty while the step has not run yet.
func stepDisplayName(step *model.Step, evaluated string) string {
if step.Name != "" {
return cmp.Or(evaluated, step.Name)
}
first, _, _ := strings.Cut(strings.TrimSpace(cmp.Or(evaluated, step.String())), "\n")
return "Run " + cmp.Or(strings.TrimSpace(first), step.String())
}
// addReportedStep inserts a step at pos of the reported steps. Caller holds stateMu.
func (r *Reporter) addReportedStep(pos int, stage runnerv1.StepStage, number int, name string) *runnerv1.StepState {
step := &runnerv1.StepState{Name: name, Stage: stage, Number: int64(number)}
@@ -233,7 +216,7 @@ func (r *Reporter) reportedStepOf(entry logging.Record) (*runnerv1.StepState, bo
main := r.reportedSteps[reportedStepKey{runnerv1.StepStage_STEP_STAGE_MAIN, number}]
if evaluated, _ := recordAttr[string](entry, "step"); evaluated != "" {
// evaluated as GitHub shows it, and masked as an expression can name a secret
main.Name = r.mask(stepDisplayName(r.stepModels[number], evaluated))
main.Name = r.mask(model.StepDisplayName(r.stepModels[number], evaluated))
}
if step, ok := r.reportedSteps[key]; ok {
return step, true
@@ -332,15 +315,19 @@ func (h *reporterHandler) WithAttrs(attrs []logging.Attr) logging.Handler {
func (r *Reporter) appendLogRow(row *runnerv1.LogRow) {
row.Content = r.mask(row.Content)
if step := r.currentReportedStep; step != nil {
if step.LogLength == 0 {
step.LogIndex = int64(r.logOffset + len(r.logRows))
}
step.LogLength++
r.extendStepLog(step)
}
r.logRows = append(r.logRows, row)
r.jobLog.write(row.Time.AsTime(), row.Content)
}
func (r *Reporter) extendStepLog(step *runnerv1.StepState) {
if step.LogLength == 0 {
step.LogIndex = int64(r.logOffset + len(r.logRows))
}
step.LogLength++
}
func attrArgs(attrs []logging.Attr) []any {
args := make([]any, len(attrs))
for i, a := range attrs {
@@ -420,7 +407,9 @@ func (r *Reporter) Handle(_ context.Context, entry logging.Record) error {
if v, ok := entry.Attr("jobResult"); ok {
if jobResult, ok := parseResult(v); ok {
// We need to ensure log upload before this upload
r.state.Result = jobResult
if r.serverEndErr == nil {
r.state.Result = jobResult
}
r.state.StoppedAt = timestamppb.New(timestamp)
for _, s := range r.state.Steps {
if s.Result == runnerv1.Result_RESULT_UNSPECIFIED {
@@ -464,10 +453,7 @@ func (r *Reporter) Handle(_ context.Context, entry logging.Record) error {
v, hasRawOutput := entry.Attr("raw_output")
rawOutput, _ := v.(bool)
if entry.Level >= logging.LevelError || rawOutput {
if step.LogLength == 0 {
step.LogIndex = int64(r.logOffset + len(r.logRows))
}
step.LogLength++
r.extendStepLog(step)
r.appendLogRow(logRow(entry))
} else if !hasRawOutput && r.shouldAppendLogRow(entry) {
r.appendLogRow(logRow(entry))
@@ -624,19 +610,18 @@ func (r *Reporter) SetOutputs(outputs map[string]string) {
r.outputs = map[string]jobOutput{}
}
for k, v := range outputs {
if l := len(k); l > maxOutputKeyLen {
logging.Warnf("ignore output %q because the key is too long: %d > %d", k, l, maxOutputKeyLen)
r.logf("ignore output %q because the key is too long: %d > %d", k, l, maxOutputKeyLen)
continue
var reason string
switch {
case len(k) > protocol.MaxOutputKeyLength:
reason = fmt.Sprintf("the key is too long: %d > %d", len(k), protocol.MaxOutputKeyLength)
case len(v) > protocol.MaxOutputValueLength:
reason = fmt.Sprintf("the value is too long: %d > %d", len(v), protocol.MaxOutputValueLength)
case r.logReplacer.Replace(v) != v: // GitHub skips an output that may carry a secret rather than masking it
reason = "it may contain a secret"
}
if l := len(v); l > maxOutputValueLen {
logging.Warnf("ignore output %q because the value is too long: %d > %d", k, l, maxOutputValueLen)
r.logf("ignore output %q because the value is too long: %d > %d", k, l, maxOutputValueLen)
continue
}
if r.logReplacer.Replace(v) != v { // GitHub skips an output that may carry a secret rather than masking it
logging.Warnf("ignore output %q because it may contain a secret", k)
r.logf("ignore output %q because it may contain a secret", k)
if reason != "" {
logging.Warnf("ignore output %q because %s", k, reason)
r.logf("ignore output %q because %s", k, reason)
continue
}
if _, ok := r.outputs[k]; !ok {
@@ -645,34 +630,32 @@ func (r *Reporter) SetOutputs(outputs map[string]string) {
}
}
func (r *Reporter) Close(lastWords string) error {
func (r *Reporter) Close(runErr error) error {
defer deregisterGlobalMasks(r) // deferred so a panic below cannot strand this task's masks
r.stateMu.Lock()
r.closed = true
var lastWords string
if r.state.Result == runnerv1.Result_RESULT_UNSPECIFIED {
// No result of its own, so say why it stopped.
result, words := runnerv1.Result_RESULT_FAILURE, "Early termination"
switch {
case r.serverResult != runnerv1.Result_RESULT_UNSPECIFIED:
result, words = r.serverResult, "Ended by the server"
case errors.Is(r.ctx.Err(), context.Canceled):
result, words = runnerv1.Result_RESULT_CANCELLED, "Cancelled"
}
if lastWords == "" {
lastWords = words
if r.ctx.Err() == context.Canceled {
r.state.Result = runnerv1.Result_RESULT_CANCELLED
lastWords = "Cancelled"
} else {
r.state.Result = runnerv1.Result_RESULT_FAILURE
lastWords = "Early termination"
}
}
if r.state.StoppedAt == nil {
for _, v := range r.state.Steps {
if v.Result == runnerv1.Result_RESULT_UNSPECIFIED {
v.Result = runnerv1.Result_RESULT_CANCELLED
}
}
r.state.Result = result
r.appendLogRow(&runnerv1.LogRow{
Time: timestamppb.Now(),
Content: lastWords,
})
r.state.StoppedAt = timestamppb.Now()
} else if lastWords != "" {
}
if runErr != nil && (r.serverEndErr == nil || runErr != context.Canceled && !errors.Is(runErr, r.serverEndErr)) {
lastWords = cmp.Or(runErr.Error(), lastWords)
}
if lastWords != "" {
r.appendLogRow(&runnerv1.LogRow{
Time: timestamppb.Now(),
Content: lastWords,
@@ -888,11 +871,18 @@ func (r *Reporter) ReportState(reportResult bool) error {
// A terminal result means the server is done with this task; keep running and
// the job holds a capacity slot until runner.timeout.
if state := resp.State; state != nil && state.Result != runnerv1.Result_RESULT_UNSPECIFIED {
if result := resp.GetState().GetResult(); result != runnerv1.Result_RESULT_UNSPECIFIED {
r.stateMu.Lock()
r.serverResult = state.Result
if !r.closed && r.serverEndErr == nil {
r.serverEndErr = errors.New("Ended by the server: " + metrics.ResultToStatusLabel(result))
r.state.Result = result
if step := r.currentReportedStep; step != nil && step.Stage == runnerv1.StepStage_STEP_STAGE_MAIN && step.StoppedAt == nil {
r.extendStepLog(r.state.Steps[step.Number])
}
r.appendLogRow(&runnerv1.LogRow{Time: timestamppb.Now(), Content: r.serverEndErr.Error()})
r.cancel(r.serverEndErr)
}
r.stateMu.Unlock()
r.cancel()
}
if len(noSent) > 0 {
return fmt.Errorf("%w: %v", errOutputsNotSent, noSent)
@@ -919,23 +909,12 @@ func (r *Reporter) shouldAppendLogRow(entry logging.Record) bool {
return !r.duringSteps() && entry.Level >= r.logReportLevel
}
var stringToResult = map[string]runnerv1.Result{
"success": runnerv1.Result_RESULT_SUCCESS,
"failure": runnerv1.Result_RESULT_FAILURE,
"skipped": runnerv1.Result_RESULT_SKIPPED,
"cancelled": runnerv1.Result_RESULT_CANCELLED,
}
func parseResult(result any) (runnerv1.Result, bool) {
str := ""
if v, ok := result.(string); ok { // for jobResult
str = v
} else if v, ok := result.(fmt.Stringer); ok { // for stepResult
str = v.String()
if stringer, ok := result.(fmt.Stringer); ok {
result = stringer.String()
}
ret, ok := stringToResult[str]
return ret, ok
conclusion, _ := result.(string)
return runnerv1.ParseConclusion(conclusion)
}
func logRow(entry logging.Record) *runnerv1.LogRow {

View File

@@ -27,6 +27,7 @@ import (
"gitea.com/gitea/runner/internal/pkg/metrics"
"gitea.dev/actionslib/pkg/model"
"gitea.dev/actionslib/pkg/protocol"
runnerv1 "gitea.dev/actionslib/runner/v1"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
@@ -72,7 +73,7 @@ func TestReporter_LogLevelFiltering(t *testing.T) {
assert.True(t, reporter.shouldAppendLogRow(logging.Record{Level: logging.LevelWarn}))
reporter.RunDaemon()
defer func() {
require.NoError(t, reporter.Close(""))
require.NoError(t, reporter.Close(nil))
}()
reporter.ResetSteps(newTestSteps(2))
@@ -172,18 +173,13 @@ func TestReporter_RunDaemonClose_Race(t *testing.T) {
},
)
ctx, cancel := context.WithCancel(t.Context())
cfg, _ := config.LoadDefault("")
reporter := NewReporter(ctx, cancel, client, &runnerv1.Task{
Context: &structpb.Struct{},
}, cfg)
reporter := newTestReporter(t, client, cfg)
reporter.ResetSteps(newTestSteps(1))
reporter.RunDaemon()
require.NoError(t, reporter.Close(""))
cancel()
require.NoError(t, reporter.Close(nil))
}
func TestReporter_LogFlush(t *testing.T) {
@@ -215,7 +211,7 @@ func TestReporter_LogFlush(t *testing.T) {
reporter := newTestReporter(t, client, cfg)
reporter.ResetSteps(newTestSteps(1))
reporter.RunDaemon()
defer func() { require.NoError(t, reporter.Close("")) }()
defer func() { require.NoError(t, reporter.Close(nil)) }()
for _, message := range tc.messages {
require.NoError(t, fire(reporter, logEntry{
@@ -340,7 +336,7 @@ func TestReporter_StateNotifyFlush(t *testing.T) {
reporter.ResetSteps(newTestSteps(1))
reporter.RunDaemon()
defer func() {
_ = reporter.Close("")
_ = reporter.Close(nil)
}()
require.NoError(t, fire(reporter, logEntry{
@@ -394,7 +390,7 @@ func TestReporter_CloseFinalizesLogWithoutRows(t *testing.T) {
reporter.state.StoppedAt = timestamppb.Now()
reporter.stateMu.Unlock()
require.NoError(t, reporter.Close(""))
require.NoError(t, reporter.Close(nil))
require.Equal(t, int64(1), noMoreCalls.Load(), "Close must send exactly one UpdateLog with NoMore=true")
final := lastReq.Load()
@@ -436,65 +432,36 @@ func TestReporter_StateHeartbeat(t *testing.T) {
}
func TestReporter_ServerCancelStillFlushesFinal(t *testing.T) {
var (
updateTaskCalls atomic.Int64
finalLogNoMoreSeen atomic.Bool
finalTaskStateSeen atomic.Bool
)
const message = "Ended by the server: failure"
client := mocks.NewClient(t)
client.On("UpdateLog", mock.Anything, mock.Anything).Return(
func(_ context.Context, req *runnerv1.UpdateLogRequest) (*runnerv1.UpdateLogResponse, error) {
if req.NoMore {
finalLogNoMoreSeen.Store(true)
}
return &runnerv1.UpdateLogResponse{
AckIndex: req.Index + int64(len(req.Rows)),
}, nil
},
)
client.On("UpdateTask", mock.Anything, mock.Anything).Return(
func(_ context.Context, req *runnerv1.UpdateTaskRequest) (*runnerv1.UpdateTaskResponse, error) {
n := updateTaskCalls.Add(1)
if n == 1 {
return &runnerv1.UpdateTaskResponse{
State: &runnerv1.TaskState{
Result: runnerv1.Result_RESULT_CANCELLED,
},
}, nil
}
if req.State != nil && req.State.Result != runnerv1.Result_RESULT_UNSPECIFIED {
finalTaskStateSeen.Store(true)
}
return &runnerv1.UpdateTaskResponse{}, nil
},
)
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
cfg, _ := config.LoadDefault("")
reporter := NewReporter(ctx, cancel, client, &runnerv1.Task{Context: &structpb.Struct{}}, cfg)
reporter.ResetSteps(newTestSteps(1))
reporter.stateMu.Lock()
reporter.stateChanged = true
reporter.stateMu.Unlock()
require.NoError(t, reporter.ReportState(false))
require.Equal(t, int64(1), updateTaskCalls.Load())
select {
case <-ctx.Done():
case <-time.After(time.Second):
t.Fatal("expected r.ctx to be cancelled after server returned RESULT_CANCELLED")
}
var lastState *runnerv1.TaskState
client.On("UpdateTask", mock.Anything, mock.Anything).Return(func(ctx context.Context, req *runnerv1.UpdateTaskRequest) (*runnerv1.UpdateTaskResponse, error) {
require.NoError(t, ctx.Err())
lastState = req.State
return &runnerv1.UpdateTaskResponse{State: &runnerv1.TaskState{Result: runnerv1.Result_RESULT_FAILURE}}, nil
})
client.On("UpdateLog", mock.Anything, mock.Anything).Return(func(ctx context.Context, req *runnerv1.UpdateLogRequest) (*runnerv1.UpdateLogResponse, error) {
require.NoError(t, ctx.Err())
require.True(t, req.NoMore)
require.Len(t, req.Rows, 3)
assert.Equal(t, []string{"running", message, "stopped"}, []string{req.Rows[0].Content, req.Rows[1].Content, req.Rows[2].Content})
return &runnerv1.UpdateLogResponse{AckIndex: int64(len(req.Rows))}, nil
}).Once()
reporter := newTestReporter(t, client, &config.Config{Runner: config.Runner{LogReportLevel: "info"}})
close(reporter.daemon)
require.NoError(t, reporter.Close("cancelled"))
assert.True(t, finalLogNoMoreSeen.Load(), "Close() must send a final UpdateLog{NoMore:true} even after server-side cancellation")
assert.True(t, finalTaskStateSeen.Load(), "Close() must send a final UpdateTask with the populated final state even after server-side cancellation")
reporter.ResetSteps(newTestSteps(1))
step := map[string]any{"stage": runner.StageMain, "stepNumber": 0, "raw_output": true}
require.NoError(t, fire(reporter, logEntry{Message: "running", Data: step}))
require.NoError(t, reporter.ReportState(false))
require.EqualError(t, context.Cause(reporter.ctx), message)
require.NoError(t, fire(reporter, logEntry{Message: "stopped", Data: step}))
require.NoError(t, fire(reporter, logEntry{Level: logging.LevelDebug, Data: map[string]any{"jobResult": "cancelled"}}))
assert.Equal(t, runnerv1.Result_RESULT_FAILURE, reporter.Result())
require.NoError(t, reporter.ReportState(false))
require.NoError(t, reporter.Close(fmt.Errorf("run: %w", context.Cause(reporter.ctx))))
assert.Equal(t, runnerv1.Result_RESULT_FAILURE, lastState.Result)
assert.EqualValues(t, 3, lastState.Steps[0].LogLength)
}
func TestReporter_CloseReportsCancelledOnCanceledCtx(t *testing.T) {
@@ -522,16 +489,15 @@ func TestReporter_CloseReportsCancelledOnCanceledCtx(t *testing.T) {
},
)
ctx, cancel := context.WithCancel(t.Context())
cfg, _ := config.LoadDefault("")
reporter := NewReporter(ctx, cancel, client, &runnerv1.Task{Context: &structpb.Struct{}}, cfg)
reporter := newTestReporter(t, client, cfg)
reporter.ResetSteps(newTestSteps(1))
cancel()
reporter.cancel(nil)
close(reporter.daemon)
require.NoError(t, reporter.Close(""))
require.NoError(t, reporter.Close(nil))
got := finalState.Load()
require.NotNil(t, got, "Close() must send a final UpdateTask")
@@ -607,7 +573,7 @@ func TestReporter_StopHeartbeats(t *testing.T) {
assert.Equal(t, beforeStop, updateTaskCalls.Load(),
"UpdateTask must not be called after StopHeartbeats")
require.NoError(t, reporter.Close(""))
require.NoError(t, reporter.Close(nil))
assert.Greater(t, updateTaskCalls.Load(), beforeStop,
"Close() must still send a final UpdateTask after StopHeartbeats")
})
@@ -646,12 +612,12 @@ func TestReporter_SetOutputs(t *testing.T) {
r.SetOutputs(map[string]string{"foo": "baz"})
assert.Equal(t, "bar", r.outputs["foo"].value)
longKey := strings.Repeat("k", maxOutputKeyLen+1)
longKey := strings.Repeat("k", protocol.MaxOutputKeyLength+1)
r.SetOutputs(map[string]string{longKey: "v"})
_, ok = r.outputs[longKey]
assert.False(t, ok)
longValue := strings.Repeat("v", maxOutputValueLen+1)
longValue := strings.Repeat("v", protocol.MaxOutputValueLength+1)
r.SetOutputs(map[string]string{"big": longValue})
_, ok = r.outputs["big"]
assert.False(t, ok)
@@ -665,10 +631,10 @@ func TestReporter_SetOutputs(t *testing.T) {
require.True(t, ok)
assert.Equal(t, "caf\xff", got.value)
r.SetOutputs(map[string]string{"atlimit": longValue[:maxOutputValueLen]})
r.SetOutputs(map[string]string{"atlimit": longValue[:protocol.MaxOutputValueLength]})
got, ok = r.outputs["atlimit"]
require.True(t, ok)
assert.Len(t, got.value, maxOutputValueLen)
assert.Len(t, got.value, protocol.MaxOutputValueLength)
}
func TestReporter_DebugSettingsAreNotMasked(t *testing.T) {
@@ -733,8 +699,7 @@ func TestReporter_ParseResult(t *testing.T) {
wantOk bool
}{
{"job result string", "success", runnerv1.Result_RESULT_SUCCESS, true},
{"failure string", "failure", runnerv1.Result_RESULT_FAILURE, true},
{"step result stringer", runnerv1.Result_RESULT_SKIPPED, runnerv1.Result_RESULT_UNSPECIFIED, false},
{"step result stringer", model.StepStatusSkipped, runnerv1.Result_RESULT_SKIPPED, true},
{"unknown string", "bogus", runnerv1.Result_RESULT_UNSPECIFIED, false},
{"unsupported type", 123, runnerv1.Result_RESULT_UNSPECIFIED, false},
}
@@ -840,39 +805,10 @@ func TestReporter_CloseWithStuckDaemon(t *testing.T) {
case <-time.After(5 * time.Second):
t.Fatal("daemon never reached UpdateLog")
}
require.NoError(t, reporter.Close(""))
require.NoError(t, reporter.Close(nil))
})
}
func TestReporter_ServerFailureResultIsReportedAsFailure(t *testing.T) {
var lastState *runnerv1.TaskState
client := mocks.NewClient(t)
client.On("UpdateTask", mock.Anything, mock.Anything).Return(func(_ context.Context, req *runnerv1.UpdateTaskRequest) (*runnerv1.UpdateTaskResponse, error) {
lastState = req.State
return &runnerv1.UpdateTaskResponse{
State: &runnerv1.TaskState{Result: runnerv1.Result_RESULT_FAILURE},
}, nil
})
client.On("UpdateLog", mock.Anything, mock.Anything).Return(func(_ context.Context, req *runnerv1.UpdateLogRequest) (*runnerv1.UpdateLogResponse, error) {
return &runnerv1.UpdateLogResponse{
AckIndex: req.Index + int64(len(req.Rows)),
}, nil
}).Maybe()
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
cfg, _ := config.LoadDefault("")
reporter := NewReporter(ctx, cancel, client, &runnerv1.Task{Context: &structpb.Struct{}}, cfg)
close(reporter.daemon)
require.NoError(t, reporter.ReportState(false))
require.ErrorIs(t, ctx.Err(), context.Canceled)
require.NoError(t, reporter.Close(""))
require.NotNil(t, lastState)
assert.Equal(t, runnerv1.Result_RESULT_FAILURE, lastState.Result)
}
func TestReporter_NoteReport(t *testing.T) {
hook := logtest.SetDefault(t)
@@ -904,25 +840,19 @@ func TestReporter_CloseMasksLastWords(t *testing.T) {
}, nil
},
)
client.On("UpdateTask", mock.Anything, mock.Anything).Return(
func(_ context.Context, _ *runnerv1.UpdateTaskRequest) (*runnerv1.UpdateTaskResponse, error) {
return &runnerv1.UpdateTaskResponse{}, nil
},
)
client.On("UpdateTask", mock.Anything, mock.Anything).Return(&runnerv1.UpdateTaskResponse{}, nil)
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
const idToken = "id-token-request-secret"
taskCtx, err := structpb.NewStruct(map[string]any{"actions_id_token_request_token": idToken})
require.NoError(t, err)
cfg, _ := config.LoadDefault("")
reporter := NewReporter(ctx, cancel, client, &runnerv1.Task{
reporter := NewReporter(t.Context(), nil, client, &runnerv1.Task{
Context: taskCtx,
Secrets: map[string]string{"TOKEN": secret},
}, cfg)
close(reporter.daemon)
require.NoError(t, reporter.Close("could not get job matrix: "+secret+" "+idToken))
require.NoError(t, reporter.Close(fmt.Errorf("could not get job matrix: %s %s", secret, idToken)))
require.Len(t, rows, 1)
assert.Equal(t, "could not get job matrix: *** ***", rows[0].Content)
@@ -983,7 +913,7 @@ func TestReporter_StepRangeCoversAckedRows(t *testing.T) {
reporter.ResetSteps(newTestSteps(1))
reporter.RunDaemon()
defer func() {
_ = reporter.Close("")
_ = reporter.Close(nil)
}()
stepData := map[string]any{"stage": "Main", "stepNumber": 0, "raw_output": true}
@@ -1027,8 +957,8 @@ func TestReporter_FlushWithoutAckedRowsSkipsState(t *testing.T) {
func newTestReporter(t *testing.T, client *mocks.Client, cfg *config.Config) *Reporter {
t.Helper()
ctx, cancel := context.WithCancel(t.Context())
t.Cleanup(cancel)
ctx, cancel := context.WithCancelCause(t.Context())
t.Cleanup(func() { cancel(nil) })
return NewReporter(ctx, cancel, client, &runnerv1.Task{Context: &structpb.Struct{}}, cfg)
}
@@ -1041,14 +971,14 @@ func newTestSteps(n int) []*model.Step {
}
func TestReporter_ReportedSteps(t *testing.T) {
newReporter := func(t *testing.T, steps []*model.Step) (*Reporter, context.CancelFunc) {
newReporter := func(t *testing.T, steps []*model.Step) (*Reporter, context.CancelCauseFunc) {
client := mocks.NewClient(t)
client.On("UpdateLog", mock.Anything, mock.Anything).Maybe().Return(func(_ context.Context, req *runnerv1.UpdateLogRequest) (*runnerv1.UpdateLogResponse, error) {
return &runnerv1.UpdateLogResponse{AckIndex: req.Index + int64(len(req.Rows))}, nil
})
client.On("UpdateTask", mock.Anything, mock.Anything).Maybe().Return(&runnerv1.UpdateTaskResponse{}, nil)
cfg, _ := config.LoadDefault("")
ctx, cancel := context.WithCancel(t.Context())
ctx, cancel := context.WithCancelCause(t.Context())
reporter := NewReporter(ctx, cancel, client, &runnerv1.Task{Context: &structpb.Struct{}, Secrets: map[string]string{"TOKEN": "s3cr3t"}}, cfg)
reporter.RunDaemon()
reporter.Logf("runner version")
@@ -1123,7 +1053,7 @@ func TestReporter_ReportedSteps(t *testing.T) {
assert.Equal(t, want, reportedOf(t, reporter))
send(t, reporter, logging.LevelInfo, "Removing images", map[string]any{"stage": runner.StageComplete})
require.NoError(t, reporter.Close(""))
require.NoError(t, reporter.Close(nil))
want[5].result, want[5].logLen = success, 3
assert.Equal(t, want, reportedOf(t, reporter))
@@ -1156,8 +1086,8 @@ func TestReporter_ReportedSteps(t *testing.T) {
send(t, reporter, logging.LevelInfo, "main output", map[string]any{"stage": runner.StageMain, "stepNumber": 1, "raw_output": true})
send(t, reporter, logging.LevelInfo, "Run Post echo 0", started(runner.StagePost, 0))
send(t, reporter, logging.LevelInfo, "Failure - Post echo 0", result(runner.StagePost, 0, model.StepStatusFailure))
cancel()
require.NoError(t, reporter.Close(""))
cancel(nil)
require.NoError(t, reporter.Close(nil))
results := make(map[string]runnerv1.Result)
for _, v := range reportedOf(t, reporter) {
@@ -1184,7 +1114,7 @@ func TestReporter_ReportedSteps(t *testing.T) {
reporter, _ := newReporter(t, newTestSteps(1))
reporter.Logf("workflow prepared")
send(t, reporter, logging.LevelInfo, "Job failed", map[string]any{"jobResult": model.StepStatusFailure})
require.NoError(t, reporter.Close(""))
require.NoError(t, reporter.Close(nil))
assert.Equal(t, []reported{
{setup, 0, "Set up job", failure, 0, 3},
@@ -1199,7 +1129,7 @@ func TestReporter_ReportedSteps(t *testing.T) {
send(t, reporter, logging.LevelError, "##[error]unable to clone 'invalid-owner/invalid-action'", nil)
send(t, reporter, logging.LevelInfo, "Cleaning up container", map[string]any{"stage": runner.StageComplete})
send(t, reporter, logging.LevelInfo, "Job failed", map[string]any{"stage": runner.StageComplete, "jobResult": model.StepStatusFailure})
require.NoError(t, reporter.Close(""))
require.NoError(t, reporter.Close(nil))
got := reportedOf(t, reporter)
assert.Equal(t, []runnerv1.Result{failure, skipped, success}, []runnerv1.Result{got[0].result, got[1].result, got[2].result})
@@ -1209,7 +1139,7 @@ func TestReporter_ReportedSteps(t *testing.T) {
reporter, _ := newReporter(t, newTestSteps(1))
send(t, reporter, logging.LevelError, "##[error]job completed hook failed", map[string]any{"stage": runner.StageComplete})
send(t, reporter, logging.LevelInfo, "Job failed", map[string]any{"stage": runner.StageComplete, "jobResult": model.StepStatusFailure})
require.NoError(t, reporter.Close(""))
require.NoError(t, reporter.Close(nil))
step := reporter.state.ReportedSteps[len(reporter.state.ReportedSteps)-1]
assert.Equal(t, failure, step.Result)
@@ -1220,7 +1150,7 @@ func TestReporter_ReportedSteps(t *testing.T) {
t.Run("step not reached in a succeeding job", func(t *testing.T) {
reporter, _ := newReporter(t, newTestSteps(1))
send(t, reporter, logging.LevelInfo, "Job succeeded", map[string]any{"stage": runner.StageComplete, "jobResult": model.StepStatusSuccess})
require.NoError(t, reporter.Close(""))
require.NoError(t, reporter.Close(nil))
assert.Equal(t, skipped, reportedOf(t, reporter)[1].result)
})
@@ -1231,7 +1161,7 @@ func TestReporter_ReportedSteps(t *testing.T) {
reporter, _ := newReporter(t, steps)
send(t, reporter, logging.LevelDebug, "Run Main", map[string]any{"stage": runner.StageMain, "stepNumber": 0, "step": "echo linux\necho more"})
send(t, reporter, logging.LevelDebug, "Run Main", map[string]any{"stage": runner.StageMain, "stepNumber": 1, "step": "Deploy with s3cr3t"})
require.NoError(t, reporter.Close(""))
require.NoError(t, reporter.Close(nil))
names := []string{}
for _, v := range reportedOf(t, reporter) {
@@ -1244,7 +1174,7 @@ func TestReporter_ReportedSteps(t *testing.T) {
reporter, _ := newReporter(t, nil)
send(t, reporter, logging.LevelInfo, "Cleaning up container", map[string]any{"stage": runner.StageComplete})
send(t, reporter, logging.LevelInfo, "Job succeeded", map[string]any{"stage": runner.StageComplete, "jobResult": model.StepStatusSuccess})
require.NoError(t, reporter.Close(""))
require.NoError(t, reporter.Close(nil))
assert.Empty(t, reportedOf(t, reporter))
})
}

View File

@@ -3,4 +3,33 @@
"extends": [
"local>gitea/renovate-config"
],
"customManagers": [
{
"customType": "regex",
"managerFilePatterns": ["/^act/runner/node\\.go$/"],
"matchStrings": ['// renovate: datasource=(?<datasource>\\S+)\\s+\\{[^\\n]*"(?<depName>[a-z]+-[a-z0-9]+)", "(?<currentValue>[0-9.]+)", "(?<currentDigest>[a-f0-9]{64})"\\}'],
},
],
"customDatasources": {
"nodejs": {
"format": "plain",
"defaultRegistryUrlTemplate": "https://nodejs.org/dist/latest-v{{replace '[.].+' '' currentValue}}.x/SHASUMS256.txt",
"transformTemplates": [
'{"releases": [{"version": $match(releases[0].version, /node-v([0-9.]+)-/).groups[0], "digest": $substringBefore(releases[$contains(version, / (node-v[0-9.]+-)?{{packageName}}([.]tar[.]gz|[/]node[.]exe)$/)].version, " ")}]}',
],
},
"alpine-nodejs": {
"defaultRegistryUrlTemplate": "https://api.github.com/repos/actions/alpine_nodejs/releases",
"transformTemplates": [
'{"releases": [$[$substringBefore(tag_name, ".") = "v{{replace "[.].+" "" currentValue}}"].{"version": $substring(tag_name, 1), "releaseTimestamp": published_at, "digest": $substringAfter(assets[$contains(name, /-{{packageName}}[.]tar[.]gz$/) and digest].digest, "sha256:")}]}',
],
},
},
"packageRules": [
{
"description": "nodejs.org serves no release timestamps, so Node.js would be held back forever",
"matchDatasources": ["custom.nodejs"],
"minimumReleaseAge": "0",
},
],
}

View File

@@ -1,53 +1,26 @@
#!/usr/bin/env bash
if [[ ! -d /data ]]; then
mkdir -p /data
fi
mkdir -p /data
cd /data || exit 1
cd /data
CONFIG_ARG=""
if [[ ! -z "${CONFIG_FILE}" ]]; then
CONFIG_ARG="--config ${CONFIG_FILE}"
fi
RUNNER_STATE_FILE=${RUNNER_STATE_FILE:-$(gitea-runner ${CONFIG_ARG} config runner-file)}
LABEL_ARGS=""
if [[ ! -z "${GITEA_RUNNER_LABELS}" ]]; then
LABEL_ARGS="--labels ${GITEA_RUNNER_LABELS}"
fi
EXTRA_ARGS="${LABEL_ARGS}"
if [[ ! -z "${GITEA_RUNNER_EPHEMERAL}" ]]; then
EXTRA_ARGS="${EXTRA_ARGS} --ephemeral"
fi
# Also pass the labels to the daemon, so that an already registered runner
# picks up changes to GITEA_RUNNER_LABELS instead of keeping the labels it
# was first registered with.
RUN_ARGS="${LABEL_ARGS}"
if [[ ! -z "${GITEA_RUNNER_ONCE}" ]]; then
RUN_ARGS="${RUN_ARGS} --once"
fi
# In case no token is set, it's possible to read the token from a file, i.e. a Docker Secret
if [[ -z "${GITEA_RUNNER_REGISTRATION_TOKEN}" ]] && [[ -f "${GITEA_RUNNER_REGISTRATION_TOKEN_FILE}" ]]; then
GITEA_RUNNER_REGISTRATION_TOKEN=$(cat "${GITEA_RUNNER_REGISTRATION_TOKEN_FILE}")
fi
runner_args=(--config "$CONFIG_FILE")
RUNNER_STATE_FILE=${RUNNER_STATE_FILE:-$(gitea-runner "${runner_args[@]}" config runner-file)}
# Use the same ENV variable names as https://github.com/vegardit/docker-gitea-act-runner
test -f "$RUNNER_STATE_FILE" || echo "$RUNNER_STATE_FILE is missing or not a regular file"
if [[ ! -s "$RUNNER_STATE_FILE" ]]; then
register_args=("${runner_args[@]}" --instance "$GITEA_INSTANCE_URL" --name "$GITEA_RUNNER_NAME" --labels "$GITEA_RUNNER_LABELS"
--no-interactive ${GITEA_RUNNER_EPHEMERAL:+--ephemeral})
if [[ -z $GITEA_RUNNER_REGISTRATION_TOKEN && -f $GITEA_RUNNER_REGISTRATION_TOKEN_FILE ]]; then
register_args+=(--token-file "$GITEA_RUNNER_REGISTRATION_TOKEN_FILE")
fi
for ((try = 1; ; try++)); do # waits for Gitea like the daemon does, a container may have no restart policy
gitea-runner register \
--instance "${GITEA_INSTANCE_URL}" \
--token "${GITEA_RUNNER_REGISTRATION_TOKEN}" \
--name "${GITEA_RUNNER_NAME:-`hostname`}" \
${CONFIG_ARG} ${EXTRA_ARGS} --no-interactive 2>&1 | tee /tmp/reg.log
if grep -q 'Runner registered successfully' /tmp/reg.log; then
if gitea-runner register "${register_args[@]}" 2>&1; then
echo "SUCCESS"
break
fi
if [[ ${GITEA_MAX_REG_ATTEMPTS:-0} -gt 0 ]] && [[ $try -ge $GITEA_MAX_REG_ATTEMPTS ]]; then
if [[ ${GITEA_MAX_REG_ATTEMPTS:-0} -gt 0 && $try -ge $GITEA_MAX_REG_ATTEMPTS ]]; then
echo "Registration failed after ${try} attempts"
exit 1
fi
@@ -56,7 +29,6 @@ if [[ ! -s "$RUNNER_STATE_FILE" ]]; then
done
fi
# Prevent reading the token from the gitea-runner process
unset GITEA_RUNNER_REGISTRATION_TOKEN
unset GITEA_RUNNER_REGISTRATION_TOKEN_FILE
unset GITEA_RUNNER_REGISTRATION_TOKEN GITEA_RUNNER_REGISTRATION_TOKEN_FILE
exec gitea-runner daemon ${CONFIG_ARG} ${RUN_ARGS}
exec gitea-runner daemon "${runner_args[@]}" ${GITEA_RUNNER_ONCE:+--once}