mirror of
https://gitea.com/gitea/act_runner.git
synced 2026-07-22 12:37:46 +00:00
Compare commits
19 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ad967330a8 | ||
|
|
60177008a5 | ||
|
|
58c5eb8d21 | ||
|
|
d6882b3df5 | ||
|
|
7e7e3ef1a6 | ||
|
|
16357a34b2 | ||
|
|
d53538ac38 | ||
|
|
554b3b7671 | ||
|
|
65756d60b3 | ||
|
|
be9b4502d6 | ||
|
|
1d74ae636a | ||
|
|
b12d02c25f | ||
|
|
f2e0cf9131 | ||
|
|
0ee4643d4a | ||
|
|
e774003c18 | ||
|
|
eeb479ea89 | ||
|
|
eba33e178d | ||
|
|
3396021e0f | ||
|
|
745b0ab6e4 |
@@ -43,12 +43,18 @@ jobs:
|
||||
strategy:
|
||||
matrix:
|
||||
variant:
|
||||
# The basic image is built from source and can target any arch the
|
||||
# toolchain supports. The dind variants are limited to the arches the
|
||||
# docker:dind base image publishes.
|
||||
- target: basic
|
||||
tag_suffix: ""
|
||||
platforms: linux/amd64,linux/arm64,linux/riscv64,linux/s390x
|
||||
- target: dind
|
||||
tag_suffix: "-dind"
|
||||
platforms: linux/amd64,linux/arm64
|
||||
- target: dind-rootless
|
||||
tag_suffix: "-dind-rootless"
|
||||
platforms: linux/amd64,linux/arm64
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
@@ -82,9 +88,7 @@ jobs:
|
||||
context: .
|
||||
file: ./Dockerfile
|
||||
target: ${{ matrix.variant.target }}
|
||||
platforms: |
|
||||
linux/amd64
|
||||
linux/arm64
|
||||
platforms: ${{ matrix.variant.platforms }}
|
||||
push: true
|
||||
tags: |
|
||||
${{ env.DOCKER_ORG }}/runner:nightly${{ matrix.variant.tag_suffix }}
|
||||
|
||||
@@ -42,12 +42,18 @@ jobs:
|
||||
strategy:
|
||||
matrix:
|
||||
variant:
|
||||
# The basic image is built from source and can target any arch the
|
||||
# toolchain supports. The dind variants are limited to the arches the
|
||||
# docker:dind base image publishes.
|
||||
- target: basic
|
||||
tag_suffix: ""
|
||||
platforms: linux/amd64,linux/arm64,linux/riscv64,linux/s390x
|
||||
- target: dind
|
||||
tag_suffix: "-dind"
|
||||
platforms: linux/amd64,linux/arm64
|
||||
- target: dind-rootless
|
||||
tag_suffix: "-dind-rootless"
|
||||
platforms: linux/amd64,linux/arm64
|
||||
container:
|
||||
image: catthehacker/ubuntu:act-latest
|
||||
env:
|
||||
@@ -91,9 +97,7 @@ jobs:
|
||||
context: .
|
||||
file: ./Dockerfile
|
||||
target: ${{ matrix.variant.target }}
|
||||
platforms: |
|
||||
linux/amd64
|
||||
linux/arm64
|
||||
platforms: ${{ matrix.variant.platforms }}
|
||||
push: true
|
||||
tags: ${{ steps.docker_meta.outputs.tags }}
|
||||
build-args: |
|
||||
|
||||
@@ -42,3 +42,7 @@ jobs:
|
||||
# after `make test` so the images it needs are already present on the host daemon.
|
||||
- name: test against dind image
|
||||
run: make test-dind
|
||||
- name: coverage report
|
||||
run: |
|
||||
make coverage-report
|
||||
cat .tmp/coverage.md >> "$GITHUB_STEP_SUMMARY"
|
||||
2
.gitignore
vendored
2
.gitignore
vendored
@@ -3,6 +3,7 @@
|
||||
!/act/runner/testdata/secrets/.env
|
||||
.runner
|
||||
coverage.txt
|
||||
.tmp/
|
||||
/config.yaml
|
||||
|
||||
# Jetbrains
|
||||
@@ -12,3 +13,4 @@ coverage.txt
|
||||
__debug_bin
|
||||
# gorelease binary folder
|
||||
/dist
|
||||
.DS_Store
|
||||
@@ -17,14 +17,14 @@ RUN make clean && make build
|
||||
### DIND VARIANT
|
||||
#
|
||||
#
|
||||
FROM docker:29.6.0-dind AS dind
|
||||
FROM docker:29.6.1-dind AS dind
|
||||
|
||||
ARG VERSION=dev
|
||||
|
||||
LABEL org.opencontainers.image.source="https://gitea.com/gitea/runner"
|
||||
LABEL org.opencontainers.image.version="${VERSION}"
|
||||
|
||||
RUN apk add --no-cache s6 bash git tzdata
|
||||
RUN apk add --no-cache s6 bash git tzdata nftables
|
||||
|
||||
COPY --from=builder /opt/src/runner/gitea-runner /usr/local/bin/gitea-runner
|
||||
COPY scripts/run.sh /usr/local/bin/run.sh
|
||||
@@ -37,7 +37,7 @@ ENTRYPOINT ["s6-svscan","/etc/s6"]
|
||||
### DIND-ROOTLESS VARIANT
|
||||
#
|
||||
#
|
||||
FROM docker:29.6.0-dind-rootless AS dind-rootless
|
||||
FROM docker:29.6.1-dind-rootless AS dind-rootless
|
||||
|
||||
ARG VERSION=dev
|
||||
|
||||
@@ -45,7 +45,7 @@ LABEL org.opencontainers.image.source="https://gitea.com/gitea/runner"
|
||||
LABEL org.opencontainers.image.version="${VERSION}"
|
||||
|
||||
USER root
|
||||
RUN apk add --no-cache s6 bash git tzdata
|
||||
RUN apk add --no-cache s6 bash git tzdata nftables
|
||||
|
||||
COPY --from=builder /opt/src/runner/gitea-runner /usr/local/bin/gitea-runner
|
||||
COPY scripts/run.sh /usr/local/bin/run.sh
|
||||
|
||||
8
Makefile
8
Makefile
@@ -151,6 +151,12 @@ tidy-check: tidy
|
||||
test: fmt-check security-check ## test everything (integration tests self-skip without docker/network)
|
||||
@$(GO) test -race -timeout 20m -v -cover -coverprofile coverage.txt ./... && echo "\n==>\033[32m Ok\033[m\n" || exit 1
|
||||
|
||||
.PHONY: coverage-report
|
||||
coverage-report: ## turn coverage.txt from `make test` into .tmp/coverage.md
|
||||
@mkdir -p .tmp
|
||||
@node ./tools/coverage-report.ts -i coverage.txt -o .tmp/coverage.md
|
||||
@echo "Wrote .tmp/coverage.md"
|
||||
|
||||
.PHONY: test-dind
|
||||
test-dind: ## run the daemon-facing tests against the built dind image (TARGET=dind|dind-rootless)
|
||||
@./scripts/test-dind.sh $(TARGET)
|
||||
@@ -218,7 +224,7 @@ docker: ## build the docker image
|
||||
.PHONY: clean
|
||||
clean: ## delete binary and coverage files
|
||||
$(GO) clean -x -i ./...
|
||||
rm -rf coverage.txt $(EXECUTABLE) $(DIST)
|
||||
rm -rf coverage.txt .tmp $(EXECUTABLE) $(DIST)
|
||||
|
||||
.PHONY: version
|
||||
version: ## print the version
|
||||
|
||||
67
README.md
67
README.md
@@ -85,6 +85,8 @@ docker run -e GITEA_INSTANCE_URL=https://your_gitea.com -e GITEA_RUNNER_REGISTRA
|
||||
|
||||
Mount a volume on `/data` if you want the registration file and optional config to survive container recreation (see [scripts/run.sh](scripts/run.sh)).
|
||||
|
||||
> **`/data` does not hold the image cache.** It is the runner's working directory and contains only the `.runner` registration file and, optionally, your config file. Images pulled for jobs live in the *Docker daemon's* data root, which for the `dind` flavours is inside the container (`/var/lib/docker`, or `/home/rootless/.local/share/docker` for `dind-rootless`). To keep the image cache across restarts, give that path its own volume as well — otherwise every new container re-pulls the job images. With the `basic` flavour the images live on whichever daemon you point the runner at, so there is nothing extra to persist.
|
||||
|
||||
### Image flavours
|
||||
|
||||
The image is published in three flavours, all built from the single multi-stage [Dockerfile](Dockerfile) in this repository. They differ only in how a Docker daemon is made available to the jobs the runner executes; the `gitea-runner` binary inside them is identical.
|
||||
@@ -121,6 +123,8 @@ Two processes have to run side by side here (the Docker daemon and the runner),
|
||||
|
||||
Same idea as `dind`, but built on `docker:dind-rootless` so the bundled daemon and the runner run as an unprivileged user (`rootless`, UID 1000) rather than `root`. `DOCKER_HOST` is preset to `unix:///run/user/1000/docker.sock` so the runner talks to the rootless daemon. This reduces the blast radius compared to the privileged `dind` flavour, but rootless Docker carries the usual rootless limitations (networking, cgroups, storage drivers, and some operations that need additional host configuration such as `/etc/subuid` / `/etc/subgid` mappings and unprivileged user-namespace support).
|
||||
|
||||
> **The UID is fixed at 1000.** It comes from the `rootless` user baked into the upstream `docker:dind-rootless` base image, and the bundled daemon always listens on `/run/user/1000/docker.sock` inside the container, so running this flavour as a different user (`--user 1001`) does not work. If you need the runner to talk to a *host* rootless daemon that runs under some other UID, use the `basic` flavour instead and bind-mount that daemon's socket (see [examples/vm/rootless-docker.md](examples/vm/rootless-docker.md)); pointing `DOCKER_HOST` at a host socket from inside `dind-rootless` will not work. Changing the UID otherwise means rebuilding the image from a base with a different `rootless` user.
|
||||
|
||||
> **Note on Podman:** these images target the Docker daemon. The bundled `dind`/`dind-rootless` daemons are `dockerd`, not Podman, and the `basic` flavour expects a Docker-compatible socket. Running them under rootless Podman is not a supported configuration, though pointing the `basic` flavour at a Podman socket that emulates the Docker API may work for some workloads.
|
||||
|
||||
### Configuration
|
||||
@@ -143,23 +147,68 @@ Every option is described in [config.example.yaml](internal/pkg/config/config.ex
|
||||
|
||||
#### Without a config file
|
||||
|
||||
If you omit `-c`, built-in defaults apply (same as an empty YAML document). A small set of **deprecated** environment variables can still override parts of that default config, but **only when no `-c` path was given**; they are ignored if you use a config file:
|
||||
If you omit `-c`, built-in defaults apply (same as an empty YAML document).
|
||||
|
||||
| Variable | Effect |
|
||||
Earlier releases let a small set of environment variables (`GITEA_DEBUG`, `GITEA_TRACE`, `GITEA_RUNNER_CAPACITY`, `GITEA_RUNNER_FILE`, `GITEA_RUNNER_ENVIRON`, `GITEA_RUNNER_ENV_FILE`) override parts of the default config. Those overrides have been removed — use a YAML config file for all settings instead. For the Docker images, the entrypoint still understands a separate set of variables (such as `RUNNER_STATE_FILE`); see [scripts/run.sh](scripts/run.sh) and the container documentation below.
|
||||
|
||||
### Labels
|
||||
|
||||
Labels decide **which jobs a runner accepts** and **how it runs them**. A job's `runs-on` is matched against the runner's label names; the first match wins and selects the execution environment for that job.
|
||||
|
||||
A label is written as:
|
||||
|
||||
```text
|
||||
<name>[:<schema>[:<args>]]
|
||||
```
|
||||
|
||||
| Part | Meaning |
|
||||
| --- | --- |
|
||||
| `GITEA_DEBUG` | If true, sets log level to `debug` |
|
||||
| `GITEA_TRACE` | If true, sets log level to `trace` |
|
||||
| `GITEA_RUNNER_CAPACITY` | Concurrent jobs (integer) |
|
||||
| `GITEA_RUNNER_FILE` | Registration state file path (default `.runner`) |
|
||||
| `GITEA_RUNNER_ENVIRON` | Extra job env vars as comma-separated `KEY:VALUE` pairs |
|
||||
| `GITEA_RUNNER_ENV_FILE` | Path to an env file merged into job env (same idea as `runner.env_file` in YAML) |
|
||||
| `name` | The name a workflow refers to in `runs-on`, e.g. `ubuntu-latest`. |
|
||||
| `schema` | Either `docker` or `host`. Defaults to `host` when omitted. |
|
||||
| `args` | Only used by the `docker` schema: the image to run the job in. |
|
||||
|
||||
Prefer a YAML file for all settings.
|
||||
Two schemas are supported:
|
||||
|
||||
- **`docker://<image>`** — the job runs inside a container created from `<image>`:
|
||||
|
||||
```text
|
||||
ubuntu-latest:docker://docker.gitea.com/runner-images:ubuntu-latest
|
||||
```
|
||||
|
||||
- **`host`** — the job's steps run directly on the machine the runner is on, using the tools installed there:
|
||||
|
||||
```text
|
||||
macos:host
|
||||
```
|
||||
|
||||
So with the labels
|
||||
|
||||
```text
|
||||
ubuntu-latest:docker://docker.gitea.com/runner-images:ubuntu-latest,macos:host
|
||||
```
|
||||
|
||||
a workflow with `runs-on: ubuntu-latest` is executed in the `runner-images:ubuntu-latest` container, and one with `runs-on: macos` is executed directly on the host.
|
||||
|
||||
Names may themselves contain a colon (for example `pool:e57e18d4-10d4-406f-93bf-60f127221bdd`); only `host` and `docker` are treated as schemas.
|
||||
|
||||
If a job's `runs-on` matches none of the runner's labels, the job still runs, in the default `docker.gitea.com/runner-images:ubuntu-latest` image. Images maintained for this purpose are listed at [gitea/runner-images](https://gitea.com/gitea/runner-images).
|
||||
|
||||
Labels are chosen at registration time (`--labels`, or the interactive prompt) and can be changed afterwards by editing `runner.labels` in the config file, or in the Gitea UI under the runner's settings.
|
||||
|
||||
#### Registration vs config labels
|
||||
|
||||
If `runner.labels` is set in the YAML file, those labels are used during `register` and the `--labels` CLI flag is ignored.
|
||||
|
||||
The `daemon` command also accepts `--labels` (which defaults to the `GITEA_RUNNER_LABELS` environment variable), so the labels of an already registered runner can be changed without deleting its registration file. The most explicit source wins:
|
||||
|
||||
```
|
||||
--labels / GITEA_RUNNER_LABELS > runner.labels in the config file > labels in the .runner file
|
||||
```
|
||||
|
||||
Whenever the resulting labels differ from the ones in the registration file, they are written back to it and re-declared to the Gitea instance on startup.
|
||||
|
||||
> **Note:** A runner that only exposes `host` labels still needs access to a Docker daemon (e.g. a mounted `/var/run/docker.sock`) whenever a job uses a `docker://` action or a service container. `host` labels only change where the job's own steps run; container-based steps and actions are still executed with Docker.
|
||||
|
||||
#### Caching (`actions/cache`)
|
||||
|
||||
Each runner starts its own cache server automatically. Cache entries are local to that runner — runners do not share a cache by default.
|
||||
|
||||
@@ -390,6 +390,43 @@ func TestMkdirFsImplSafeResolve(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadWriteFSWritableAndAppendable(t *testing.T) {
|
||||
fsys := readWriteFSImpl{}
|
||||
name := filepath.Join(t.TempDir(), "nested", "artifact.txt")
|
||||
|
||||
w, err := fsys.OpenWritable(name)
|
||||
require.NoError(t, err)
|
||||
_, err = w.Write([]byte("first"))
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, w.Close())
|
||||
|
||||
w, err = fsys.OpenAppendable(name)
|
||||
require.NoError(t, err)
|
||||
_, err = w.Write([]byte("-second"))
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, w.Close())
|
||||
|
||||
got, err := os.ReadFile(name)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "first-second", string(got))
|
||||
|
||||
w, err = fsys.OpenWritable(name)
|
||||
require.NoError(t, err)
|
||||
_, err = w.Write([]byte("replaced"))
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, w.Close())
|
||||
|
||||
got, err = os.ReadFile(name)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "replaced", string(got))
|
||||
}
|
||||
|
||||
func TestServeEmptyArtifactPathReturnsCancelableNoop(t *testing.T) {
|
||||
cancel := Serve(t.Context(), "", "127.0.0.1", "0")
|
||||
require.NotNil(t, cancel)
|
||||
cancel()
|
||||
}
|
||||
|
||||
func TestDownloadArtifactFileUnsafePath(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
|
||||
|
||||
73
act/common/context_helpers_test.go
Normal file
73
act/common/context_helpers_test.go
Normal file
@@ -0,0 +1,73 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package common
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
func TestDryrunContext(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
if Dryrun(ctx) {
|
||||
t.Fatal("plain context should not be dryrun")
|
||||
}
|
||||
if !Dryrun(WithDryrun(ctx, true)) {
|
||||
t.Fatal("WithDryrun(true) should set dryrun")
|
||||
}
|
||||
if Dryrun(WithDryrun(ctx, false)) {
|
||||
t.Fatal("WithDryrun(false) should clear dryrun")
|
||||
}
|
||||
}
|
||||
|
||||
func TestJobErrorContainer(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
err := errors.New("job failed")
|
||||
|
||||
SetJobError(ctx, err)
|
||||
if got := JobError(ctx); got != nil {
|
||||
t.Fatalf("JobError without container = %v, want nil", got)
|
||||
}
|
||||
|
||||
ctx = WithJobErrorContainer(ctx)
|
||||
SetJobError(ctx, err)
|
||||
if got := JobError(ctx); !errors.Is(got, err) {
|
||||
t.Fatalf("JobError = %v, want %v", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoggerAndHookContext(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
if Logger(ctx) != logrus.StandardLogger() {
|
||||
t.Fatal("plain context should use standard logger")
|
||||
}
|
||||
if LoggerHook(ctx) != nil {
|
||||
t.Fatal("plain context should not have a logger hook")
|
||||
}
|
||||
|
||||
logger := logrus.New()
|
||||
ctx = WithLogger(ctx, logger)
|
||||
if Logger(ctx) != logger {
|
||||
t.Fatal("WithLogger should set logger")
|
||||
}
|
||||
|
||||
hook := testHook{}
|
||||
ctx = WithLoggerHook(ctx, hook)
|
||||
if LoggerHook(ctx) != hook {
|
||||
t.Fatal("WithLoggerHook should set hook")
|
||||
}
|
||||
}
|
||||
|
||||
type testHook struct{}
|
||||
|
||||
func (testHook) Levels() []logrus.Level {
|
||||
return logrus.AllLevels
|
||||
}
|
||||
|
||||
func (testHook) Fire(*logrus.Entry) error {
|
||||
return nil
|
||||
}
|
||||
@@ -7,6 +7,8 @@ package common
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"reflect"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -170,3 +172,43 @@ func TestNewParallelExecutorCanceled(t *testing.T) {
|
||||
assert.Equal(int32(3), count.Load())
|
||||
assert.Error(errExpected, err) //nolint:testifylint // pre-existing issue from nektos/act
|
||||
}
|
||||
|
||||
func TestExecutorConditionalsAndFinally(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
var calls []string
|
||||
record := func(name string) Executor {
|
||||
return func(ctx context.Context) error {
|
||||
calls = append(calls, name)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
require.NoError(t, record("if-true").If(func(context.Context) bool { return true })(ctx))
|
||||
require.NoError(t, record("if-false").If(func(context.Context) bool { return false })(ctx))
|
||||
require.NoError(t, record("if-not").IfNot(func(context.Context) bool { return false })(ctx))
|
||||
require.NoError(t, record("if-bool").IfBool(true)(ctx))
|
||||
require.NoError(t, record("main").Finally(record("finally"))(ctx))
|
||||
|
||||
want := []string{"if-true", "if-not", "if-bool", "main", "finally"}
|
||||
if !reflect.DeepEqual(calls, want) {
|
||||
t.Fatalf("calls = %v, want %v", calls, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecutorFinallyReturnsFinallyErrorWithOriginal(t *testing.T) {
|
||||
mainErr := errors.New("main failed")
|
||||
finalErr := errors.New("cleanup failed")
|
||||
|
||||
err := NewErrorExecutor(mainErr).Finally(NewErrorExecutor(finalErr))(context.Background())
|
||||
require.Error(t, err)
|
||||
if !strings.Contains(err.Error(), "cleanup failed") || !strings.Contains(err.Error(), "main failed") {
|
||||
t.Fatalf("finally error = %q, want both cleanup and original error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConditionalNot(t *testing.T) {
|
||||
cond := Conditional(func(context.Context) bool { return false })
|
||||
if !cond.Not()(context.Background()) {
|
||||
t.Fatal("inverted conditional should be true")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,6 +50,13 @@ func TestFindGitSlug(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestErrorWrapsCommitAndCause(t *testing.T) {
|
||||
err := &Error{err: ErrShortRef, commit: "abc123"}
|
||||
require.Equal(t, ErrShortRef.Error(), err.Error())
|
||||
require.ErrorIs(t, err, ErrShortRef)
|
||||
require.Equal(t, "abc123", err.Commit())
|
||||
}
|
||||
|
||||
func cleanGitHooks(dir string) error {
|
||||
hooksDir := filepath.Join(dir, ".git", "hooks")
|
||||
files, err := os.ReadDir(hooksDir)
|
||||
@@ -96,6 +103,22 @@ func TestFindGitRemoteURL(t *testing.T) {
|
||||
assert.Equal(remoteURL, u)
|
||||
}
|
||||
|
||||
func TestFindGithubRepoUsesOriginAndCustomRemote(t *testing.T) {
|
||||
basedir := t.TempDir()
|
||||
require.NoError(t, gitCmd("init", basedir))
|
||||
require.NoError(t, cleanGitHooks(basedir))
|
||||
require.NoError(t, gitCmd("-C", basedir, "remote", "add", "origin", "https://github.com/owner/repo.git"))
|
||||
require.NoError(t, gitCmd("-C", basedir, "remote", "add", "ghe", "git@git.example.com:team/project.git"))
|
||||
|
||||
slug, err := FindGithubRepo(context.Background(), basedir, "github.com", "")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "owner/repo", slug)
|
||||
|
||||
slug, err = FindGithubRepo(context.Background(), basedir, "git.example.com", "ghe")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "team/project", slug)
|
||||
}
|
||||
|
||||
func TestGitFindRef(t *testing.T) {
|
||||
basedir := t.TempDir()
|
||||
|
||||
|
||||
@@ -498,6 +498,79 @@ func TestParseDevice(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseDeviceByServerOS(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
device string
|
||||
serverOS string
|
||||
want container.DeviceMapping
|
||||
wantErr string
|
||||
}{
|
||||
{
|
||||
name: "linux source only",
|
||||
device: "/dev/snd",
|
||||
serverOS: "linux",
|
||||
want: container.DeviceMapping{
|
||||
PathOnHost: "/dev/snd",
|
||||
PathInContainer: "/dev/snd",
|
||||
CgroupPermissions: "rwm",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "linux source and mode",
|
||||
device: "/dev/snd:rw",
|
||||
serverOS: "linux",
|
||||
want: container.DeviceMapping{
|
||||
PathOnHost: "/dev/snd",
|
||||
PathInContainer: "/dev/snd",
|
||||
CgroupPermissions: "rw",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "linux source target and mode",
|
||||
device: "/dev/snd:/container/snd:m",
|
||||
serverOS: "linux",
|
||||
want: container.DeviceMapping{
|
||||
PathOnHost: "/dev/snd",
|
||||
PathInContainer: "/container/snd",
|
||||
CgroupPermissions: "m",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "windows passes value through",
|
||||
device: `class/GUID`,
|
||||
serverOS: "windows",
|
||||
want: container.DeviceMapping{
|
||||
PathOnHost: `class/GUID`,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "invalid server OS",
|
||||
device: "/dev/snd",
|
||||
serverOS: "plan9",
|
||||
wantErr: "unknown server OS: plan9",
|
||||
},
|
||||
{
|
||||
name: "too many linux fields",
|
||||
device: "/dev/snd:/container/snd:rw:extra",
|
||||
serverOS: "linux",
|
||||
wantErr: "invalid device specification: /dev/snd:/container/snd:rw:extra",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
got, err := parseDevice(tc.device, tc.serverOS)
|
||||
if tc.wantErr != "" {
|
||||
assert.Error(t, err, tc.wantErr)
|
||||
return
|
||||
}
|
||||
assert.NilError(t, err)
|
||||
assert.Equal(t, got, tc.want)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseNetworkConfig(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
@@ -930,6 +1003,82 @@ func TestValidateDevice(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateDeviceByServerOS(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
value string
|
||||
serverOS string
|
||||
want string
|
||||
wantError string
|
||||
}{
|
||||
{
|
||||
name: "linux preserves three-field container path",
|
||||
value: "/host:/container/../device:rw",
|
||||
serverOS: "linux",
|
||||
want: "/host:/container/../device:rw",
|
||||
},
|
||||
{
|
||||
name: "linux source path can be relative when target is absolute",
|
||||
value: "relative-host:/container/device",
|
||||
serverOS: "linux",
|
||||
want: "relative-host:/container/device",
|
||||
},
|
||||
{
|
||||
name: "windows defers validation",
|
||||
value: `class/GUID`,
|
||||
serverOS: "windows",
|
||||
want: `class/GUID`,
|
||||
},
|
||||
{
|
||||
name: "linux rejects bad mode",
|
||||
value: "/host:/container:ro",
|
||||
serverOS: "linux",
|
||||
wantError: "bad mode specified: ro",
|
||||
},
|
||||
{
|
||||
name: "linux target must be absolute",
|
||||
value: "/host:relative",
|
||||
serverOS: "linux",
|
||||
wantError: "relative is not an absolute path",
|
||||
},
|
||||
{
|
||||
name: "unknown server OS",
|
||||
value: "/dev/snd",
|
||||
serverOS: "plan9",
|
||||
wantError: "unknown server OS: plan9",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
got, err := validateDevice(tc.value, tc.serverOS)
|
||||
if tc.wantError != "" {
|
||||
assert.Error(t, err, tc.wantError)
|
||||
return
|
||||
}
|
||||
assert.NilError(t, err)
|
||||
assert.Equal(t, got, tc.want)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeviceCgroupRulesAndInvalidParameter(t *testing.T) {
|
||||
got, err := validateDeviceCgroupRule("c 1:3 rwm")
|
||||
assert.NilError(t, err)
|
||||
assert.Equal(t, got, "c 1:3 rwm")
|
||||
|
||||
_, err = validateDeviceCgroupRule("invalid")
|
||||
assert.Error(t, err, "invalid device cgroup format 'invalid'")
|
||||
|
||||
if invalidParameter(nil) != nil {
|
||||
t.Fatal("invalidParameter(nil) should be nil")
|
||||
}
|
||||
err = invalidParameter(errors.New("bad input"))
|
||||
assert.Assert(t, err != nil)
|
||||
var invalid interface{ InvalidParameter() }
|
||||
assert.Assert(t, errors.As(err, &invalid))
|
||||
}
|
||||
|
||||
func TestParseSystemPaths(t *testing.T) {
|
||||
tests := []struct {
|
||||
doc string
|
||||
|
||||
@@ -72,7 +72,9 @@ func NewDockerPullExecutor(input NewDockerPullExecutorInput) common.Executor {
|
||||
|
||||
_ = logDockerResponse(logger, reader, err != nil)
|
||||
}
|
||||
return err
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to pull image '%s' (%s): %w", imageRef, input.Platform, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -13,6 +13,9 @@ import (
|
||||
"strings"
|
||||
|
||||
"gitea.com/gitea/runner/act/common"
|
||||
|
||||
"golang.org/x/text/encoding/unicode"
|
||||
"golang.org/x/text/transform"
|
||||
)
|
||||
|
||||
func parseEnvFile(e Container, srcPath string, env *map[string]string) common.Executor {
|
||||
@@ -28,11 +31,19 @@ func parseEnvFile(e Container, srcPath string, env *map[string]string) common.Ex
|
||||
if err != nil && err != io.EOF {
|
||||
return err
|
||||
}
|
||||
s := bufio.NewScanner(reader)
|
||||
// Decode by BOM: Windows PowerShell 5.1 redirection writes UTF-16, and some
|
||||
// tools emit a UTF-8 BOM. Without a BOM the file is read as UTF-8, as before.
|
||||
decoded := transform.NewReader(reader, unicode.BOMOverride(unicode.UTF8.NewDecoder()))
|
||||
|
||||
s := bufio.NewScanner(decoded)
|
||||
// Default 64 KiB max token size is too small for realistic env-file lines; allow up to 16 MiB.
|
||||
s.Buffer(make([]byte, 0, 64*1024), 16*1024*1024)
|
||||
for s.Scan() {
|
||||
line := s.Text()
|
||||
// GitHub's runner ignores blank lines
|
||||
if strings.TrimSpace(line) == "" {
|
||||
continue
|
||||
}
|
||||
singleLineEnv := strings.Index(line, "=")
|
||||
multiLineEnv := strings.Index(line, "<<")
|
||||
if singleLineEnv != -1 && (multiLineEnv == -1 || singleLineEnv < multiLineEnv) {
|
||||
|
||||
@@ -13,6 +13,8 @@ import (
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"golang.org/x/text/encoding"
|
||||
"golang.org/x/text/encoding/unicode"
|
||||
)
|
||||
|
||||
func newTestHostEnv(t *testing.T) (*HostEnvironment, string) {
|
||||
@@ -64,6 +66,63 @@ func TestParseEnvFileLineExceedsBufferReportsScannerError(t *testing.T) {
|
||||
assert.Contains(t, err.Error(), "reading env file")
|
||||
}
|
||||
|
||||
// Regression test: a blank line used to fail the job at "Complete Job", after
|
||||
// every step had already been recorded as successful.
|
||||
func TestParseEnvFileBlankLines(t *testing.T) {
|
||||
e, envPath := newTestHostEnv(t)
|
||||
require.NoError(t, os.WriteFile(envPath, []byte("\nFOO=bar\n\n \nBAZ=qux\n\n"), 0o600))
|
||||
|
||||
env := map[string]string{}
|
||||
require.NoError(t, parseEnvFile(e, envPath, &env)(context.Background()))
|
||||
assert.Equal(t, "bar", env["FOO"])
|
||||
assert.Equal(t, "qux", env["BAZ"])
|
||||
}
|
||||
|
||||
// blank lines inside a heredoc value are content, not separators
|
||||
func TestParseEnvFileMultiLineKeepsBlankLines(t *testing.T) {
|
||||
e, envPath := newTestHostEnv(t)
|
||||
require.NoError(t, os.WriteFile(envPath, []byte("FOO<<EOF\nline1\n\nline2\nEOF\n"), 0o600))
|
||||
|
||||
env := map[string]string{}
|
||||
require.NoError(t, parseEnvFile(e, envPath, &env)(context.Background()))
|
||||
assert.Equal(t, "line1\n\nline2", env["FOO"])
|
||||
}
|
||||
|
||||
func TestParseEnvFileUTF8BOM(t *testing.T) {
|
||||
e, envPath := newTestHostEnv(t)
|
||||
content := append([]byte{0xEF, 0xBB, 0xBF}, []byte("FOO=bar\n")...)
|
||||
require.NoError(t, os.WriteFile(envPath, content, 0o600))
|
||||
|
||||
env := map[string]string{}
|
||||
require.NoError(t, parseEnvFile(e, envPath, &env)(context.Background()))
|
||||
assert.Equal(t, "bar", env["FOO"])
|
||||
}
|
||||
|
||||
// Windows host mode: PowerShell 5.1 redirection writes UTF-16, which used to be
|
||||
// unrecognisable as KEY=VALUE, so the writes were silently ignored.
|
||||
func TestParseEnvFileUTF16(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
encoder *encoding.Encoder
|
||||
}{
|
||||
{"little endian", unicode.UTF16(unicode.LittleEndian, unicode.UseBOM).NewEncoder()},
|
||||
{"big endian", unicode.UTF16(unicode.BigEndian, unicode.UseBOM).NewEncoder()},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
e, envPath := newTestHostEnv(t)
|
||||
content, err := tt.encoder.Bytes([]byte("FOO=bar\r\nMULTI<<EOF\r\nline1\r\nEOF\r\n"))
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, os.WriteFile(envPath, content, 0o600))
|
||||
|
||||
env := map[string]string{}
|
||||
require.NoError(t, parseEnvFile(e, envPath, &env)(context.Background()))
|
||||
assert.Equal(t, "bar", env["FOO"])
|
||||
assert.Equal(t, "line1", env["MULTI"])
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseEnvFileMissingDelimiter(t *testing.T) {
|
||||
e, envPath := newTestHostEnv(t)
|
||||
require.NoError(t, os.WriteFile(envPath, []byte("FOO<<EOF\nline1\nline2\n"), 0o600))
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/go-git/go-billy/v5"
|
||||
"github.com/go-git/go-billy/v5/memfs"
|
||||
@@ -221,3 +222,63 @@ func TestCopyCollectorWriteFileOverwritesFileWithSymlink(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "target", resolved)
|
||||
}
|
||||
|
||||
func TestDefaultFsOpenReadlinkAndWalk(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("creating symlinks requires elevated privileges on Windows")
|
||||
}
|
||||
|
||||
root := t.TempDir()
|
||||
require.NoError(t, os.WriteFile(filepath.Join(root, "file.txt"), []byte("content"), 0o644))
|
||||
require.NoError(t, os.Symlink("file.txt", filepath.Join(root, "link.txt")))
|
||||
|
||||
fsys := &DefaultFs{}
|
||||
var walked []string
|
||||
require.NoError(t, fsys.Walk(root, func(path string, info os.FileInfo, err error) error {
|
||||
require.NoError(t, err)
|
||||
walked = append(walked, info.Name())
|
||||
return nil
|
||||
}))
|
||||
require.Contains(t, walked, "file.txt")
|
||||
require.Contains(t, walked, "link.txt")
|
||||
|
||||
file, err := fsys.Open(filepath.Join(root, "file.txt"))
|
||||
require.NoError(t, err)
|
||||
data, err := io.ReadAll(file)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, file.Close())
|
||||
require.Equal(t, "content", string(data))
|
||||
|
||||
link, err := fsys.Readlink(filepath.Join(root, "link.txt"))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "file.txt", link)
|
||||
}
|
||||
|
||||
func TestFileCollectorCancellationAndWalkError(t *testing.T) {
|
||||
fc := &FileCollector{Fs: &memoryFs{Filesystem: memfs.New()}}
|
||||
walk := fc.CollectFiles(cancelledContext(t), nil)
|
||||
|
||||
err := walk("file", fakeFileInfo{name: "file"}, nil)
|
||||
require.EqualError(t, err, "copy cancelled")
|
||||
|
||||
err = walk("file", fakeFileInfo{name: "file"}, os.ErrPermission)
|
||||
require.ErrorIs(t, err, os.ErrPermission)
|
||||
}
|
||||
|
||||
func cancelledContext(t *testing.T) context.Context {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
return ctx
|
||||
}
|
||||
|
||||
type fakeFileInfo struct {
|
||||
name string
|
||||
}
|
||||
|
||||
func (f fakeFileInfo) Name() string { return f.name }
|
||||
func (f fakeFileInfo) Size() int64 { return 0 }
|
||||
func (f fakeFileInfo) Mode() os.FileMode { return 0o644 }
|
||||
func (f fakeFileInfo) ModTime() time.Time { return time.Time{} }
|
||||
func (f fakeFileInfo) IsDir() bool { return false }
|
||||
func (f fakeFileInfo) Sys() any { return nil }
|
||||
|
||||
74
act/lookpath/lp_unix_test.go
Normal file
74
act/lookpath/lp_unix_test.go
Normal file
@@ -0,0 +1,74 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
//go:build aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris
|
||||
|
||||
package lookpath
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type testEnv map[string]string
|
||||
|
||||
func (e testEnv) Getenv(name string) string {
|
||||
return e[name]
|
||||
}
|
||||
|
||||
func TestLookPath2SearchesPathAndEmptyElement(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
exe := filepath.Join(dir, "tool")
|
||||
if err := os.WriteFile(exe, []byte("#!/bin/sh\n"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
got, err := LookPath2("tool", testEnv{"PATH": string(filepath.ListSeparator) + dir})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got != exe {
|
||||
t.Fatalf("LookPath2() = %q, want %q", got, exe)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLookPath2DirectPathDoesNotSearchPath(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
exe := filepath.Join(dir, "tool")
|
||||
if err := os.WriteFile(exe, []byte("#!/bin/sh\n"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
got, err := LookPath2(exe, testEnv{"PATH": ""})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got != exe {
|
||||
t.Fatalf("LookPath2() = %q, want %q", got, exe)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLookPath2ReportsPermissionAndNotFound(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
file := filepath.Join(dir, "not-executable")
|
||||
if err := os.WriteFile(file, []byte("plain text"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
_, err := LookPath2(file, testEnv{"PATH": dir})
|
||||
var pathErr *Error
|
||||
if !errors.As(err, &pathErr) || !errors.Is(pathErr.Err, fs.ErrPermission) {
|
||||
t.Fatalf("LookPath2(non-executable) error = %v, want fs.ErrPermission wrapped in *Error", err)
|
||||
}
|
||||
if pathErr.Error() != fs.ErrPermission.Error() {
|
||||
t.Fatalf("Error() = %q, want %q", pathErr.Error(), fs.ErrPermission.Error())
|
||||
}
|
||||
|
||||
_, err = LookPath2("missing", testEnv{"PATH": dir})
|
||||
if !errors.As(err, &pathErr) || !errors.Is(pathErr.Err, ErrNotFound) {
|
||||
t.Fatalf("LookPath2(missing) error = %v, want ErrNotFound wrapped in *Error", err)
|
||||
}
|
||||
}
|
||||
63
act/model/action_test.go
Normal file
63
act/model/action_test.go
Normal file
@@ -0,0 +1,63 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package model
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestReadActionDefaultsAndCaseInsensitiveUsing(t *testing.T) {
|
||||
action, err := ReadAction(strings.NewReader(`
|
||||
name: example
|
||||
runs:
|
||||
using: NoDe24
|
||||
main: dist/index.js
|
||||
`))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if action.Runs.Using != ActionRunsUsingNode24 {
|
||||
t.Fatalf("using = %q, want %q", action.Runs.Using, ActionRunsUsingNode24)
|
||||
}
|
||||
if action.Runs.PreIf != "always()" {
|
||||
t.Fatalf("pre-if = %q, want always()", action.Runs.PreIf)
|
||||
}
|
||||
if action.Runs.PostIf != "always()" {
|
||||
t.Fatalf("post-if = %q, want always()", action.Runs.PostIf)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadActionPreservesExplicitConditions(t *testing.T) {
|
||||
action, err := ReadAction(strings.NewReader(`
|
||||
runs:
|
||||
using: composite
|
||||
pre-if: success()
|
||||
post-if: failure()
|
||||
steps:
|
||||
- run: echo hello
|
||||
`))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if action.Runs.PreIf != "success()" || action.Runs.PostIf != "failure()" {
|
||||
t.Fatalf("conditions = %q/%q, want explicit values", action.Runs.PreIf, action.Runs.PostIf)
|
||||
}
|
||||
if !action.Runs.Using.IsComposite() || action.Runs.Using.IsDocker() || action.Runs.Using.IsNode() {
|
||||
t.Fatalf("unexpected using predicates for %q", action.Runs.Using)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadActionRejectsUnknownUsing(t *testing.T) {
|
||||
_, err := ReadAction(strings.NewReader(`
|
||||
runs:
|
||||
using: node99
|
||||
`))
|
||||
if err == nil {
|
||||
t.Fatal("expected unknown runs.using to fail")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "node99") {
|
||||
t.Fatalf("error = %q, want invalid value", err)
|
||||
}
|
||||
}
|
||||
@@ -6,10 +6,12 @@ package model
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type WorkflowPlanTest struct {
|
||||
@@ -65,3 +67,133 @@ func TestWorkflow(t *testing.T) {
|
||||
assert.NoError(t, err) //nolint:testifylint // pre-existing issue from nektos/act
|
||||
assert.NotNil(t, result)
|
||||
}
|
||||
|
||||
func TestNewSingleWorkflowPlannerAndPlanMethods(t *testing.T) {
|
||||
planner, err := NewSingleWorkflowPlanner("ci.yml", strings.NewReader(`
|
||||
name: CI
|
||||
on: [push, pull_request]
|
||||
jobs:
|
||||
build:
|
||||
name: Build project
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- run: make build
|
||||
test:
|
||||
needs: build
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- run: make test
|
||||
`))
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, []string{"pull_request", "push"}, planner.GetEvents())
|
||||
|
||||
eventPlan, err := planner.PlanEvent("push")
|
||||
require.NoError(t, err)
|
||||
require.Len(t, eventPlan.Stages, 2)
|
||||
assert.Equal(t, []string{"build"}, eventPlan.Stages[0].GetJobIDs())
|
||||
assert.Equal(t, []string{"test"}, eventPlan.Stages[1].GetJobIDs())
|
||||
assert.Equal(t, len("Build project"), eventPlan.MaxRunNameLen())
|
||||
assert.Equal(t, "Build project", eventPlan.Stages[0].Runs[0].String())
|
||||
assert.Equal(t, "build", eventPlan.Stages[0].Runs[0].JobID)
|
||||
assert.NotNil(t, eventPlan.Stages[0].Runs[0].Job())
|
||||
|
||||
jobPlan, err := planner.PlanJob("test")
|
||||
require.NoError(t, err)
|
||||
require.Len(t, jobPlan.Stages, 2)
|
||||
assert.Equal(t, []string{"build"}, jobPlan.Stages[0].GetJobIDs())
|
||||
assert.Equal(t, []string{"test"}, jobPlan.Stages[1].GetJobIDs())
|
||||
|
||||
allPlan, err := planner.PlanAll()
|
||||
require.NoError(t, err)
|
||||
require.Len(t, allPlan.Stages, 2)
|
||||
assert.Equal(t, []string{"build"}, allPlan.Stages[0].GetJobIDs())
|
||||
assert.Equal(t, []string{"test"}, allPlan.Stages[1].GetJobIDs())
|
||||
}
|
||||
|
||||
func TestCombineWorkflowPlannerMergesWorkflowStages(t *testing.T) {
|
||||
first := mustReadWorkflow(t, `
|
||||
name: First
|
||||
on: push
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- run: make build
|
||||
`)
|
||||
second := mustReadWorkflow(t, `
|
||||
name: Second
|
||||
on: push
|
||||
jobs:
|
||||
lint:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- run: make lint
|
||||
test:
|
||||
needs: lint
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- run: make test
|
||||
`)
|
||||
|
||||
planner := CombineWorkflowPlanner(first, second)
|
||||
plan, err := planner.PlanEvent("push")
|
||||
require.NoError(t, err)
|
||||
require.Len(t, plan.Stages, 2)
|
||||
assert.ElementsMatch(t, []string{"build", "lint"}, plan.Stages[0].GetJobIDs())
|
||||
assert.Equal(t, []string{"test"}, plan.Stages[1].GetJobIDs())
|
||||
|
||||
empty, err := planner.PlanEvent("schedule")
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, empty.Stages)
|
||||
}
|
||||
|
||||
func TestPlannerErrorsForMissingAndCyclicJobs(t *testing.T) {
|
||||
workflow := mustReadWorkflow(t, `
|
||||
name: Cyclic
|
||||
on: push
|
||||
jobs:
|
||||
a:
|
||||
needs: b
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- run: echo a
|
||||
b:
|
||||
needs: a
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- run: echo b
|
||||
`)
|
||||
planner := CombineWorkflowPlanner(workflow)
|
||||
|
||||
plan, err := planner.PlanJob("missing")
|
||||
require.Error(t, err)
|
||||
assert.Empty(t, plan.Stages)
|
||||
assert.Contains(t, err.Error(), "Could not find any stages")
|
||||
|
||||
plan, err = planner.PlanEvent("push")
|
||||
require.Error(t, err)
|
||||
assert.Empty(t, plan.Stages)
|
||||
assert.Contains(t, err.Error(), "unable to build dependency graph")
|
||||
}
|
||||
|
||||
func TestNewSingleWorkflowPlannerErrors(t *testing.T) {
|
||||
_, err := NewSingleWorkflowPlanner("empty.yml", strings.NewReader(""))
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "file is empty")
|
||||
|
||||
_, err = NewSingleWorkflowPlanner("invalid.yml", strings.NewReader("jobs: ["))
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "workflow is not valid")
|
||||
}
|
||||
|
||||
func mustReadWorkflow(t *testing.T, content string) *Workflow {
|
||||
t.Helper()
|
||||
|
||||
workflow, err := ReadWorkflow(strings.NewReader(content))
|
||||
require.NoError(t, err)
|
||||
if workflow.Name == "" {
|
||||
workflow.Name = "workflow"
|
||||
}
|
||||
return workflow
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
@@ -58,6 +59,190 @@ func TestJobNeedsResult(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestJobSetContinueOnErrorFirmFailureWins(t *testing.T) {
|
||||
job := &Job{}
|
||||
job.SetContinueOnError(true)
|
||||
assert.True(t, job.ContinueOnError)
|
||||
|
||||
job.SetContinueOnError(false)
|
||||
assert.False(t, job.ContinueOnError)
|
||||
|
||||
job.SetContinueOnError(true)
|
||||
assert.False(t, job.ContinueOnError, "a later tolerated failure must not hide an earlier firm failure")
|
||||
}
|
||||
|
||||
func TestStepStatusText(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
status stepStatus
|
||||
text string
|
||||
}{
|
||||
{StepStatusSuccess, "success"},
|
||||
{StepStatusFailure, "failure"},
|
||||
{StepStatusSkipped, "skipped"},
|
||||
} {
|
||||
t.Run(tc.text, func(t *testing.T) {
|
||||
got, err := tc.status.MarshalText()
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, tc.text, string(got))
|
||||
|
||||
var parsed stepStatus
|
||||
require.NoError(t, parsed.UnmarshalText(got))
|
||||
assert.Equal(t, tc.status, parsed)
|
||||
assert.Equal(t, tc.text, parsed.String())
|
||||
})
|
||||
}
|
||||
|
||||
var parsed stepStatus
|
||||
require.Error(t, parsed.UnmarshalText([]byte("cancelled")))
|
||||
assert.Empty(t, stepStatus(99).String())
|
||||
}
|
||||
|
||||
func TestWorkflowCallConfig(t *testing.T) {
|
||||
workflow, err := ReadWorkflow(strings.NewReader(`
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
name:
|
||||
required: true
|
||||
type: string
|
||||
outputs:
|
||||
digest:
|
||||
value: ${{ jobs.build.outputs.digest }}
|
||||
jobs: {}
|
||||
`))
|
||||
require.NoError(t, err)
|
||||
|
||||
config := workflow.WorkflowCallConfig()
|
||||
require.NotNil(t, config)
|
||||
require.Contains(t, config.Inputs, "name")
|
||||
assert.True(t, config.Inputs["name"].Required)
|
||||
assert.Equal(t, "string", config.Inputs["name"].Type)
|
||||
assert.Equal(t, "${{ jobs.build.outputs.digest }}", config.Outputs["digest"].Value)
|
||||
|
||||
listWorkflow, err := ReadWorkflow(strings.NewReader("on: [workflow_call]\njobs: {}\n"))
|
||||
require.NoError(t, err)
|
||||
assert.NotNil(t, listWorkflow.WorkflowCallConfig())
|
||||
assert.Empty(t, listWorkflow.WorkflowCallConfig().Inputs)
|
||||
}
|
||||
|
||||
func TestJobSecretsAndEnvironment(t *testing.T) {
|
||||
inheritJob := readJob(t, `
|
||||
secrets: inherit
|
||||
env:
|
||||
A: one
|
||||
B: two
|
||||
`)
|
||||
assert.True(t, inheritJob.InheritSecrets())
|
||||
assert.Nil(t, inheritJob.Secrets())
|
||||
assert.Equal(t, map[string]string{"A": "one", "B": "two"}, inheritJob.Environment())
|
||||
|
||||
mappingJob := readJob(t, `
|
||||
secrets:
|
||||
TOKEN: ${{ secrets.TOKEN }}
|
||||
`)
|
||||
assert.False(t, mappingJob.InheritSecrets())
|
||||
assert.Equal(t, map[string]string{"TOKEN": "${{ secrets.TOKEN }}"}, mappingJob.Secrets())
|
||||
}
|
||||
|
||||
func TestJobTypeAndString(t *testing.T) {
|
||||
tests := []struct {
|
||||
job Job
|
||||
want JobType
|
||||
wantErr bool
|
||||
}{
|
||||
{job: Job{}, want: JobTypeDefault},
|
||||
{job: Job{Uses: "./.github/workflows/reuse.yml"}, want: JobTypeReusableWorkflowLocal},
|
||||
{job: Job{Uses: "owner/repo/.github/workflows/reuse.yaml@v1"}, want: JobTypeReusableWorkflowRemote},
|
||||
{job: Job{Uses: "owner/repo/.github/workflows/reuse.yaml"}, want: JobTypeInvalid, wantErr: true},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(fmt.Sprintf("%s/%s", tc.job.Uses, tc.want), func(t *testing.T) {
|
||||
got, err := tc.job.Type()
|
||||
if tc.wantErr {
|
||||
require.Error(t, err)
|
||||
} else {
|
||||
require.NoError(t, err)
|
||||
}
|
||||
assert.Equal(t, tc.want, got)
|
||||
})
|
||||
}
|
||||
|
||||
assert.Equal(t, "default", JobTypeDefault.String())
|
||||
assert.Equal(t, "local-reusable-workflow", JobTypeReusableWorkflowLocal.String())
|
||||
assert.Equal(t, "remote-reusable-workflow", JobTypeReusableWorkflowRemote.String())
|
||||
assert.Equal(t, "unknown", JobType(99).String())
|
||||
}
|
||||
|
||||
func TestStepStringEnvironmentEnvAndType(t *testing.T) {
|
||||
step := readStep(t, `
|
||||
id: example
|
||||
env:
|
||||
DIRECT: value
|
||||
with:
|
||||
mixed-key: input
|
||||
`)
|
||||
assert.Equal(t, "example", step.String())
|
||||
assert.Equal(t, map[string]string{"DIRECT": "value"}, step.Environment())
|
||||
assert.Equal(t, map[string]string{"DIRECT": "value", "INPUT_MIXED-KEY": "input"}, step.GetEnv())
|
||||
|
||||
for _, tc := range []struct {
|
||||
step Step
|
||||
want StepType
|
||||
}{
|
||||
{step: Step{}, want: StepTypeInvalid},
|
||||
{step: Step{Run: "echo hi"}, want: StepTypeRun},
|
||||
{step: Step{Run: "echo hi", Uses: "actions/checkout@v4"}, want: StepTypeInvalid},
|
||||
{step: Step{Uses: "docker://alpine:latest"}, want: StepTypeUsesDockerURL},
|
||||
{step: Step{Uses: "./.github/workflows/reuse.yml"}, want: StepTypeReusableWorkflowLocal},
|
||||
{step: Step{Uses: "owner/repo/.github/workflows/reuse.yml@v1"}, want: StepTypeReusableWorkflowRemote},
|
||||
{step: Step{Uses: "./actions/local"}, want: StepTypeUsesActionLocal},
|
||||
{step: Step{Uses: "actions/checkout@v4"}, want: StepTypeUsesActionRemote},
|
||||
} {
|
||||
t.Run(tc.want.String(), func(t *testing.T) {
|
||||
assert.Equal(t, tc.want, tc.step.Type())
|
||||
})
|
||||
}
|
||||
|
||||
assert.Equal(t, "invalid", StepTypeInvalid.String())
|
||||
assert.Equal(t, "run", StepTypeRun.String())
|
||||
assert.Equal(t, "local-action", StepTypeUsesActionLocal.String())
|
||||
assert.Equal(t, "remote-action", StepTypeUsesActionRemote.String())
|
||||
assert.Equal(t, "docker", StepTypeUsesDockerURL.String())
|
||||
assert.Equal(t, "local-reusable-workflow", StepTypeReusableWorkflowLocal.String())
|
||||
assert.Equal(t, "remote-reusable-workflow", StepTypeReusableWorkflowRemote.String())
|
||||
assert.Equal(t, "unknown", StepType(99).String())
|
||||
assert.NotEmpty(t, (&Step{Uses: "actions/checkout@v4"}).UsesHash())
|
||||
}
|
||||
|
||||
func TestWorkflowGetJobAndIDs(t *testing.T) {
|
||||
workflow := &Workflow{Jobs: map[string]*Job{"build": {}}}
|
||||
assert.Equal(t, []string{"build"}, workflow.GetJobIDs())
|
||||
|
||||
job := workflow.GetJob("build")
|
||||
require.NotNil(t, job)
|
||||
assert.Equal(t, "build", job.Name)
|
||||
assert.Equal(t, "success()", job.If.Value)
|
||||
assert.Nil(t, workflow.GetJob("missing"))
|
||||
}
|
||||
|
||||
func TestRawConcurrencyYaml(t *testing.T) {
|
||||
var expr RawConcurrency
|
||||
require.NoError(t, yaml.Unmarshal([]byte("group-${{ github.ref }}"), &expr))
|
||||
assert.Equal(t, "group-${{ github.ref }}", expr.RawExpression)
|
||||
marshaled, err := expr.MarshalYAML()
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "group-${{ github.ref }}", marshaled)
|
||||
|
||||
var object RawConcurrency
|
||||
require.NoError(t, yaml.Unmarshal([]byte("group: ci\ncancel-in-progress: true\n"), &object))
|
||||
assert.Equal(t, "ci", object.Group)
|
||||
assert.Equal(t, "true", object.CancelInProgress)
|
||||
marshaled, err = object.MarshalYAML()
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, (*objectConcurrency)(&object), marshaled)
|
||||
}
|
||||
|
||||
func TestReadWorkflow_ScheduleEvent(t *testing.T) {
|
||||
yaml := `
|
||||
name: local-action-docker-url
|
||||
@@ -952,3 +1137,19 @@ func TestJobMatrixValidation(t *testing.T) {
|
||||
assert.Nil(t, matrix, "matrix with nested map should return nil")
|
||||
})
|
||||
}
|
||||
|
||||
func readJob(t *testing.T, content string) *Job {
|
||||
t.Helper()
|
||||
|
||||
var job Job
|
||||
require.NoError(t, yaml.Unmarshal([]byte(content), &job))
|
||||
return &job
|
||||
}
|
||||
|
||||
func readStep(t *testing.T, content string) *Step {
|
||||
t.Helper()
|
||||
|
||||
var step Step
|
||||
require.NoError(t, yaml.Unmarshal([]byte(content), &step))
|
||||
return &step
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
@@ -85,6 +86,19 @@ func newCompositeRunContext(ctx context.Context, parent *RunContext, step action
|
||||
return compositerc
|
||||
}
|
||||
|
||||
// appendUniqueMasks appends the masks from src to dst, skipping any mask that
|
||||
// is already present in dst. This prevents the parent RunContext's Masks slice
|
||||
// from growing exponentially when composite actions are nested or repeated,
|
||||
// since each composite RunContext is seeded with its parent's masks.
|
||||
func appendUniqueMasks(dst, src []string) []string {
|
||||
for _, m := range src {
|
||||
if !slices.Contains(dst, m) {
|
||||
dst = append(dst, m)
|
||||
}
|
||||
}
|
||||
return dst
|
||||
}
|
||||
|
||||
func execAsComposite(step actionStep) common.Executor {
|
||||
rc := step.getRunContext()
|
||||
action := step.getActionModel()
|
||||
@@ -110,7 +124,11 @@ func execAsComposite(step actionStep) common.Executor {
|
||||
}, eval.Interpolate(ctx, output.Value))
|
||||
}
|
||||
|
||||
rc.Masks = append(rc.Masks, compositeRC.Masks...)
|
||||
// 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
|
||||
// compositeRC.Env is dirty, contains INPUT_ and merged step env, only rely on compositeRC.GlobalEnv
|
||||
mergeIntoMap := mergeIntoMapCaseSensitive
|
||||
|
||||
70
act/runner/action_composite_test.go
Normal file
70
act/runner/action_composite_test.go
Normal file
@@ -0,0 +1,70 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package runner
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestAppendUniqueMasks(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
dst []string
|
||||
src []string
|
||||
want []string
|
||||
}{
|
||||
{
|
||||
name: "appends new masks",
|
||||
dst: []string{"a"},
|
||||
src: []string{"b", "c"},
|
||||
want: []string{"a", "b", "c"},
|
||||
},
|
||||
{
|
||||
name: "skips masks already present",
|
||||
dst: []string{"a", "b"},
|
||||
src: []string{"a", "b"},
|
||||
want: []string{"a", "b"},
|
||||
},
|
||||
{
|
||||
name: "deduplicates within src",
|
||||
dst: []string{"a"},
|
||||
src: []string{"b", "b", "a"},
|
||||
want: []string{"a", "b"},
|
||||
},
|
||||
{
|
||||
name: "empty src leaves dst unchanged",
|
||||
dst: []string{"a"},
|
||||
src: nil,
|
||||
want: []string{"a"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
assert.Equal(t, tt.want, appendUniqueMasks(tt.dst, tt.src))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestAppendUniqueMasksNoExponentialGrowth reproduces the exponential growth of
|
||||
// the parent's Masks slice observed with nested/repeated composite actions. A
|
||||
// composite RunContext is seeded with its parent's masks and the whole seeded
|
||||
// slice was previously appended back into the parent, doubling its length on
|
||||
// every composite action.
|
||||
func TestAppendUniqueMasksNoExponentialGrowth(t *testing.T) {
|
||||
parentMasks := []string{"secret"}
|
||||
|
||||
for range 20 {
|
||||
// compositeRC.Masks starts as a copy of the parent's masks (it is
|
||||
// seeded with parent.Masks in newCompositeRunContext).
|
||||
compositeMasks := make([]string, len(parentMasks))
|
||||
copy(compositeMasks, parentMasks)
|
||||
|
||||
parentMasks = appendUniqueMasks(parentMasks, compositeMasks)
|
||||
}
|
||||
|
||||
assert.Equal(t, []string{"secret"}, parentMasks)
|
||||
}
|
||||
@@ -229,7 +229,8 @@ func (ee expressionEvaluator) evaluate(ctx context.Context, in string, defaultSt
|
||||
logger.Debugf("evaluating expression '%s'", in)
|
||||
evaluated, err := ee.interpreter.Evaluate(in, defaultStatusCheck)
|
||||
|
||||
printable := regexp.MustCompile(`::add-mask::.*`).ReplaceAllString(fmt.Sprintf("%t", evaluated), "::add-mask::***)")
|
||||
// evaluated is an any: %t renders everything but a bool as "%!t(string=...)"
|
||||
printable := regexp.MustCompile(`::add-mask::.*`).ReplaceAllString(fmt.Sprintf("%v", evaluated), "::add-mask::***)")
|
||||
logger.Debugf("expression '%s' evaluated to '%s'", in, printable)
|
||||
|
||||
return evaluated, err
|
||||
@@ -497,11 +498,7 @@ func getEvaluatorInputs(ctx context.Context, rc *RunContext, step step, ghc *mod
|
||||
if value == nil {
|
||||
value = v.Default
|
||||
}
|
||||
if v.Type == "boolean" {
|
||||
inputs[k] = value == "true"
|
||||
} else {
|
||||
inputs[k] = value
|
||||
}
|
||||
inputs[k] = coerceInputValue(value, v.Type)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -514,17 +511,26 @@ func getEvaluatorInputs(ctx context.Context, rc *RunContext, step step, ghc *mod
|
||||
if value == nil {
|
||||
value = v.Default
|
||||
}
|
||||
if v.Type == "boolean" {
|
||||
inputs[k] = value == "true"
|
||||
} else {
|
||||
inputs[k] = value
|
||||
}
|
||||
inputs[k] = coerceInputValue(value, v.Type)
|
||||
}
|
||||
}
|
||||
}
|
||||
return inputs
|
||||
}
|
||||
|
||||
// coerceInputValue converts an input value to the type declared by the workflow.
|
||||
// The event payload carries natively typed JSON values on newer Gitea versions,
|
||||
// while defaults and older servers provide strings.
|
||||
func coerceInputValue(value any, inputType string) any {
|
||||
if inputType != "boolean" {
|
||||
return value
|
||||
}
|
||||
if b, ok := value.(bool); ok {
|
||||
return b
|
||||
}
|
||||
return value == "true"
|
||||
}
|
||||
|
||||
func setupWorkflowInputs(ctx context.Context, inputs *map[string]any, rc *RunContext) {
|
||||
if rc.caller != nil {
|
||||
config := rc.Run.Workflow.WorkflowCallConfig()
|
||||
@@ -548,7 +554,7 @@ func setupWorkflowInputs(ctx context.Context, inputs *map[string]any, rc *RunCon
|
||||
}
|
||||
}
|
||||
|
||||
(*inputs)[name] = value
|
||||
(*inputs)[name] = coerceInputValue(value, input.Type)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,12 +6,14 @@ package runner
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"gitea.com/gitea/runner/act/exprparser"
|
||||
"gitea.com/gitea/runner/act/model"
|
||||
|
||||
assert "github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
yaml "go.yaml.in/yaml/v4"
|
||||
)
|
||||
|
||||
@@ -321,3 +323,82 @@ func TestRewriteSubExpressionForceFormat(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetEvaluatorInputsBoolean(t *testing.T) {
|
||||
workflows := map[string]string{
|
||||
"workflow_call": `
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
flag:
|
||||
type: boolean
|
||||
default: true
|
||||
name:
|
||||
type: string
|
||||
default: gitea
|
||||
`,
|
||||
"workflow_dispatch": `
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
flag:
|
||||
type: boolean
|
||||
default: true
|
||||
name:
|
||||
type: string
|
||||
default: gitea
|
||||
`,
|
||||
}
|
||||
|
||||
tables := []struct {
|
||||
name string
|
||||
event map[string]any
|
||||
flag any
|
||||
}{
|
||||
{
|
||||
// Gitea >= 1.27 resolves the inputs server-side and sends native JSON types
|
||||
name: "native bool true",
|
||||
event: map[string]any{"inputs": map[string]any{"flag": true}},
|
||||
flag: true,
|
||||
},
|
||||
{
|
||||
name: "native bool false",
|
||||
event: map[string]any{"inputs": map[string]any{"flag": false}},
|
||||
flag: false,
|
||||
},
|
||||
{
|
||||
name: "string true",
|
||||
event: map[string]any{"inputs": map[string]any{"flag": "true"}},
|
||||
flag: true,
|
||||
},
|
||||
{
|
||||
name: "string false",
|
||||
event: map[string]any{"inputs": map[string]any{"flag": "false"}},
|
||||
flag: false,
|
||||
},
|
||||
{
|
||||
name: "default is used when the event carries no inputs",
|
||||
event: map[string]any{},
|
||||
flag: true,
|
||||
},
|
||||
}
|
||||
|
||||
for eventName, workflow := range workflows {
|
||||
for _, table := range tables {
|
||||
t.Run(eventName+"/"+table.name, func(t *testing.T) {
|
||||
wf, err := model.ReadWorkflow(strings.NewReader(workflow))
|
||||
require.NoError(t, err)
|
||||
|
||||
rc := &RunContext{
|
||||
Config: &Config{Workdir: "."},
|
||||
Run: &model.Run{JobID: "job1", Workflow: wf},
|
||||
}
|
||||
ghc := &model.GithubContext{EventName: eventName, Event: table.event}
|
||||
|
||||
inputs := getEvaluatorInputs(context.Background(), rc, nil, ghc)
|
||||
assert.Equal(t, table.flag, inputs["flag"])
|
||||
assert.Equal(t, "gitea", inputs["name"])
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -305,30 +305,45 @@ func setReusedWorkflowCallerResult(rc *RunContext, runner Runner) common.Executo
|
||||
// getGitCloneToken returns GITEA_TOKEN when shouldCloneURLUseToken returns true,
|
||||
// otherwise returns an empty string
|
||||
func getGitCloneToken(conf *Config, cloneURL string) string {
|
||||
if !shouldCloneURLUseToken(conf.GitHubInstance, cloneURL) {
|
||||
if !shouldCloneURLUseToken(conf.GitHubInstance, conf.trustedActionInstance(), cloneURL) {
|
||||
return ""
|
||||
}
|
||||
return conf.GetToken()
|
||||
}
|
||||
|
||||
// For Gitea
|
||||
// shouldCloneURLUseToken returns true when the following conditions are met:
|
||||
// 1. cloneURL is from the same Gitea instance that the runner is registered to
|
||||
// 2. the cloneURL does not have basic auth embedded
|
||||
func shouldCloneURLUseToken(instanceURL, cloneURL string) bool {
|
||||
if !strings.HasPrefix(instanceURL, "http://") &&
|
||||
!strings.HasPrefix(instanceURL, "https://") {
|
||||
instanceURL = "https://" + instanceURL
|
||||
// trustedActionInstance returns the self-hosted DEFAULT_ACTIONS_URL host that may carry the
|
||||
// task token, or "" when actions resolve to github.com / a GithubMirror (never trusted).
|
||||
func (c Config) trustedActionInstance() string {
|
||||
if c.DefaultActionInstanceIsSelfHosted {
|
||||
return c.DefaultActionInstance
|
||||
}
|
||||
|
||||
u1, err1 := url.Parse(instanceURL)
|
||||
u2, err2 := url.Parse(cloneURL)
|
||||
if err1 != nil || err2 != nil {
|
||||
return false
|
||||
}
|
||||
if u2.User != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
return u1.Host == u2.Host
|
||||
return ""
|
||||
}
|
||||
|
||||
// For Gitea
|
||||
// shouldCloneURLUseToken returns true when the following conditions are met:
|
||||
// 1. cloneURL's host matches this Gitea instance: either the registered instance
|
||||
// (instanceURL) or, for DEFAULT_ACTIONS_URL=self on a different hostname, the
|
||||
// self-hosted action instance (trustedActionInstance, "" when not trusted)
|
||||
// 2. the cloneURL does not have basic auth embedded
|
||||
func shouldCloneURLUseToken(instanceURL, trustedActionInstance, cloneURL string) bool {
|
||||
u2, err := url.Parse(cloneURL)
|
||||
if err != nil || u2.User != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
for _, candidate := range []string{instanceURL, trustedActionInstance} {
|
||||
if candidate == "" {
|
||||
continue
|
||||
}
|
||||
if !strings.HasPrefix(candidate, "http://") &&
|
||||
!strings.HasPrefix(candidate, "https://") {
|
||||
candidate = "https://" + candidate
|
||||
}
|
||||
if u1, err := url.Parse(candidate); err == nil && u1.Host == u2.Host {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -136,12 +136,30 @@ func TestGetGitCloneTokenWithSchemalessGiteaInstance(t *testing.T) {
|
||||
require.Equal(t, "token-value", token)
|
||||
}
|
||||
|
||||
func TestGetGitCloneTokenSelfHostedActionsDifferentHost(t *testing.T) {
|
||||
// The runner registered with one hostname while DEFAULT_ACTIONS_URL=self resolves
|
||||
// actions against AppURL on a different hostname for the same instance.
|
||||
conf := &Config{
|
||||
GitHubInstance: "gitea.local",
|
||||
DefaultActionInstance: "https://gitea.my-nas.lan",
|
||||
DefaultActionInstanceIsSelfHosted: true,
|
||||
Secrets: map[string]string{
|
||||
"GITEA_TOKEN": "token-value",
|
||||
},
|
||||
}
|
||||
|
||||
token := getGitCloneToken(conf, "https://gitea.my-nas.lan/owner/action")
|
||||
|
||||
require.Equal(t, "token-value", token)
|
||||
}
|
||||
|
||||
func TestShouldCloneURLUseToken(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
instanceURL string
|
||||
cloneURL string
|
||||
want bool
|
||||
name string
|
||||
instanceURL string
|
||||
trustedActionInstance string
|
||||
cloneURL string
|
||||
want bool
|
||||
}{
|
||||
{
|
||||
name: "same host with schemaless instance",
|
||||
@@ -173,11 +191,37 @@ func TestShouldCloneURLUseToken(t *testing.T) {
|
||||
cloneURL: "://gitea.example.net/actions/tools",
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
// self-hosted DEFAULT_ACTIONS_URL on a different hostname than the
|
||||
// registered instance: the token must still be attached.
|
||||
name: "self-hosted action instance on different host",
|
||||
instanceURL: "gitea.local",
|
||||
trustedActionInstance: "https://gitea.my-nas.lan",
|
||||
cloneURL: "https://gitea.my-nas.lan/owner/action",
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
// embedded basic auth must still be rejected even when the host matches
|
||||
// the trusted action instance.
|
||||
name: "self-hosted action instance with embedded basic auth",
|
||||
instanceURL: "gitea.local",
|
||||
trustedActionInstance: "https://gitea.my-nas.lan",
|
||||
cloneURL: "https://user:pass@gitea.my-nas.lan/owner/action",
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
// github.com / mirror hosts are never trusted: trustedActionInstance is
|
||||
// empty in github mode, so an off-instance clone URL gets no token.
|
||||
name: "github mode does not trust mirror host",
|
||||
instanceURL: "gitea.local",
|
||||
cloneURL: "https://mirror.example.com/owner/action",
|
||||
want: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
require.Equal(t, tt.want, shouldCloneURLUseToken(tt.instanceURL, tt.cloneURL))
|
||||
require.Equal(t, tt.want, shouldCloneURLUseToken(tt.instanceURL, tt.trustedActionInstance, tt.cloneURL))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -138,7 +138,9 @@ func (rc *RunContext) GetEnv() map[string]string {
|
||||
}
|
||||
}
|
||||
}
|
||||
rc.Env["ACT"] = "true"
|
||||
if !rc.Config.DisableActEnv {
|
||||
rc.Env["ACT"] = "true"
|
||||
}
|
||||
|
||||
if !rc.Config.NoSkipCheckout {
|
||||
rc.Env["ACT_SKIP_CHECKOUT"] = "true"
|
||||
@@ -337,6 +339,9 @@ func printStartJobContainerGroup(ctx context.Context, image, name, network strin
|
||||
}
|
||||
}
|
||||
|
||||
// newContainer is a variable so tests can substitute a container that needs no Docker daemon.
|
||||
var newContainer = container.NewContainer
|
||||
|
||||
func (rc *RunContext) startJobContainer() common.Executor {
|
||||
return func(ctx context.Context) error {
|
||||
logger := common.Logger(ctx)
|
||||
@@ -379,6 +384,13 @@ func (rc *RunContext) startJobContainer() common.Executor {
|
||||
|
||||
// add service containers
|
||||
for serviceID, spec := range rc.Run.Job().Services {
|
||||
// GitHub compatibility: skip services whose image evaluates to an
|
||||
// empty string, enabling conditional services via expressions
|
||||
serviceImage := rc.ExprEval.Interpolate(ctx, spec.Image)
|
||||
if serviceImage == "" {
|
||||
logger.Infof("The service '%s' will not be started because the container definition has an empty image.", serviceID)
|
||||
continue
|
||||
}
|
||||
// interpolate env
|
||||
interpolatedEnvs := make(map[string]string, len(spec.Env))
|
||||
for k, v := range spec.Env {
|
||||
@@ -393,7 +405,9 @@ func (rc *RunContext) startJobContainer() common.Executor {
|
||||
for _, v := range spec.Cmd {
|
||||
interpolatedCmd = append(interpolatedCmd, rc.ExprEval.Interpolate(ctx, v))
|
||||
}
|
||||
username, password, err = rc.handleServiceCredentials(ctx, spec.Credentials)
|
||||
// keep these local: reusing username/password would overwrite the
|
||||
// credentials the job container is pulled with further down
|
||||
serviceUsername, servicePassword, err := rc.handleServiceCredentials(ctx, spec.Credentials)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to handle service %s credentials: %w", serviceID, err)
|
||||
}
|
||||
@@ -414,12 +428,12 @@ func (rc *RunContext) startJobContainer() common.Executor {
|
||||
}
|
||||
|
||||
serviceContainerName := createContainerName(rc.jobContainerName(), serviceID)
|
||||
c := container.NewContainer(&container.NewContainerInput{
|
||||
c := newContainer(&container.NewContainerInput{
|
||||
Name: serviceContainerName,
|
||||
WorkingDir: ext.ToContainerPath(rc.Config.Workdir),
|
||||
Image: rc.ExprEval.Interpolate(ctx, spec.Image),
|
||||
Username: username,
|
||||
Password: password,
|
||||
Image: serviceImage,
|
||||
Username: serviceUsername,
|
||||
Password: servicePassword,
|
||||
Cmd: interpolatedCmd,
|
||||
Env: envs,
|
||||
Mounts: serviceMounts,
|
||||
@@ -475,7 +489,7 @@ func (rc *RunContext) startJobContainer() common.Executor {
|
||||
// For Gitea, `jobContainerNetwork` should be the same as `networkName`
|
||||
jobContainerNetwork := networkName
|
||||
|
||||
rc.JobContainer = container.NewContainer(&container.NewContainerInput{
|
||||
rc.JobContainer = newContainer(&container.NewContainerInput{
|
||||
Cmd: nil,
|
||||
Entrypoint: []string{"/bin/sleep", fmt.Sprint(rc.Config.ContainerMaxLifetime.Round(time.Second).Seconds())},
|
||||
WorkingDir: ext.ToContainerPath(rc.Config.Workdir),
|
||||
@@ -783,7 +797,13 @@ func (rc *RunContext) Executor() (common.Executor, error) {
|
||||
return func(ctx context.Context) error {
|
||||
res, err := rc.isEnabled(ctx)
|
||||
if err != nil {
|
||||
rc.caller.setReusedWorkflowJobResult(rc.JobName, "failure") // For Gitea
|
||||
// Record the failure so a job whose if-expression fails to evaluate
|
||||
// gets a result (and therefore a stop time) instead of being left
|
||||
// unfinished. rc.caller is only set for reusable workflows.
|
||||
rc.result("failure")
|
||||
if rc.caller != nil { // For Gitea
|
||||
rc.caller.setReusedWorkflowJobResult(rc.JobName, "failure")
|
||||
}
|
||||
return err
|
||||
}
|
||||
if res {
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"testing"
|
||||
|
||||
"gitea.com/gitea/runner/act/common"
|
||||
"gitea.com/gitea/runner/act/container"
|
||||
"gitea.com/gitea/runner/act/exprparser"
|
||||
"gitea.com/gitea/runner/act/model"
|
||||
|
||||
@@ -202,6 +203,93 @@ jobs:
|
||||
assert.Empty(t, password)
|
||||
}
|
||||
|
||||
// fakeContainer turns every container operation into a no-op, so startJobContainer
|
||||
// runs without a Docker daemon. The embedded interface is nil, so any method the
|
||||
// test does not exercise panics rather than silently doing the wrong thing.
|
||||
type fakeContainer struct {
|
||||
container.ExecutionsEnvironment
|
||||
}
|
||||
|
||||
func (fakeContainer) Pull(bool) common.Executor { return func(context.Context) error { return nil } }
|
||||
func (fakeContainer) Start(bool) common.Executor { return func(context.Context) error { return nil } }
|
||||
func (fakeContainer) Remove() common.Executor { return func(context.Context) error { return nil } }
|
||||
func (fakeContainer) Close() common.Executor { return func(context.Context) error { return nil } }
|
||||
func (fakeContainer) GetActPath() string { return "/var/run/act" }
|
||||
func (fakeContainer) Create([]string, []string) common.Executor {
|
||||
return func(context.Context) error { return nil }
|
||||
}
|
||||
|
||||
func (fakeContainer) Copy(string, ...*container.FileEntry) common.Executor {
|
||||
return func(context.Context) error { return nil }
|
||||
}
|
||||
|
||||
// Regression test: a service without a `credentials:` block resolves to empty
|
||||
// credentials, which used to overwrite the job container's own credentials.
|
||||
func TestStartJobContainerKeepsJobCredentialsWithServices(t *testing.T) {
|
||||
workflow, err := model.ReadWorkflow(strings.NewReader(`
|
||||
name: test
|
||||
on: push
|
||||
jobs:
|
||||
job:
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: registry.example/private:latest
|
||||
credentials:
|
||||
username: job-user
|
||||
password: job-password
|
||||
services:
|
||||
redis:
|
||||
image: redis:latest
|
||||
db:
|
||||
image: postgres:latest
|
||||
credentials:
|
||||
username: db-user
|
||||
password: db-password
|
||||
steps: []
|
||||
`))
|
||||
require.NoError(t, err)
|
||||
|
||||
var inputs []*container.NewContainerInput
|
||||
origNewContainer := newContainer
|
||||
newContainer = func(input *container.NewContainerInput) container.ExecutionsEnvironment {
|
||||
inputs = append(inputs, input)
|
||||
return fakeContainer{}
|
||||
}
|
||||
t.Cleanup(func() { newContainer = origNewContainer })
|
||||
|
||||
rc := &RunContext{
|
||||
Name: "test",
|
||||
Config: &Config{
|
||||
Workdir: "/tmp",
|
||||
// no daemon: an explicit network mode creates no network, and
|
||||
// reusing containers short-circuits the volume cleanup executors
|
||||
ContainerNetworkMode: "host",
|
||||
ReuseContainers: true,
|
||||
Env: map[string]string{},
|
||||
Secrets: map[string]string{},
|
||||
},
|
||||
Env: map[string]string{},
|
||||
Run: &model.Run{
|
||||
JobID: "job",
|
||||
Workflow: workflow,
|
||||
},
|
||||
}
|
||||
rc.ExprEval = rc.NewExpressionEvaluator(t.Context())
|
||||
|
||||
require.NoError(t, rc.startJobContainer()(t.Context()))
|
||||
|
||||
credentials := map[string][2]string{}
|
||||
for _, in := range inputs {
|
||||
credentials[in.Image] = [2]string{in.Username, in.Password}
|
||||
}
|
||||
|
||||
// the job container keeps its own credentials, whichever services exist
|
||||
require.Equal(t, [2]string{"job-user", "job-password"}, credentials["registry.example/private:latest"])
|
||||
// each service keeps its own, and a service without credentials gets none
|
||||
require.Equal(t, [2]string{"db-user", "db-password"}, credentials["postgres:latest"])
|
||||
require.Equal(t, [2]string{"", ""}, credentials["redis:latest"])
|
||||
}
|
||||
|
||||
func TestRunContext_GetBindsAndMounts(t *testing.T) {
|
||||
rctemplate := &RunContext{
|
||||
Name: "TestRCName",
|
||||
|
||||
@@ -65,6 +65,7 @@ type Config struct {
|
||||
ArtifactServerAddr string // the address the artifact server binds to
|
||||
ArtifactServerPort string // the port the artifact server binds to
|
||||
NoSkipCheckout bool // do not skip actions/checkout
|
||||
DisableActEnv bool // do not inject the ACT=true environment variable into jobs
|
||||
RemoteName string // remote name in local git repo config
|
||||
ReplaceGheActionWithGithubCom []string // Use actions from GitHub Enterprise instance to GitHub
|
||||
ReplaceGheActionTokenWithGithubCom string // Token of private action repo on GitHub.
|
||||
@@ -73,18 +74,24 @@ type Config struct {
|
||||
ContainerNetworkCreateOptions container.NewDockerNetworkCreateExecutorInput // the default network create options
|
||||
ActionCache ActionCache // Use a custom ActionCache Implementation
|
||||
|
||||
PresetGitHubContext *model.GithubContext // the preset github context, overrides some fields like DefaultBranch, Env, Secrets etc.
|
||||
EventJSON string // the content of JSON file to use for event.json in containers, overrides EventPath
|
||||
ContainerNamePrefix string // the prefix of container name
|
||||
ContainerMaxLifetime time.Duration // the max lifetime of job containers
|
||||
CleanWorkdir bool // remove host executor workdir on teardown
|
||||
DefaultActionInstance string // the default actions web site
|
||||
PlatformPicker func(labels []string) string // platform picker, it will take precedence over Platforms if isn't nil
|
||||
JobLoggerLevel *log.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
|
||||
InsecureSkipTLS bool // whether to skip verifying TLS certificate of the Gitea instance
|
||||
MaxParallel int // max parallel jobs to run across all workflows (0 = no limit, uses CPU count)
|
||||
AllocatePTY bool // allocate a pseudo-TTY for each step's process
|
||||
PresetGitHubContext *model.GithubContext // the preset github context, overrides some fields like DefaultBranch, Env, Secrets etc.
|
||||
EventJSON string // the content of JSON file to use for event.json in containers, overrides EventPath
|
||||
ContainerNamePrefix string // the prefix of container name
|
||||
ContainerMaxLifetime time.Duration // the max lifetime of job containers
|
||||
CleanWorkdir bool // remove host executor workdir on teardown
|
||||
DefaultActionInstance string // the default actions web site
|
||||
// DefaultActionInstanceIsSelfHosted reports whether DefaultActionInstance is this
|
||||
// self-hosted Gitea (DEFAULT_ACTIONS_URL=self). It gates token trust: only then may the
|
||||
// task token be attached to action clone URLs on DefaultActionInstance's host, which can
|
||||
// differ from GitHubInstance when the runner registered with a different hostname than
|
||||
// AppURL. It is never set for github.com or a GithubMirror, so the token stays on-instance.
|
||||
DefaultActionInstanceIsSelfHosted bool
|
||||
PlatformPicker func(labels []string) string // platform picker, it will take precedence over Platforms if isn't nil
|
||||
JobLoggerLevel *log.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
|
||||
InsecureSkipTLS bool // whether to skip verifying TLS certificate of the Gitea instance
|
||||
MaxParallel int // max parallel jobs to run across all workflows (0 = no limit, uses CPU count)
|
||||
AllocatePTY bool // allocate a pseudo-TTY for each step's process
|
||||
}
|
||||
|
||||
// GetToken: Adapt to Gitea
|
||||
|
||||
@@ -303,6 +303,7 @@ func TestRunEvent(t *testing.T) {
|
||||
// services
|
||||
{workdir, "services", "push", "", platforms, secrets},
|
||||
{workdir, "services-with-container", "push", "", platforms, secrets},
|
||||
{workdir, "services-empty-image", "push", "", platforms, secrets},
|
||||
|
||||
// local remote action overrides
|
||||
{workdir, "local-remote-action-overrides", "push", "", platforms, secrets},
|
||||
|
||||
@@ -121,7 +121,7 @@ func (sar *stepActionRemote) prepareActionExecutor() common.Executor {
|
||||
// top-level token; keep the shouldCloneURLUseToken host gate to avoid leaking it.
|
||||
cloneURL := sar.remoteAction.CloneURL(defaultActionURL)
|
||||
token := ""
|
||||
if shouldCloneURLUseToken(sar.RunContext.Config.GitHubInstance, cloneURL) {
|
||||
if shouldCloneURLUseToken(sar.RunContext.Config.GitHubInstance, sar.RunContext.Config.trustedActionInstance(), cloneURL) {
|
||||
token = github.Token
|
||||
}
|
||||
gitClone := stepActionRemoteNewCloneExecutor(git.NewGitCloneExecutorInput{
|
||||
|
||||
10
act/runner/testdata/services-empty-image/push.yml
vendored
Normal file
10
act/runner/testdata/services-empty-image/push.yml
vendored
Normal file
@@ -0,0 +1,10 @@
|
||||
name: services-empty-image
|
||||
on: push
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
services:
|
||||
db:
|
||||
image: ${{ false && 'postgres:16' || '' }}
|
||||
steps:
|
||||
- run: echo "empty-image service was skipped"
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"inputs": {
|
||||
"required": "required input",
|
||||
"boolean": "true"
|
||||
"boolean": true
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,11 @@ NOTE: `dind-docker.yaml` uses the native sidecar pattern (init container with `r
|
||||
|
||||
NOTE: A helm chart for `gitea-runner` also exists for easier deployments https://gitea.com/gitea/helm-actions
|
||||
|
||||
Each example persists **two** things, and it is worth knowing which is which:
|
||||
|
||||
- `/data` is the runner's working directory. It holds the `.runner` registration file and, optionally, the config file — so the runner re-attaches to the server instead of registering again.
|
||||
- The Docker daemon's data root holds the images pulled for jobs (`/var/lib/docker` for the dind sidecar, `/home/rootless/.local/share/docker` for `dind-rootless`). It is *not* under `/data`. If you drop this volume, the examples still work, but the image cache is discarded whenever the pod is recreated and every job re-pulls its images.
|
||||
|
||||
Files in this directory:
|
||||
|
||||
- [`dind-docker.yaml`](dind-docker.yaml)
|
||||
@@ -13,3 +18,6 @@ Files in this directory:
|
||||
|
||||
- [`rootless-docker.yaml`](rootless-docker.yaml)
|
||||
How to create a rootless Deployment and Persistent Volume for Kubernetes to act as a runner. The Docker credentials are re-generated each time the pod connects and does not need to be persisted.
|
||||
|
||||
- [`statefulset-dind.yaml`](statefulset-dind.yaml)
|
||||
StatefulSet variant of the dind example. Each replica gets a stable identity and its own persistent volume via `volumeClaimTemplates`, so the runner keeps its `.runner` registration across restarts and reschedules instead of trying to register again.
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
# Holds the runner's working directory (/data): the .runner registration file
|
||||
# and, optionally, the config file.
|
||||
kind: PersistentVolumeClaim
|
||||
apiVersion: v1
|
||||
metadata:
|
||||
@@ -10,6 +12,21 @@ spec:
|
||||
storage: 1Gi
|
||||
storageClassName: standard
|
||||
---
|
||||
# Holds the Docker daemon's data root (/var/lib/docker), i.e. the images pulled
|
||||
# for jobs. Without it, the image cache is lost whenever the pod is recreated
|
||||
# and every job re-pulls its images. Size it for the images you expect to cache.
|
||||
kind: PersistentVolumeClaim
|
||||
apiVersion: v1
|
||||
metadata:
|
||||
name: docker-vol
|
||||
spec:
|
||||
accessModes:
|
||||
- ReadWriteOnce
|
||||
resources:
|
||||
requests:
|
||||
storage: 20Gi
|
||||
storageClassName: standard
|
||||
---
|
||||
apiVersion: v1
|
||||
data:
|
||||
# The registration token can be obtained from the web UI, API or command-line.
|
||||
@@ -45,6 +62,9 @@ spec:
|
||||
- name: runner-data
|
||||
persistentVolumeClaim:
|
||||
claimName: runner-vol
|
||||
- name: docker-data
|
||||
persistentVolumeClaim:
|
||||
claimName: docker-vol
|
||||
initContainers:
|
||||
- name: docker
|
||||
image: docker:28.2.2-dind
|
||||
@@ -53,6 +73,8 @@ spec:
|
||||
volumeMounts:
|
||||
- name: docker-socket
|
||||
mountPath: /var/run
|
||||
- name: docker-data
|
||||
mountPath: /var/lib/docker
|
||||
startupProbe:
|
||||
exec:
|
||||
command: ["/usr/bin/test", "-S", "/var/run/docker.sock"]
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
# Holds the runner's working directory (/data): the .runner registration file
|
||||
# and, optionally, the config file.
|
||||
kind: PersistentVolumeClaim
|
||||
apiVersion: v1
|
||||
metadata:
|
||||
@@ -10,6 +12,21 @@ spec:
|
||||
storage: 1Gi
|
||||
storageClassName: standard
|
||||
---
|
||||
# Holds the rootless Docker daemon's data root, i.e. the images pulled for jobs.
|
||||
# Without it, the image cache is lost whenever the pod is recreated and every job
|
||||
# re-pulls its images. Size it for the images you expect to cache.
|
||||
kind: PersistentVolumeClaim
|
||||
apiVersion: v1
|
||||
metadata:
|
||||
name: docker-vol
|
||||
spec:
|
||||
accessModes:
|
||||
- ReadWriteOnce
|
||||
resources:
|
||||
requests:
|
||||
storage: 20Gi
|
||||
storageClassName: standard
|
||||
---
|
||||
apiVersion: v1
|
||||
data:
|
||||
# The registration token can be obtained from the web UI, API or command-line.
|
||||
@@ -43,7 +60,12 @@ spec:
|
||||
- name: runner-data
|
||||
persistentVolumeClaim:
|
||||
claimName: runner-vol
|
||||
- name: docker-data
|
||||
persistentVolumeClaim:
|
||||
claimName: docker-vol
|
||||
securityContext:
|
||||
# The dind-rootless image runs as the `rootless` user (UID/GID 1000);
|
||||
# fsGroup makes both volumes writable for it.
|
||||
fsGroup: 1000
|
||||
containers:
|
||||
- name: runner
|
||||
@@ -68,4 +90,7 @@ spec:
|
||||
volumeMounts:
|
||||
- name: runner-data
|
||||
mountPath: /data
|
||||
# The rootless daemon keeps its images here, not under /data.
|
||||
- name: docker-data
|
||||
mountPath: /home/rootless/.local/share/docker
|
||||
|
||||
|
||||
96
examples/kubernetes/statefulset-dind.yaml
Normal file
96
examples/kubernetes/statefulset-dind.yaml
Normal file
@@ -0,0 +1,96 @@
|
||||
# StatefulSet variant of the dind example.
|
||||
#
|
||||
# Unlike the Deployment, a StatefulSet gives each replica a stable identity and,
|
||||
# via volumeClaimTemplates, its own persistent volume. That means every runner
|
||||
# pod keeps its own `.runner` registration file across restarts and reschedules,
|
||||
# so it re-attaches to the server instead of trying to register again.
|
||||
apiVersion: v1
|
||||
data:
|
||||
# The registration token can be obtained from the web UI, API or command-line.
|
||||
# You can also set a pre-defined global runner registration token for the Gitea instance via
|
||||
# `GITEA_RUNNER_REGISTRATION_TOKEN`/`GITEA_RUNNER_REGISTRATION_TOKEN_FILE` environment variable.
|
||||
token: << base64 encoded registration token >>
|
||||
kind: Secret
|
||||
metadata:
|
||||
name: runner-secret
|
||||
type: Opaque
|
||||
---
|
||||
apiVersion: apps/v1
|
||||
kind: StatefulSet
|
||||
metadata:
|
||||
labels:
|
||||
app: runner
|
||||
name: runner
|
||||
spec:
|
||||
serviceName: runner
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels:
|
||||
app: runner
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app: runner
|
||||
spec:
|
||||
restartPolicy: Always
|
||||
volumes:
|
||||
- name: docker-socket
|
||||
emptyDir: {}
|
||||
initContainers:
|
||||
- name: docker
|
||||
image: docker:28.2.2-dind
|
||||
securityContext:
|
||||
privileged: true
|
||||
volumeMounts:
|
||||
- name: docker-socket
|
||||
mountPath: /var/run
|
||||
# Keeps the images pulled for jobs across restarts. Without this, the
|
||||
# daemon's data root is ephemeral and every job re-pulls its images.
|
||||
- name: docker-data
|
||||
mountPath: /var/lib/docker
|
||||
startupProbe:
|
||||
exec:
|
||||
command: ["/usr/bin/test", "-S", "/var/run/docker.sock"]
|
||||
livenessProbe:
|
||||
exec:
|
||||
command: ["/usr/bin/test", "-S", "/var/run/docker.sock"]
|
||||
restartPolicy: Always
|
||||
containers:
|
||||
- name: runner
|
||||
image: gitea/runner:nightly
|
||||
env:
|
||||
- name: GITEA_INSTANCE_URL
|
||||
value: http://gitea-http.gitea.svc.cluster.local:3000
|
||||
- name: GITEA_RUNNER_REGISTRATION_TOKEN
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: runner-secret
|
||||
key: token
|
||||
volumeMounts:
|
||||
- name: runner-data
|
||||
mountPath: /data
|
||||
- name: docker-socket
|
||||
mountPath: /var/run
|
||||
volumeClaimTemplates:
|
||||
# The runner's working directory: the .runner registration file and, optionally,
|
||||
# the config file.
|
||||
- metadata:
|
||||
name: runner-data
|
||||
spec:
|
||||
accessModes:
|
||||
- ReadWriteOnce
|
||||
resources:
|
||||
requests:
|
||||
storage: 1Gi
|
||||
storageClassName: standard
|
||||
# The Docker daemon's data root: the images pulled for jobs. Size it for the
|
||||
# images you expect to cache.
|
||||
- metadata:
|
||||
name: docker-data
|
||||
spec:
|
||||
accessModes:
|
||||
- ReadWriteOnce
|
||||
resources:
|
||||
requests:
|
||||
storage: 20Gi
|
||||
storageClassName: standard
|
||||
34
examples/systemd/README.md
Normal file
34
examples/systemd/README.md
Normal file
@@ -0,0 +1,34 @@
|
||||
# Running the runner as a systemd service
|
||||
|
||||
[`gitea-runner.service`](./gitea-runner.service) is an example unit for running
|
||||
the runner as a background service on a systemd host.
|
||||
|
||||
## Setup
|
||||
|
||||
1. Install the `gitea-runner` binary (e.g. to `/usr/local/bin/gitea-runner`).
|
||||
2. Create a dedicated user and working directory:
|
||||
|
||||
```bash
|
||||
sudo useradd --system --home-dir /var/lib/gitea-runner --create-home gitea-runner
|
||||
```
|
||||
|
||||
3. Generate a config and register the runner (as the service user), so the
|
||||
`.runner` file ends up in the working directory:
|
||||
|
||||
```bash
|
||||
sudo -u gitea-runner gitea-runner generate-config > /etc/gitea-runner/config.yaml
|
||||
cd /var/lib/gitea-runner
|
||||
sudo -u gitea-runner gitea-runner register --config /etc/gitea-runner/config.yaml
|
||||
```
|
||||
|
||||
4. Install and enable the unit:
|
||||
|
||||
```bash
|
||||
sudo cp gitea-runner.service /etc/systemd/system/gitea-runner.service
|
||||
sudo systemctl daemon-reload
|
||||
sudo systemctl enable --now gitea-runner
|
||||
```
|
||||
|
||||
Adjust the binary path, config path, working directory and user to match your
|
||||
installation. If jobs use the host's Docker daemon, uncomment the
|
||||
`docker.service` dependencies in the unit.
|
||||
30
examples/systemd/gitea-runner.service
Normal file
30
examples/systemd/gitea-runner.service
Normal file
@@ -0,0 +1,30 @@
|
||||
[Unit]
|
||||
Description=Gitea Actions runner
|
||||
Documentation=https://gitea.com/gitea/runner
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
# Uncomment when jobs use the local Docker daemon:
|
||||
# After=docker.service
|
||||
# Requires=docker.service
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
# Adjust the binary path, config path and working directory to your setup.
|
||||
# The working directory is where the .runner registration file is read from
|
||||
# unless runner.file is set to an absolute path in the config.
|
||||
ExecStart=/usr/local/bin/gitea-runner daemon --config /etc/gitea-runner/config.yaml
|
||||
WorkingDirectory=/var/lib/gitea-runner
|
||||
User=gitea-runner
|
||||
Group=gitea-runner
|
||||
|
||||
# Restart automatically so the runner survives transient failures, e.g. the
|
||||
# Gitea instance being temporarily unreachable at startup.
|
||||
Restart=on-failure
|
||||
RestartSec=5s
|
||||
|
||||
# Allow running jobs to finish before the runner is stopped. Keep this in sync
|
||||
# with runner.shutdown_timeout in the config.
|
||||
TimeoutStopSec=3h
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
11
go.mod
11
go.mod
@@ -11,7 +11,7 @@ require (
|
||||
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.6.0+incompatible
|
||||
github.com/docker/cli v29.6.1+incompatible
|
||||
github.com/docker/go-connections v0.7.0
|
||||
github.com/go-git/go-billy/v5 v5.9.0
|
||||
github.com/go-git/go-git/v5 v5.19.1
|
||||
@@ -29,6 +29,7 @@ require (
|
||||
github.com/opencontainers/selinux v1.15.1
|
||||
github.com/pkg/errors v0.9.1
|
||||
github.com/prometheus/client_golang v1.23.2
|
||||
github.com/prometheus/client_model v0.6.2
|
||||
github.com/rhysd/actionlint v1.7.12
|
||||
github.com/sirupsen/logrus v1.9.4
|
||||
github.com/spf13/cobra v1.10.2
|
||||
@@ -37,8 +38,9 @@ require (
|
||||
github.com/timshannon/bolthold v0.0.0-20240314194003-30aac6950928
|
||||
go.etcd.io/bbolt v1.5.0
|
||||
go.yaml.in/yaml/v4 v4.0.0-rc.3
|
||||
golang.org/x/sys v0.46.0
|
||||
golang.org/x/term v0.44.0
|
||||
golang.org/x/sys v0.47.0
|
||||
golang.org/x/term v0.45.0
|
||||
golang.org/x/text v0.40.0
|
||||
google.golang.org/protobuf v1.36.11
|
||||
gotest.tools/v3 v3.5.2
|
||||
tags.cncf.io/container-device-interface v1.1.0
|
||||
@@ -84,7 +86,6 @@ require (
|
||||
github.com/opencontainers/go-digest v1.0.0 // indirect
|
||||
github.com/pjbgf/sha1cd v0.6.0 // indirect
|
||||
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||
github.com/prometheus/client_model v0.6.2 // indirect
|
||||
github.com/prometheus/common v0.66.1 // indirect
|
||||
github.com/prometheus/procfs v0.17.0 // indirect
|
||||
github.com/robfig/cron/v3 v3.0.1 // indirect
|
||||
@@ -106,7 +107,7 @@ require (
|
||||
go.yaml.in/yaml/v3 v3.0.4 // indirect
|
||||
golang.org/x/crypto v0.52.0 // indirect
|
||||
golang.org/x/net v0.54.0 // indirect
|
||||
golang.org/x/sync v0.20.0 // indirect
|
||||
golang.org/x/sync v0.22.0 // indirect
|
||||
gopkg.in/warnings.v0 v0.1.2 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
)
|
||||
|
||||
24
go.sum
24
go.sum
@@ -47,10 +47,8 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
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.5.3+incompatible h1:nbEFfz774vBwQ5KRYv7c/AghjReqnGISvrRhzjV0evs=
|
||||
github.com/docker/cli v29.5.3+incompatible/go.mod h1:JLrzqnKDaYBop7H2jaqPtU4hHvMKP+vjCwu2uszcLI8=
|
||||
github.com/docker/cli v29.6.0+incompatible h1:nw9himxMMZ7eIeherJNlKQq+acnlzGgHd+4uf10QRSc=
|
||||
github.com/docker/cli v29.6.0+incompatible/go.mod h1:JLrzqnKDaYBop7H2jaqPtU4hHvMKP+vjCwu2uszcLI8=
|
||||
github.com/docker/cli v29.6.1+incompatible h1:oO7F4nn3Ovr/5TlfTUWFbMwBSS/B7Xs6Epv26gBrUP8=
|
||||
github.com/docker/cli v29.6.1+incompatible/go.mod h1:JLrzqnKDaYBop7H2jaqPtU4hHvMKP+vjCwu2uszcLI8=
|
||||
github.com/docker/docker-credential-helpers v0.9.6 h1:cT2PbRPSlnMmNTfT2TDMXRyQ1KMWHG7xoTLBcn1ZNv0=
|
||||
github.com/docker/docker-credential-helpers v0.9.6/go.mod h1:v1S+hepowrQXITkEfw6o4+BMbGot02wiKpzWhGUZK6c=
|
||||
github.com/docker/go-connections v0.7.0 h1:6SsRfJddP22WMrCkj19x9WKjEDTB+ahsdiGYf0mN39c=
|
||||
@@ -129,12 +127,8 @@ github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3N
|
||||
github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo=
|
||||
github.com/moby/go-archive v0.2.0 h1:zg5QDUM2mi0JIM9fdQZWC7U8+2ZfixfTYoHL7rWUcP8=
|
||||
github.com/moby/go-archive v0.2.0/go.mod h1:mNeivT14o8xU+5q1YnNrkQVpK+dnNe/K6fHqnTg4qPU=
|
||||
github.com/moby/moby/api v1.54.2 h1:wiat9QAhnDQjA7wk1kh/TqHz2I1uUA7M7t9SAl/JNXg=
|
||||
github.com/moby/moby/api v1.54.2/go.mod h1:+RQ6wluLwtYaTd1WnPLykIDPekkuyD/ROWQClE83pzs=
|
||||
github.com/moby/moby/api v1.55.0 h1:2/sexvQyqIWS8pRSCFddBfpW2qE7vR7FCL+vN8pxwMc=
|
||||
github.com/moby/moby/api v1.55.0/go.mod h1:+RQ6wluLwtYaTd1WnPLykIDPekkuyD/ROWQClE83pzs=
|
||||
github.com/moby/moby/client v0.4.1 h1:DMQgisVoMkmMs7fp3ROSdiBnoAu8+vo3GggFl06M/wY=
|
||||
github.com/moby/moby/client v0.4.1/go.mod h1:z52C9O2POPOsnxZAy//WtKcQ32P+jT/NGeXu/7nfjGQ=
|
||||
github.com/moby/moby/client v0.5.0 h1:5XhyPk2fuOWf6RlSFa3MkIIgDZkF25xToXW8Q/BH7cc=
|
||||
github.com/moby/moby/client v0.5.0/go.mod h1:rcVpF8ncl9vo5gaIBdol6CnbEtSj1uxMvEV/UrykF/s=
|
||||
github.com/moby/patternmatcher v0.6.1 h1:qlhtafmr6kgMIJjKJMDmMWq7WLkKIo23hsrpR3x084U=
|
||||
@@ -213,8 +207,6 @@ github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:
|
||||
github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17UxZ74=
|
||||
github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y=
|
||||
go.etcd.io/bbolt v1.3.8/go.mod h1:N9Mkw9X8x5fupy0IKsmuqVtoGDyxsaDlbk4Rd05IAQw=
|
||||
go.etcd.io/bbolt v1.4.3 h1:dEadXpI6G79deX5prL3QRNP6JB8UxVkqo4UPnHaNXJo=
|
||||
go.etcd.io/bbolt v1.4.3/go.mod h1:tKQlpPaYCVFctUIgFKFnAlvbmB3tpy1vkTnDWohtc0E=
|
||||
go.etcd.io/bbolt v1.5.0 h1:S7GAl7Fxv12yohbwFfIbQCGDWbQbtDGPET4P/bD4lxU=
|
||||
go.etcd.io/bbolt v1.5.0/go.mod h1:mkltfYE5aUHQxUct9N9V+Kp7aSjFqjgrhcXIS70Lrdk=
|
||||
go.etcd.io/gofail v0.1.0/go.mod h1:VZBCXYGZhHAinaBiiqYvuDynvahNsAyLFwB3kEHKz1M=
|
||||
@@ -250,6 +242,8 @@ golang.org/x/net v0.54.0 h1:2zJIZAxAHV/OHCDTCOHAYehQzLfSXuf/5SoL/Dv6w/w=
|
||||
golang.org/x/net v0.54.0/go.mod h1:Sj4oj8jK6XmHpBZU/zWHw3BV3abl4Kvi+Ut7cQcY+cQ=
|
||||
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
|
||||
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
|
||||
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
@@ -258,14 +252,16 @@ golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBc
|
||||
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.4.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw=
|
||||
golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
|
||||
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.44.0 h1:0rLvDRCtNj0gZkyIXhCyOb2OAzEhLVqc4B+hrsBhrmc=
|
||||
golang.org/x/term v0.44.0/go.mod h1:7ze4MdzUzLXpSAoFP1H0bOI9aXDqveSvatT5vKcFh2Y=
|
||||
golang.org/x/term v0.45.0 h1:NwWyBmoJCbfTHpxrWoZ9C6/VxOf7ic219I8xZZFdrf0=
|
||||
golang.org/x/term v0.45.0/go.mod h1:9aqxs0blBcrm/n0L9QW0aRVD+ktan8ssZromtqJC43w=
|
||||
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc=
|
||||
golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38=
|
||||
golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=
|
||||
golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
|
||||
31
internal/app/cmd/bug_report.go
Normal file
31
internal/app/cmd/bug_report.go
Normal file
@@ -0,0 +1,31 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"runtime"
|
||||
|
||||
"gitea.com/gitea/runner/internal/pkg/ver"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// loadBugReportCmd prints environment details that are useful when opening a
|
||||
// bug report, so users can paste them straight into an issue.
|
||||
func loadBugReportCmd() *cobra.Command {
|
||||
return &cobra.Command{
|
||||
Use: "bug-report",
|
||||
Short: "Print information useful when filing a bug report",
|
||||
Args: cobra.MaximumNArgs(0),
|
||||
RunE: func(cmd *cobra.Command, _ []string) error {
|
||||
w := cmd.OutOrStdout()
|
||||
fmt.Fprintf(w, "Runner version: %s\n", ver.Version())
|
||||
fmt.Fprintf(w, "Go version: %s\n", runtime.Version())
|
||||
fmt.Fprintf(w, "OS/Arch: %s/%s\n", runtime.GOOS, runtime.GOARCH)
|
||||
fmt.Fprintf(w, "NumCPU: %d\n", runtime.NumCPU())
|
||||
return nil
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -35,7 +35,8 @@ func Execute(ctx context.Context) {
|
||||
}
|
||||
registerCmd.Flags().BoolVar(®Args.NoInteractive, "no-interactive", false, "Disable interactive mode")
|
||||
registerCmd.Flags().StringVar(®Args.InstanceAddr, "instance", "", "Gitea instance address")
|
||||
registerCmd.Flags().StringVar(®Args.Token, "token", "", "Runner token")
|
||||
registerCmd.Flags().StringVar(®Args.Token, "token", "", "Runner token (or set the GITEA_RUNNER_REGISTRATION_TOKEN envvar)")
|
||||
registerCmd.Flags().StringVar(®Args.TokenFile, "token-file", "", "Path to a file containing the runner token")
|
||||
registerCmd.Flags().StringVar(®Args.RunnerName, "name", "", "Runner name")
|
||||
registerCmd.Flags().StringVar(®Args.Labels, "labels", "", "Runner tags, comma separated")
|
||||
registerCmd.Flags().BoolVar(®Args.Ephemeral, "ephemeral", false, "Configure the runner to be ephemeral and only ever be able to pick a single job (stricter than --once)")
|
||||
@@ -50,11 +51,15 @@ func Execute(ctx context.Context) {
|
||||
RunE: runDaemon(ctx, &daemArgs, &configFile),
|
||||
}
|
||||
daemonCmd.Flags().BoolVar(&daemArgs.Once, "once", false, "Run one job then exit")
|
||||
daemonCmd.Flags().StringVar(&daemArgs.Labels, "labels", os.Getenv("GITEA_RUNNER_LABELS"), "Runner labels, comma separated. Overrides the labels of an already registered runner")
|
||||
rootCmd.AddCommand(daemonCmd)
|
||||
|
||||
// ./gitea-runner exec
|
||||
rootCmd.AddCommand(loadExecCmd(ctx))
|
||||
|
||||
// ./gitea-runner bug-report
|
||||
rootCmd.AddCommand(loadBugReportCmd())
|
||||
|
||||
// ./gitea-runner config
|
||||
rootCmd.AddCommand(&cobra.Command{
|
||||
Use: "generate-config",
|
||||
|
||||
@@ -49,10 +49,7 @@ func runDaemon(ctx context.Context, daemArgs *daemonArgs, configFile *string) fu
|
||||
return fmt.Errorf("failed to load registration file: %w", err)
|
||||
}
|
||||
|
||||
lbls := reg.Labels
|
||||
if len(cfg.Runner.Labels) > 0 {
|
||||
lbls = cfg.Runner.Labels
|
||||
}
|
||||
lbls := resolveLabels(daemArgs.Labels, cfg.Runner.Labels, reg.Labels)
|
||||
|
||||
ls := labels.Labels{}
|
||||
for _, l := range lbls {
|
||||
@@ -176,7 +173,12 @@ func runDaemon(ctx context.Context, daemArgs *daemonArgs, configFile *string) fu
|
||||
} else {
|
||||
go poller.Poll()
|
||||
|
||||
<-ctx.Done()
|
||||
// Stop either on an external cancellation or when the poller shuts
|
||||
// itself down (e.g. after the runner has been unregistered).
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-poller.Done():
|
||||
}
|
||||
}
|
||||
|
||||
log.Infof("runner: %s shutdown initiated, waiting %s for running jobs to complete before shutting down", resp.Msg.Runner.Name, cfg.Runner.ShutdownTimeout)
|
||||
@@ -189,12 +191,39 @@ func runDaemon(ctx context.Context, daemArgs *daemonArgs, configFile *string) fu
|
||||
log.Warnf("runner: %s cancelled in progress jobs during shutdown", resp.Msg.Runner.Name)
|
||||
}
|
||||
|
||||
if poller.Unregistered() {
|
||||
return errors.New("runner is no longer registered with the server; please register it again")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
type daemonArgs struct {
|
||||
Once bool
|
||||
Once bool
|
||||
Labels string
|
||||
}
|
||||
|
||||
// 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 {
|
||||
return lbls
|
||||
}
|
||||
if len(cfgLabels) > 0 {
|
||||
return cfgLabels
|
||||
}
|
||||
return 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)
|
||||
}
|
||||
}
|
||||
return lbls
|
||||
}
|
||||
|
||||
// initLogging setup the global logrus logger.
|
||||
|
||||
66
internal/app/cmd/daemon_test.go
Normal file
66
internal/app/cmd/daemon_test.go
Normal file
@@ -0,0 +1,66 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"gitea.com/gitea/runner/internal/pkg/config"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestResolveLabels(t *testing.T) {
|
||||
var (
|
||||
cfgLabels = []string{"cfg:host"}
|
||||
regLabels = []string{"reg:host"}
|
||||
)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
arg string
|
||||
cfg []string
|
||||
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},
|
||||
{"blank flag is ignored", " , ", cfgLabels, regLabels, cfgLabels},
|
||||
{"nothing configured", "", nil, nil, nil},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
require.Equal(t, tt.want, resolveLabels(tt.arg, tt.cfg, tt.reg))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetDockerSocketPathUsesConfigAndEnvironment(t *testing.T) {
|
||||
got, err := getDockerSocketPath("tcp://docker.example:2376")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "tcp://docker.example:2376", got)
|
||||
|
||||
t.Setenv("DOCKER_HOST", "unix:///tmp/docker.sock")
|
||||
got, err = getDockerSocketPath("-")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "unix:///tmp/docker.sock", got)
|
||||
}
|
||||
|
||||
func TestInitLoggingSetsLevelAndCaller(t *testing.T) {
|
||||
oldLevel := log.GetLevel()
|
||||
oldReportCaller := log.StandardLogger().ReportCaller
|
||||
t.Cleanup(func() {
|
||||
log.SetLevel(oldLevel)
|
||||
log.SetReportCaller(oldReportCaller)
|
||||
})
|
||||
|
||||
cfg := &config.Config{}
|
||||
cfg.Log.Level = "debug"
|
||||
initLogging(cfg)
|
||||
|
||||
require.Equal(t, log.DebugLevel, log.GetLevel())
|
||||
require.True(t, log.StandardLogger().ReportCaller)
|
||||
}
|
||||
@@ -34,6 +34,7 @@ type executeArgs struct {
|
||||
runList bool
|
||||
job string
|
||||
event string
|
||||
eventpath string
|
||||
workdir string
|
||||
workflowsPath string
|
||||
noWorkflowRecurse bool
|
||||
@@ -441,12 +442,14 @@ func runExec(ctx context.Context, execArgs *executeArgs) func(cmd *cobra.Command
|
||||
ArtifactServerPort: execArgs.artifactServerPort,
|
||||
ArtifactServerAddr: execArgs.artifactServerAddr,
|
||||
NoSkipCheckout: execArgs.noSkipCheckout,
|
||||
EventPath: execArgs.resolve(execArgs.eventpath),
|
||||
// PresetGitHubContext: preset,
|
||||
// EventJSON: string(eventJSON),
|
||||
ContainerNamePrefix: "GITEA-ACTIONS-TASK-" + eventName,
|
||||
ContainerMaxLifetime: maxLifetime,
|
||||
ContainerNetworkMode: container.NetworkMode(execArgs.network),
|
||||
DefaultActionInstance: execArgs.defaultActionsURL,
|
||||
ContainerNamePrefix: "GITEA-ACTIONS-TASK-" + eventName,
|
||||
ContainerMaxLifetime: maxLifetime,
|
||||
ContainerNetworkMode: container.NetworkMode(execArgs.network),
|
||||
DefaultActionInstance: execArgs.defaultActionsURL,
|
||||
DefaultActionInstanceIsSelfHosted: execArgs.defaultActionsURL != "" && execArgs.defaultActionsURL != "https://github.com",
|
||||
PlatformPicker: func(_ []string) string {
|
||||
return execArgs.image
|
||||
},
|
||||
@@ -495,8 +498,9 @@ func loadExecCmd(ctx context.Context) *cobra.Command {
|
||||
}
|
||||
|
||||
execCmd.Flags().BoolVarP(&execArg.runList, "list", "l", false, "list workflows")
|
||||
execCmd.Flags().StringVarP(&execArg.job, "job", "j", "", "run a specific job ID")
|
||||
execCmd.Flags().StringVarP(&execArg.job, "job", "j", "", "run a specific job ID; when several workflow files define that job, also pass --workflows/-W to select the file")
|
||||
execCmd.Flags().StringVarP(&execArg.event, "event", "E", "", "run a event name")
|
||||
execCmd.Flags().StringVarP(&execArg.eventpath, "eventpath", "e", "", "path to a JSON event payload file exposed as the event that triggered the workflow")
|
||||
execCmd.PersistentFlags().StringVarP(&execArg.workflowsPath, "workflows", "W", "./.gitea/workflows/", "path to workflow file(s)")
|
||||
execCmd.PersistentFlags().StringVarP(&execArg.workdir, "directory", "C", ".", "working directory")
|
||||
execCmd.PersistentFlags().BoolVarP(&execArg.noWorkflowRecurse, "no-recurse", "", false, "Flag to disable running workflows from subdirectories of specified path in '--workflows'/'-W' flag")
|
||||
|
||||
220
internal/app/cmd/exec_test.go
Normal file
220
internal/app/cmd/exec_test.go
Normal file
@@ -0,0 +1,220 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"gitea.com/gitea/runner/act/model"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"go.yaml.in/yaml/v4"
|
||||
)
|
||||
|
||||
func TestExecuteArgsResolve(t *testing.T) {
|
||||
workdir := t.TempDir()
|
||||
args := &executeArgs{workdir: workdir}
|
||||
|
||||
require.Empty(t, args.resolve(""))
|
||||
require.Equal(t, filepath.Join(workdir, "sub", "file"), args.resolve("sub/file"))
|
||||
|
||||
abs := filepath.Join(workdir, "abs")
|
||||
require.Equal(t, abs, args.resolve(abs))
|
||||
}
|
||||
|
||||
func TestExecuteArgsPaths(t *testing.T) {
|
||||
workdir := t.TempDir()
|
||||
args := &executeArgs{
|
||||
workdir: workdir,
|
||||
workflowsPath: ".gitea/workflows",
|
||||
envfile: ".env",
|
||||
}
|
||||
|
||||
require.Equal(t, filepath.Join(workdir, ".gitea/workflows"), args.WorkflowsPath())
|
||||
require.Equal(t, filepath.Join(workdir, ".env"), args.Envfile())
|
||||
require.Equal(t, workdir, args.Workdir())
|
||||
}
|
||||
|
||||
func TestExecuteArgsLoadVars(t *testing.T) {
|
||||
require.Empty(t, (&executeArgs{}).LoadVars())
|
||||
|
||||
args := &executeArgs{vars: []string{"FOO=bar", "EMPTY", "WITH=eq=sign"}}
|
||||
require.Equal(t, map[string]string{
|
||||
"FOO": "bar",
|
||||
"EMPTY": "",
|
||||
"WITH": "eq=sign",
|
||||
}, args.LoadVars())
|
||||
}
|
||||
|
||||
func TestExecuteArgsLoadSecrets(t *testing.T) {
|
||||
t.Setenv("FROMENV", "from-env-value")
|
||||
|
||||
args := &executeArgs{secrets: []string{"token=abc", "fromenv"}}
|
||||
require.Equal(t, map[string]string{
|
||||
"TOKEN": "abc",
|
||||
"FROMENV": "from-env-value",
|
||||
}, args.LoadSecrets())
|
||||
}
|
||||
|
||||
func TestReadEnvs(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
envFile := filepath.Join(dir, ".env")
|
||||
require.NoError(t, os.WriteFile(envFile, []byte("FOO=bar\nBAZ=qux\n"), 0o600))
|
||||
|
||||
envs := map[string]string{"EXISTING": "keep"}
|
||||
require.True(t, readEnvs(envFile, envs))
|
||||
require.Equal(t, map[string]string{
|
||||
"EXISTING": "keep",
|
||||
"FOO": "bar",
|
||||
"BAZ": "qux",
|
||||
}, envs)
|
||||
|
||||
missing := map[string]string{}
|
||||
require.False(t, readEnvs(filepath.Join(dir, "does-not-exist"), missing))
|
||||
require.Empty(t, missing)
|
||||
}
|
||||
|
||||
func TestRunExecListUsesJobEventAndAllPlans(t *testing.T) {
|
||||
planner := &fakeWorkflowPlanner{
|
||||
events: []string{"push", "pull_request"},
|
||||
plans: map[string]*model.Plan{
|
||||
"job:build": listPlan("build", "Build", "push"),
|
||||
"event:push": listPlan("test", "Test", "push"),
|
||||
"all": listPlan("lint", "Lint", "push"),
|
||||
},
|
||||
}
|
||||
|
||||
out := captureStdout(t, func() {
|
||||
require.NoError(t, runExecList(planner, &executeArgs{job: "build"}))
|
||||
require.NoError(t, runExecList(planner, &executeArgs{event: "push"}))
|
||||
require.NoError(t, runExecList(planner, &executeArgs{autodetectEvent: true}))
|
||||
require.NoError(t, runExecList(planner, &executeArgs{}))
|
||||
})
|
||||
|
||||
require.Contains(t, out, "Build")
|
||||
require.Contains(t, out, "Test")
|
||||
require.Contains(t, out, "Lint")
|
||||
require.Equal(t, []string{"job:build", "event:push", "event:push", "all"}, planner.calls)
|
||||
}
|
||||
|
||||
func TestPrintListReportsDuplicateJobIDs(t *testing.T) {
|
||||
workflowA := workflowForList("A", "a.yml", "push", "build", "Build A")
|
||||
workflowB := workflowForList("B", "b.yml", "pull_request", "build", "Build B")
|
||||
plan := &model.Plan{Stages: []*model.Stage{{
|
||||
Runs: []*model.Run{
|
||||
{Workflow: workflowA, JobID: "build"},
|
||||
{Workflow: workflowB, JobID: "build"},
|
||||
},
|
||||
}}}
|
||||
|
||||
out := captureStdout(t, func() {
|
||||
printList(plan)
|
||||
})
|
||||
|
||||
require.Contains(t, out, "Workflow file")
|
||||
require.Contains(t, out, "Build A")
|
||||
require.Contains(t, out, "Build B")
|
||||
require.Contains(t, out, "Detected multiple jobs with the same job name")
|
||||
}
|
||||
|
||||
func TestLoadExecCmdDefinesExpectedFlags(t *testing.T) {
|
||||
cmd := loadExecCmd(context.Background())
|
||||
|
||||
for _, name := range []string{
|
||||
"list",
|
||||
"job",
|
||||
"event",
|
||||
"workflows",
|
||||
"directory",
|
||||
"env",
|
||||
"secret",
|
||||
"var",
|
||||
"dryrun",
|
||||
"image",
|
||||
"gitea-instance",
|
||||
} {
|
||||
if cmd.Flags().Lookup(name) == nil && cmd.PersistentFlags().Lookup(name) == nil {
|
||||
t.Fatalf("expected flag %q to be registered", name)
|
||||
}
|
||||
}
|
||||
|
||||
require.Equal(t, "exec", cmd.Use)
|
||||
require.NoError(t, cmd.Args(cmd, strings.Split("a b c", " ")))
|
||||
require.Error(t, cmd.Args(cmd, strings.Fields(strings.Repeat("arg ", 21))))
|
||||
}
|
||||
|
||||
type fakeWorkflowPlanner struct {
|
||||
events []string
|
||||
plans map[string]*model.Plan
|
||||
calls []string
|
||||
}
|
||||
|
||||
func (p *fakeWorkflowPlanner) PlanEvent(eventName string) (*model.Plan, error) {
|
||||
p.calls = append(p.calls, "event:"+eventName)
|
||||
return p.plans["event:"+eventName], nil
|
||||
}
|
||||
|
||||
func (p *fakeWorkflowPlanner) PlanJob(jobName string) (*model.Plan, error) {
|
||||
p.calls = append(p.calls, "job:"+jobName)
|
||||
return p.plans["job:"+jobName], nil
|
||||
}
|
||||
|
||||
func (p *fakeWorkflowPlanner) PlanAll() (*model.Plan, error) {
|
||||
p.calls = append(p.calls, "all")
|
||||
return p.plans["all"], nil
|
||||
}
|
||||
|
||||
func (p *fakeWorkflowPlanner) GetEvents() []string {
|
||||
return p.events
|
||||
}
|
||||
|
||||
func listPlan(jobID, jobName, event string) *model.Plan {
|
||||
workflow := workflowForList("Workflow "+jobID, jobID+".yml", event, jobID, jobName)
|
||||
return &model.Plan{Stages: []*model.Stage{{Runs: []*model.Run{{Workflow: workflow, JobID: jobID}}}}}
|
||||
}
|
||||
|
||||
func workflowForList(name, file, event, jobID, jobName string) *model.Workflow {
|
||||
return &model.Workflow{
|
||||
Name: name,
|
||||
File: file,
|
||||
RawOn: rawOnNode(event),
|
||||
Jobs: map[string]*model.Job{
|
||||
jobID: {Name: jobName},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func rawOnNode(event string) yaml.Node {
|
||||
var node yaml.Node
|
||||
if err := yaml.Unmarshal([]byte(event), &node); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return *node.Content[0]
|
||||
}
|
||||
|
||||
func captureStdout(t *testing.T, fn func()) string {
|
||||
t.Helper()
|
||||
|
||||
old := os.Stdout
|
||||
r, w, err := os.Pipe()
|
||||
require.NoError(t, err)
|
||||
os.Stdout = w
|
||||
|
||||
fn()
|
||||
|
||||
require.NoError(t, w.Close())
|
||||
os.Stdout = old
|
||||
|
||||
var buf bytes.Buffer
|
||||
_, err = io.Copy(&buf, r)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, r.Close())
|
||||
return buf.String()
|
||||
}
|
||||
@@ -75,6 +75,7 @@ type registerArgs struct {
|
||||
NoInteractive bool
|
||||
InstanceAddr string
|
||||
Token string
|
||||
TokenFile string
|
||||
RunnerName string
|
||||
Labels string
|
||||
Ephemeral bool
|
||||
@@ -93,6 +94,8 @@ const (
|
||||
StageExit
|
||||
)
|
||||
|
||||
const registerTokenEnvVar = "GITEA_RUNNER_REGISTRATION_TOKEN"
|
||||
|
||||
var defaultLabels = []string{
|
||||
"ubuntu-latest:docker://docker.gitea.com/runner-images:ubuntu-latest",
|
||||
"ubuntu-24.04:docker://docker.gitea.com/runner-images:ubuntu-24.04",
|
||||
@@ -207,10 +210,27 @@ func (r *registerInputs) assignToNext(stage registerStage, value string, cfg *co
|
||||
return StageUnknown
|
||||
}
|
||||
|
||||
func initInputs(regArgs *registerArgs) *registerInputs {
|
||||
func initInputs(regArgs *registerArgs) (*registerInputs, error) {
|
||||
var token string
|
||||
switch {
|
||||
case regArgs.TokenFile != "":
|
||||
tokenBytes, err := os.ReadFile(regArgs.TokenFile)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cannot read the token file: %s, %v", regArgs.TokenFile, err)
|
||||
}
|
||||
token = string(tokenBytes)
|
||||
case regArgs.Token != "":
|
||||
token = regArgs.Token
|
||||
default:
|
||||
envToken, ok := os.LookupEnv(registerTokenEnvVar)
|
||||
if !ok || envToken == "" {
|
||||
return nil, fmt.Errorf("missing token, token-file argument, or %s environment variable", registerTokenEnvVar)
|
||||
}
|
||||
token = envToken
|
||||
}
|
||||
inputs := ®isterInputs{
|
||||
InstanceAddr: regArgs.InstanceAddr,
|
||||
Token: regArgs.Token,
|
||||
Token: token,
|
||||
RunnerName: regArgs.RunnerName,
|
||||
Ephemeral: regArgs.Ephemeral,
|
||||
}
|
||||
@@ -219,7 +239,7 @@ func initInputs(regArgs *registerArgs) *registerInputs {
|
||||
if regArgs.Labels != "" {
|
||||
inputs.Labels = strings.Split(regArgs.Labels, ",")
|
||||
}
|
||||
return inputs
|
||||
return inputs, nil
|
||||
}
|
||||
|
||||
func registerInteractive(ctx context.Context, configFile string, regArgs *registerArgs) error {
|
||||
@@ -235,7 +255,10 @@ func registerInteractive(ctx context.Context, configFile string, regArgs *regist
|
||||
if f, err := os.Stat(cfg.Runner.File); err == nil && !f.IsDir() {
|
||||
stage = StageOverwriteLocalConfig
|
||||
}
|
||||
inputs := initInputs(regArgs)
|
||||
inputs, err := initInputs(regArgs)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for {
|
||||
cmdString := inputs.stageValue(stage)
|
||||
@@ -292,7 +315,10 @@ func registerNoInteractive(ctx context.Context, configFile string, regArgs *regi
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
inputs := initInputs(regArgs)
|
||||
inputs, err := initInputs(regArgs)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// specify labels in config file.
|
||||
if len(cfg.Runner.Labels) > 0 {
|
||||
if regArgs.Labels != "" {
|
||||
@@ -361,7 +387,10 @@ func doRegister(ctx context.Context, cfg *config.Config, inputs *registerInputs)
|
||||
|
||||
ls := make([]string, len(reg.Labels))
|
||||
for i, v := range reg.Labels {
|
||||
l, _ := labels.Parse(v)
|
||||
l, err := labels.Parse(v)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to parse label %q: %w", v, err)
|
||||
}
|
||||
ls[i] = l.Name
|
||||
}
|
||||
// register new runner.
|
||||
|
||||
@@ -4,16 +4,245 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"gitea.com/gitea/runner/internal/pkg/config"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"gotest.tools/v3/assert"
|
||||
)
|
||||
|
||||
func TestRegisterNonInteractiveReturnsLabelValidationError(t *testing.T) {
|
||||
err := registerNoInteractive(t.Context(), "", ®isterArgs{
|
||||
Labels: "label:invalid",
|
||||
Labels: "ubuntu:host,,broken",
|
||||
Token: "token",
|
||||
InstanceAddr: "http://localhost:3000",
|
||||
})
|
||||
assert.Error(t, err, "unsupported schema: invalid")
|
||||
assert.ErrorContains(t, err, "empty label")
|
||||
}
|
||||
|
||||
func TestRegisterInputsValidate(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
inputs registerInputs
|
||||
wantErr string
|
||||
}{
|
||||
{
|
||||
name: "empty instance address",
|
||||
inputs: registerInputs{Token: "token"},
|
||||
wantErr: "instance address is empty",
|
||||
},
|
||||
{
|
||||
name: "empty token",
|
||||
inputs: registerInputs{InstanceAddr: "http://localhost:3000"},
|
||||
wantErr: "token is empty",
|
||||
},
|
||||
{
|
||||
name: "invalid label",
|
||||
inputs: registerInputs{InstanceAddr: "http://localhost:3000", Token: "token", Labels: []string{""}},
|
||||
wantErr: "empty label",
|
||||
},
|
||||
{
|
||||
name: "valid",
|
||||
inputs: registerInputs{InstanceAddr: "http://localhost:3000", Token: "token", Labels: []string{"ubuntu:host"}},
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := tt.inputs.validate()
|
||||
if tt.wantErr != "" {
|
||||
require.EqualError(t, err, tt.wantErr)
|
||||
return
|
||||
}
|
||||
require.NoError(t, err)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateLabels(t *testing.T) {
|
||||
require.NoError(t, validateLabels([]string{"ubuntu:host", "ubuntu:docker://node:18"}))
|
||||
// a colon that is not a supported schema is part of the label name
|
||||
require.NoError(t, validateLabels([]string{"pool:e57e18d4-10d4-406f-93bf-60f127221bdd"}))
|
||||
require.Error(t, validateLabels([]string{"ubuntu:host", ""}))
|
||||
}
|
||||
|
||||
func TestRegisterInputsStageValue(t *testing.T) {
|
||||
inputs := ®isterInputs{
|
||||
InstanceAddr: "http://localhost:3000",
|
||||
Token: "token",
|
||||
RunnerName: "runner",
|
||||
Labels: []string{"ubuntu:host", "ubuntu:docker://node:18"},
|
||||
}
|
||||
require.Equal(t, "http://localhost:3000", inputs.stageValue(StageInputInstance))
|
||||
require.Equal(t, "token", inputs.stageValue(StageInputToken))
|
||||
require.Equal(t, "runner", inputs.stageValue(StageInputRunnerName))
|
||||
require.Equal(t, "ubuntu:host,ubuntu:docker://node:18", inputs.stageValue(StageInputLabels))
|
||||
require.Empty(t, (®isterInputs{}).stageValue(StageInputLabels))
|
||||
require.Empty(t, inputs.stageValue(StageWaitingForRegistration))
|
||||
}
|
||||
|
||||
func TestRegisterInputsAssignToNext(t *testing.T) {
|
||||
emptyCfg := &config.Config{}
|
||||
|
||||
t.Run("instance and token stay on empty value", func(t *testing.T) {
|
||||
inputs := ®isterInputs{}
|
||||
require.Equal(t, StageInputInstance, inputs.assignToNext(StageInputInstance, "", emptyCfg))
|
||||
require.Equal(t, StageInputToken, inputs.assignToNext(StageInputToken, "", emptyCfg))
|
||||
})
|
||||
|
||||
t.Run("instance then token then runner name", func(t *testing.T) {
|
||||
inputs := ®isterInputs{}
|
||||
require.Equal(t, StageInputToken, inputs.assignToNext(StageInputInstance, "http://localhost:3000", emptyCfg))
|
||||
require.Equal(t, "http://localhost:3000", inputs.InstanceAddr)
|
||||
require.Equal(t, StageInputRunnerName, inputs.assignToNext(StageInputToken, "token", emptyCfg))
|
||||
require.Equal(t, "token", inputs.Token)
|
||||
})
|
||||
|
||||
t.Run("empty runner name falls back to hostname", func(t *testing.T) {
|
||||
inputs := ®isterInputs{}
|
||||
require.Equal(t, StageInputLabels, inputs.assignToNext(StageInputRunnerName, "", emptyCfg))
|
||||
hostname, _ := os.Hostname()
|
||||
require.Equal(t, hostname, inputs.RunnerName)
|
||||
})
|
||||
|
||||
t.Run("labels from config skip the labels stage", func(t *testing.T) {
|
||||
cfg := &config.Config{}
|
||||
cfg.Runner.Labels = []string{"ubuntu:host", "", "pool:e57e18d4"}
|
||||
inputs := ®isterInputs{}
|
||||
require.Equal(t, StageWaitingForRegistration, inputs.assignToNext(StageInputRunnerName, "runner", cfg))
|
||||
require.Equal(t, []string{"ubuntu:host", "pool:e57e18d4"}, inputs.Labels)
|
||||
})
|
||||
|
||||
t.Run("blank labels input uses defaults", func(t *testing.T) {
|
||||
inputs := ®isterInputs{}
|
||||
require.Equal(t, StageWaitingForRegistration, inputs.assignToNext(StageInputLabels, "", emptyCfg))
|
||||
require.Equal(t, defaultLabels, inputs.Labels)
|
||||
})
|
||||
|
||||
t.Run("invalid labels input loops back", func(t *testing.T) {
|
||||
inputs := ®isterInputs{}
|
||||
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 := ®isterInputs{}
|
||||
require.Equal(t, StageWaitingForRegistration, inputs.assignToNext(StageInputLabels, "pool:e57e18d4,ubuntu:host", emptyCfg))
|
||||
require.Equal(t, []string{"pool:e57e18d4", "ubuntu:host"}, inputs.Labels)
|
||||
})
|
||||
|
||||
t.Run("overwrite local config", func(t *testing.T) {
|
||||
inputs := ®isterInputs{}
|
||||
require.Equal(t, StageInputInstance, inputs.assignToNext(StageOverwriteLocalConfig, "Y", emptyCfg))
|
||||
require.Equal(t, StageInputInstance, inputs.assignToNext(StageOverwriteLocalConfig, "y", emptyCfg))
|
||||
require.Equal(t, StageExit, inputs.assignToNext(StageOverwriteLocalConfig, "n", emptyCfg))
|
||||
})
|
||||
|
||||
t.Run("unknown stage", func(t *testing.T) {
|
||||
inputs := ®isterInputs{}
|
||||
require.Equal(t, StageUnknown, inputs.assignToNext(StageWaitingForRegistration, "x", emptyCfg))
|
||||
})
|
||||
}
|
||||
|
||||
func TestInitInputs(t *testing.T) {
|
||||
t.Run("missing token", func(t *testing.T) {
|
||||
_, err := initInputs(®isterArgs{
|
||||
InstanceAddr: "http://localhost:3000",
|
||||
RunnerName: "runner",
|
||||
Ephemeral: true,
|
||||
Labels: " ubuntu:host , ubuntu:docker://node:18 ",
|
||||
})
|
||||
require.EqualError(t, err, "missing token, token-file argument, or GITEA_RUNNER_REGISTRATION_TOKEN environment variable")
|
||||
})
|
||||
|
||||
t.Run("empty token", func(t *testing.T) {
|
||||
t.Setenv(registerTokenEnvVar, "")
|
||||
_, err := initInputs(®isterArgs{
|
||||
InstanceAddr: "http://localhost:3000",
|
||||
Token: "",
|
||||
TokenFile: "",
|
||||
RunnerName: "runner",
|
||||
Ephemeral: true,
|
||||
Labels: " ubuntu:host , ubuntu:docker://node:18 ",
|
||||
})
|
||||
require.EqualError(t, err, "missing token, token-file argument, or GITEA_RUNNER_REGISTRATION_TOKEN environment variable")
|
||||
})
|
||||
|
||||
t.Run("invalid token file", func(t *testing.T) {
|
||||
t.Setenv(registerTokenEnvVar, "from-env")
|
||||
_, err := initInputs(®isterArgs{
|
||||
InstanceAddr: "http://localhost:3000",
|
||||
TokenFile: "/tmp/nonexistent",
|
||||
RunnerName: "runner",
|
||||
Ephemeral: true,
|
||||
Labels: " ubuntu:host , ubuntu:docker://node:18 ",
|
||||
})
|
||||
require.EqualError(t, err, "cannot read the token file: /tmp/nonexistent, open /tmp/nonexistent: no such file or directory")
|
||||
})
|
||||
|
||||
t.Run("valid token", func(t *testing.T) {
|
||||
t.Setenv(registerTokenEnvVar, "from-env")
|
||||
inputs, err := initInputs(®isterArgs{
|
||||
InstanceAddr: "http://localhost:3000",
|
||||
Token: "from-plain-arg",
|
||||
RunnerName: "runner",
|
||||
Ephemeral: true,
|
||||
Labels: " ubuntu:host , ubuntu:docker://node:18 ",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "http://localhost:3000", inputs.InstanceAddr)
|
||||
require.Equal(t, "from-plain-arg", 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)
|
||||
})
|
||||
|
||||
t.Run("valid token file", func(t *testing.T) {
|
||||
t.Setenv(registerTokenEnvVar, "from-env")
|
||||
tokenFile, createErr := os.CreateTemp(t.TempDir(), "from-file")
|
||||
require.NoError(t, createErr)
|
||||
defer tokenFile.Close()
|
||||
_, writeErr := tokenFile.WriteString("from-file")
|
||||
require.NoError(t, writeErr)
|
||||
_ = tokenFile.Sync()
|
||||
|
||||
inputs, err := initInputs(®isterArgs{
|
||||
InstanceAddr: "http://localhost:3000",
|
||||
TokenFile: tokenFile.Name(),
|
||||
RunnerName: "runner",
|
||||
Ephemeral: true,
|
||||
Labels: " ubuntu:host , ubuntu:docker://node:18 ",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "http://localhost:3000", inputs.InstanceAddr)
|
||||
require.Equal(t, "from-file", 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)
|
||||
})
|
||||
|
||||
t.Run("token from environment variable", func(t *testing.T) {
|
||||
t.Setenv(registerTokenEnvVar, "from-env")
|
||||
inputs, err := initInputs(®isterArgs{
|
||||
InstanceAddr: "http://localhost:3000",
|
||||
RunnerName: "runner",
|
||||
Ephemeral: true,
|
||||
Labels: " ubuntu:host , ubuntu:docker://node:18 ",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "http://localhost:3000", inputs.InstanceAddr)
|
||||
require.Equal(t, "from-env", 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)
|
||||
})
|
||||
|
||||
t.Run("empty labels", func(t *testing.T) {
|
||||
inputs, _ := initInputs(®isterArgs{
|
||||
Token: "from-plain-arg",
|
||||
Labels: " ",
|
||||
})
|
||||
require.Nil(t, inputs.Labels)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -45,6 +45,10 @@ type Poller struct {
|
||||
shutdownJobs context.CancelFunc
|
||||
|
||||
done chan struct{}
|
||||
|
||||
// unregistered is set when the server rejects the runner with an
|
||||
// Unauthenticated response, meaning the runner is no longer registered.
|
||||
unregistered atomic.Bool
|
||||
}
|
||||
|
||||
// workerState holds the single poller's backoff state. Consecutive empty or
|
||||
@@ -137,6 +141,19 @@ func (p *Poller) PollOnce() {
|
||||
}
|
||||
}
|
||||
|
||||
// Done returns a channel that is closed once polling has fully stopped,
|
||||
// allowing callers to react when the poller shuts itself down (e.g. after the
|
||||
// runner has been unregistered) rather than only on an external cancellation.
|
||||
func (p *Poller) Done() <-chan struct{} {
|
||||
return p.done
|
||||
}
|
||||
|
||||
// Unregistered reports whether polling stopped because the server rejected the
|
||||
// runner as unregistered (an Unauthenticated response).
|
||||
func (p *Poller) Unregistered() bool {
|
||||
return p.unregistered.Load()
|
||||
}
|
||||
|
||||
func (p *Poller) runIdleMaintenance() {
|
||||
if idleRunner, ok := p.runner.(IdleRunner); ok {
|
||||
idleRunner.OnIdle(p.jobsCtx)
|
||||
@@ -264,6 +281,15 @@ func (p *Poller) fetchTask(ctx context.Context, s *workerState) (*runnerv1.Task,
|
||||
metrics.PollFetchDuration.Observe(time.Since(start).Seconds())
|
||||
|
||||
if err != nil {
|
||||
// An Unauthenticated response means the server no longer knows this
|
||||
// runner (e.g. it was deleted). Retrying forever is pointless, so stop
|
||||
// polling and let the daemon exit with an error instead of spinning.
|
||||
if connect.CodeOf(err) == connect.CodeUnauthenticated {
|
||||
log.WithError(err).Error("server rejected the runner as unregistered, stopping poller")
|
||||
p.unregistered.Store(true)
|
||||
p.shutdownPolling()
|
||||
return nil, false
|
||||
}
|
||||
log.WithError(err).Error("failed to fetch task")
|
||||
s.consecutiveErrors++
|
||||
metrics.PollFetchTotal.WithLabelValues(metrics.LabelResultError).Inc()
|
||||
|
||||
@@ -78,6 +78,35 @@ func TestPoller_FetchErrorIncrementsErrorsOnly(t *testing.T) {
|
||||
assert.Equal(t, int64(0), s.consecutiveEmpty)
|
||||
}
|
||||
|
||||
// TestPoller_FetchUnauthenticatedStopsPolling verifies that an Unauthenticated
|
||||
// response marks the runner as unregistered and cancels the polling context so
|
||||
// the daemon can exit instead of retrying forever.
|
||||
func TestPoller_FetchUnauthenticatedStopsPolling(t *testing.T) {
|
||||
client := mocks.NewClient(t)
|
||||
client.On("FetchTask", mock.Anything, mock.Anything).Return(
|
||||
func(_ context.Context, _ *connect_go.Request[runnerv1.FetchTaskRequest]) (*connect_go.Response[runnerv1.FetchTaskResponse], error) {
|
||||
return nil, connect_go.NewError(connect_go.CodeUnauthenticated, errors.New("unregistered runner"))
|
||||
},
|
||||
)
|
||||
|
||||
cfg, err := config.LoadDefault("")
|
||||
require.NoError(t, err)
|
||||
p := New(cfg, client, nil)
|
||||
|
||||
s := &workerState{}
|
||||
_, ok := p.fetchTask(context.Background(), s)
|
||||
require.False(t, ok)
|
||||
|
||||
assert.True(t, p.Unregistered(), "runner should be marked unregistered")
|
||||
assert.Equal(t, int64(0), s.consecutiveErrors, "unauthenticated must not drive error backoff")
|
||||
|
||||
select {
|
||||
case <-p.pollingCtx.Done():
|
||||
default:
|
||||
t.Fatal("expected polling context to be cancelled after an Unauthenticated response")
|
||||
}
|
||||
}
|
||||
|
||||
// TestPoller_CalculateInterval verifies the exponential backoff math is
|
||||
// correctly driven by the workerState counters.
|
||||
func TestPoller_CalculateInterval(t *testing.T) {
|
||||
|
||||
@@ -299,6 +299,15 @@ func (r *Runner) getDefaultActionsURL(task *runnerv1.Task) string {
|
||||
return giteaDefaultActionsURL
|
||||
}
|
||||
|
||||
// isSelfHostedActionsURL reports whether actions resolve to this self-hosted Gitea
|
||||
// (DEFAULT_ACTIONS_URL=self), i.e. gitea_default_actions_url is AppURL rather than
|
||||
// github.com (which may be mirror-substituted by getDefaultActionsURL). Only then may the
|
||||
// task token be attached to action clone URLs on the actions instance host.
|
||||
func (r *Runner) isSelfHostedActionsURL(task *runnerv1.Task) bool {
|
||||
giteaDefaultActionsURL := task.Context.Fields["gitea_default_actions_url"].GetStringValue()
|
||||
return giteaDefaultActionsURL != "" && giteaDefaultActionsURL != "https://github.com"
|
||||
}
|
||||
|
||||
func (r *Runner) run(ctx context.Context, task *runnerv1.Task, reporter *report.Reporter) (err error) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
@@ -436,6 +445,7 @@ func (r *Runner) run(ctx context.Context, task *runnerv1.Task, reporter *report.
|
||||
GitHubInstance: strings.TrimSuffix(r.client.Address(), "/"),
|
||||
AutoRemove: true,
|
||||
NoSkipCheckout: true,
|
||||
DisableActEnv: r.cfg.Runner.SetActEnv != nil && !*r.cfg.Runner.SetActEnv,
|
||||
PresetGitHubContext: preset,
|
||||
EventJSON: string(eventJSON),
|
||||
ContainerNamePrefix: fmt.Sprintf("GITEA-ACTIONS-TASK-%d", task.Id),
|
||||
@@ -446,14 +456,15 @@ func (r *Runner) run(ctx context.Context, task *runnerv1.Task, reporter *report.
|
||||
EnableIPv4: r.cfg.Container.NetworkCreateOptions.EnableIPv4,
|
||||
EnableIPv6: r.cfg.Container.NetworkCreateOptions.EnableIPv6,
|
||||
},
|
||||
ContainerOptions: r.cfg.Container.Options,
|
||||
ContainerDaemonSocket: r.cfg.Container.DockerHost,
|
||||
Privileged: r.cfg.Container.Privileged,
|
||||
DefaultActionInstance: r.getDefaultActionsURL(task),
|
||||
PlatformPicker: r.labels.PickPlatform,
|
||||
Vars: task.Vars,
|
||||
ValidVolumes: r.cfg.Container.ValidVolumes,
|
||||
InsecureSkipTLS: r.cfg.Runner.Insecure,
|
||||
ContainerOptions: r.cfg.Container.Options,
|
||||
ContainerDaemonSocket: r.cfg.Container.DockerHost,
|
||||
Privileged: r.cfg.Container.Privileged,
|
||||
DefaultActionInstance: r.getDefaultActionsURL(task),
|
||||
DefaultActionInstanceIsSelfHosted: r.isSelfHostedActionsURL(task),
|
||||
PlatformPicker: r.labels.PickPlatform,
|
||||
Vars: task.Vars,
|
||||
ValidVolumes: r.cfg.Container.ValidVolumes,
|
||||
InsecureSkipTLS: r.cfg.Runner.Insecure,
|
||||
}
|
||||
|
||||
rr, err := runner.New(runnerConfig)
|
||||
|
||||
104
internal/app/run/runner_test.go
Normal file
104
internal/app/run/runner_test.go
Normal file
@@ -0,0 +1,104 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package run
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
clientmocks "gitea.com/gitea/runner/internal/pkg/client/mocks"
|
||||
"gitea.com/gitea/runner/internal/pkg/config"
|
||||
"gitea.com/gitea/runner/internal/pkg/ver"
|
||||
|
||||
"connectrpc.com/connect"
|
||||
runnerv1 "gitea.dev/actions-proto-go/runner/v1"
|
||||
"github.com/stretchr/testify/mock"
|
||||
"github.com/stretchr/testify/require"
|
||||
"google.golang.org/protobuf/types/known/structpb"
|
||||
)
|
||||
|
||||
func TestRunnerCapabilitiesAndDeclare(t *testing.T) {
|
||||
require.Equal(t, []string{CapabilityCancelling}, RunnerCapabilities())
|
||||
|
||||
cli := clientmocks.NewClient(t)
|
||||
cli.On("Declare", mock.Anything, mock.MatchedBy(func(req *connect.Request[runnerv1.DeclareRequest]) bool {
|
||||
return req.Msg.Version == ver.Version() &&
|
||||
len(req.Msg.Labels) == 1 &&
|
||||
req.Msg.Labels[0] == "ubuntu" &&
|
||||
len(req.Msg.Capabilities) == 1 &&
|
||||
req.Msg.Capabilities[0] == CapabilityCancelling
|
||||
})).Return(connect.NewResponse(&runnerv1.DeclareResponse{}), nil)
|
||||
|
||||
r := &Runner{client: cli}
|
||||
_, err := r.Declare(context.Background(), []string{"ubuntu"})
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestRunnerSetCapabilitiesFromDeclare(t *testing.T) {
|
||||
r := &Runner{}
|
||||
r.SetCapabilitiesFromDeclare(nil)
|
||||
require.Empty(t, r.capabilities)
|
||||
|
||||
resp := connect.NewResponse(&runnerv1.DeclareResponse{})
|
||||
resp.Header().Set("X-Gitea-Actions-Capabilities", " cancelling,cache-v2 ")
|
||||
r.SetCapabilitiesFromDeclare(resp)
|
||||
require.Equal(t, "cancelling,cache-v2", r.capabilities)
|
||||
}
|
||||
|
||||
func TestRunnerDefaultActionsURLUsesMirrorOnlyForGithub(t *testing.T) {
|
||||
r := &Runner{cfg: &config.Config{}}
|
||||
r.cfg.Runner.GithubMirror = "https://mirror.example"
|
||||
|
||||
task := taskWithDefaultActionsURL("https://github.com")
|
||||
require.Equal(t, "https://mirror.example", r.getDefaultActionsURL(task))
|
||||
|
||||
task = taskWithDefaultActionsURL("https://gitea.example")
|
||||
require.Equal(t, "https://gitea.example", r.getDefaultActionsURL(task))
|
||||
}
|
||||
|
||||
func TestRunnerRunningCountAndNullLogger(t *testing.T) {
|
||||
r := &Runner{}
|
||||
require.Equal(t, int64(0), r.RunningCount())
|
||||
r.runningCount.Add(2)
|
||||
require.Equal(t, int64(2), r.RunningCount())
|
||||
|
||||
logger := NullLogger{}.WithJobLogger()
|
||||
require.NotNil(t, logger)
|
||||
require.NotNil(t, logger.Out)
|
||||
}
|
||||
|
||||
func TestNewRunnerInitializesLabelsAndEnvironment(t *testing.T) {
|
||||
cacheEnabled := false
|
||||
cfg := &config.Config{}
|
||||
cfg.Cache.Enabled = &cacheEnabled
|
||||
cfg.Runner.Envs = map[string]string{"EXISTING": "value"}
|
||||
reg := &config.Registration{
|
||||
Name: "runner",
|
||||
Labels: []string{"ubuntu:host", "", "pool:e57e18d4"},
|
||||
}
|
||||
cli := clientmocks.NewClient(t)
|
||||
cli.On("Address").Return("https://gitea.example/").Maybe()
|
||||
|
||||
r := NewRunner(cfg, reg, cli)
|
||||
|
||||
require.Equal(t, "runner", r.name)
|
||||
require.Len(t, r.labels, 2)
|
||||
require.Equal(t, []string{"ubuntu", "pool:e57e18d4"}, r.labels.Names())
|
||||
require.Equal(t, "value", r.envs["EXISTING"])
|
||||
require.Equal(t, "https://gitea.example/api/actions_pipeline/", r.envs["ACTIONS_RUNTIME_URL"])
|
||||
require.Equal(t, "https://gitea.example", r.envs["ACTIONS_RESULTS_URL"])
|
||||
require.Equal(t, "true", r.envs["GITEA_ACTIONS"])
|
||||
require.NotEmpty(t, r.envs["GITEA_ACTIONS_RUNNER_VERSION"])
|
||||
require.Nil(t, r.cacheHandler)
|
||||
}
|
||||
|
||||
func taskWithDefaultActionsURL(url string) *runnerv1.Task {
|
||||
return &runnerv1.Task{
|
||||
Context: &structpb.Struct{
|
||||
Fields: map[string]*structpb.Value{
|
||||
"gitea_default_actions_url": structpb.NewStringValue(url),
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,8 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gitea.com/gitea/runner/internal/pkg/ver"
|
||||
|
||||
"connectrpc.com/connect"
|
||||
"gitea.dev/actions-proto-go/ping/v1/pingv1connect"
|
||||
"gitea.dev/actions-proto-go/runner/v1/runnerv1connect"
|
||||
@@ -36,6 +38,7 @@ func New(endpoint string, insecure bool, uuid, token string, opts ...connect.Cli
|
||||
|
||||
opts = append(opts, connect.WithInterceptors(connect.UnaryInterceptorFunc(func(next connect.UnaryFunc) connect.UnaryFunc {
|
||||
return func(ctx context.Context, req connect.AnyRequest) (connect.AnyResponse, error) {
|
||||
req.Header().Set("User-Agent", "gitea-runner/"+ver.Version())
|
||||
if uuid != "" {
|
||||
req.Header().Set(UUIDHeader, uuid)
|
||||
}
|
||||
|
||||
@@ -5,8 +5,12 @@ package client
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"connectrpc.com/connect"
|
||||
pingv1 "gitea.dev/actions-proto-go/ping/v1"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
@@ -25,3 +29,67 @@ func TestGetHTTPClientUsesProxyFromEnvironment(t *testing.T) {
|
||||
require.NotNil(t, proxyURL)
|
||||
require.Equal(t, "http://proxy.example.com:8080", proxyURL.String())
|
||||
}
|
||||
|
||||
func TestGetHTTPClientInsecureTLS(t *testing.T) {
|
||||
// insecure only takes effect for https endpoints
|
||||
httpsInsecure := getHTTPClient("https://gitea.example.com", true)
|
||||
transport, ok := httpsInsecure.Transport.(*http.Transport)
|
||||
require.True(t, ok)
|
||||
require.NotNil(t, transport.TLSClientConfig)
|
||||
require.True(t, transport.TLSClientConfig.InsecureSkipVerify)
|
||||
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
endpoint string
|
||||
insecure bool
|
||||
}{
|
||||
{"https secure", "https://gitea.example.com", false},
|
||||
{"http insecure ignored", "http://gitea.example.com", true},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
c := getHTTPClient(tc.endpoint, tc.insecure)
|
||||
tr, ok := c.Transport.(*http.Transport)
|
||||
require.True(t, ok)
|
||||
require.Nil(t, tr.TLSClientConfig)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewSetsBaseURLAndHeaders(t *testing.T) {
|
||||
var gotPath string
|
||||
gotHeaders := make(http.Header)
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
gotPath = r.URL.Path
|
||||
gotHeaders = r.Header.Clone()
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
// trailing slash must be trimmed before "/api/actions" is appended
|
||||
c := New(server.URL+"/", false, "the-uuid", "the-token")
|
||||
// Address returns the endpoint as supplied (untrimmed)
|
||||
require.Equal(t, server.URL+"/", c.Address())
|
||||
require.False(t, c.Insecure())
|
||||
|
||||
// the call is expected to fail (server returns 500), we only assert what was sent
|
||||
_, _ = c.Ping(t.Context(), connect.NewRequest(&pingv1.PingRequest{Data: "hi"}))
|
||||
|
||||
require.True(t, strings.HasPrefix(gotPath, "/api/actions/"), "unexpected path %q", gotPath)
|
||||
require.Equal(t, "the-uuid", gotHeaders.Get(UUIDHeader))
|
||||
require.Equal(t, "the-token", gotHeaders.Get(TokenHeader))
|
||||
}
|
||||
|
||||
func TestNewOmitsEmptyHeaders(t *testing.T) {
|
||||
gotHeaders := make(http.Header)
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
gotHeaders = r.Header.Clone()
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
c := New(server.URL, false, "", "")
|
||||
_, _ = c.Ping(t.Context(), connect.NewRequest(&pingv1.PingRequest{Data: "hi"}))
|
||||
|
||||
require.Empty(t, gotHeaders.Get(UUIDHeader))
|
||||
require.Empty(t, gotHeaders.Get(TokenHeader))
|
||||
}
|
||||
|
||||
@@ -72,6 +72,9 @@ runner:
|
||||
# When true (the default), fetch only the requested ref of an action repository (e.g. actions/checkout@v4) at depth 1 instead of cloning every branch's full history.
|
||||
# Set to false to clone the full history.
|
||||
action_shallow_clone: true
|
||||
# When true (the default), inject the ACT=true environment variable into jobs.
|
||||
# Set to false so workflows gated on `if: ${{ !env.ACT }}` behave like they do on GitHub.
|
||||
set_act_env: true
|
||||
# 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 .
|
||||
@@ -110,6 +113,11 @@ cache:
|
||||
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.
|
||||
# If the runner itself runs in Docker, automatic detection can choose an
|
||||
# address on the runner container's network that job containers cannot reach
|
||||
# when the runner creates a separate per-job network. In that case, set this
|
||||
# to a hostname/IP reachable from job containers, and set port to a fixed
|
||||
# published port or put the job containers on a shared Docker network.
|
||||
# Ignored when external_server is set.
|
||||
host: ""
|
||||
# Port for the built-in cache server. 0 picks a random free port.
|
||||
@@ -133,6 +141,8 @@ container:
|
||||
# Specifies the network to which the container will connect.
|
||||
# Could be host, bridge or the name of a custom network.
|
||||
# If it's empty, runner will create a network automatically.
|
||||
# For dockerized runners using the built-in cache server, a custom shared
|
||||
# network can be required so job containers can reach cache.host/cache.port.
|
||||
# Deprecated: `network_mode` is still accepted for old configs; use `network` instead.
|
||||
network: ""
|
||||
# network_create_options only apply when `network` is left empty and the runner
|
||||
@@ -168,8 +178,9 @@ container:
|
||||
# If it's "-", runner will find an available docker host automatically, but the docker host won't be mounted to the job containers and service containers.
|
||||
# If it's not empty or "-", the specified docker host will be used. An error will be returned if it doesn't work.
|
||||
docker_host: ""
|
||||
# Pull docker image(s) even if already present
|
||||
force_pull: true
|
||||
# Pull docker image(s) even if already present.
|
||||
# Defaults to false when the key is omitted.
|
||||
force_pull: false
|
||||
# Rebuild docker image(s) even if already present
|
||||
force_rebuild: false
|
||||
# Always require a reachable docker daemon, even if not required by runner
|
||||
|
||||
@@ -49,6 +49,7 @@ type Runner struct {
|
||||
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 fetches only the requested ref of an action repository at depth 1 instead of cloning every branch's full history. 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.
|
||||
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.
|
||||
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.
|
||||
@@ -156,13 +157,20 @@ func LoadDefault(file string) (*Config, error) {
|
||||
b := true
|
||||
cfg.Runner.ActionShallowClone = &b
|
||||
}
|
||||
if cfg.Runner.SetActEnv == nil {
|
||||
b := true
|
||||
cfg.Runner.SetActEnv = &b
|
||||
}
|
||||
if cfg.Cache.Enabled == nil {
|
||||
b := true
|
||||
cfg.Cache.Enabled = &b
|
||||
}
|
||||
if *cfg.Cache.Enabled {
|
||||
if cfg.Cache.Dir == "" {
|
||||
home, _ := os.UserHomeDir()
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cache.dir is unset and the user home directory could not be determined: %w", err)
|
||||
}
|
||||
cfg.Cache.Dir = filepath.Join(home, ".cache", "actcache")
|
||||
}
|
||||
if cfg.Cache.ExternalServer != "" && cfg.Cache.ExternalSecret == "" {
|
||||
@@ -173,7 +181,10 @@ func LoadDefault(file string) (*Config, error) {
|
||||
cfg.Container.WorkdirParent = "workspace"
|
||||
}
|
||||
if cfg.Host.WorkdirParent == "" {
|
||||
home, _ := os.UserHomeDir()
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("host.workdir_parent is unset and the user home directory could not be determined: %w", err)
|
||||
}
|
||||
cfg.Host.WorkdirParent = filepath.Join(home, ".cache", "act")
|
||||
}
|
||||
if cfg.Runner.FetchTimeout <= 0 {
|
||||
|
||||
51
internal/pkg/config/registration_test.go
Normal file
51
internal/pkg/config/registration_test.go
Normal file
@@ -0,0 +1,51 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestSaveAndLoadRegistration(t *testing.T) {
|
||||
file := filepath.Join(t.TempDir(), ".runner")
|
||||
|
||||
reg := &Registration{
|
||||
ID: 42,
|
||||
UUID: "the-uuid",
|
||||
Name: "runner",
|
||||
Token: "the-token",
|
||||
Address: "http://localhost:3000",
|
||||
Labels: []string{"ubuntu:host", "ubuntu:docker://node:18"},
|
||||
Ephemeral: true,
|
||||
}
|
||||
|
||||
require.NoError(t, SaveRegistration(file, reg))
|
||||
// SaveRegistration stamps the warning onto the in-memory struct
|
||||
require.Equal(t, registrationWarning, reg.Warning)
|
||||
|
||||
loaded, err := LoadRegistration(file)
|
||||
require.NoError(t, err)
|
||||
|
||||
// the warning is intentionally cleared on load
|
||||
require.Empty(t, loaded.Warning)
|
||||
loaded.Warning = reg.Warning
|
||||
require.Equal(t, reg, loaded)
|
||||
}
|
||||
|
||||
func TestLoadRegistrationMissingFile(t *testing.T) {
|
||||
_, err := LoadRegistration(filepath.Join(t.TempDir(), "does-not-exist"))
|
||||
require.Error(t, err)
|
||||
}
|
||||
|
||||
func TestLoadRegistrationInvalidJSON(t *testing.T) {
|
||||
file := filepath.Join(t.TempDir(), ".runner")
|
||||
require.NoError(t, os.WriteFile(file, []byte("not json"), 0o600))
|
||||
|
||||
_, err := LoadRegistration(file)
|
||||
require.Error(t, err)
|
||||
}
|
||||
20
internal/pkg/envcheck/docker_test.go
Normal file
20
internal/pkg/envcheck/docker_test.go
Normal file
@@ -0,0 +1,20 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package envcheck
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestCheckIfDockerRunningReturnsPingError(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
|
||||
err := CheckIfDockerRunning(ctx, "unix:///definitely/missing/docker.sock")
|
||||
require.Error(t, err)
|
||||
require.Contains(t, err.Error(), "cannot ping the docker daemon")
|
||||
}
|
||||
@@ -4,7 +4,7 @@
|
||||
package labels
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"errors"
|
||||
"strings"
|
||||
)
|
||||
|
||||
@@ -17,13 +17,20 @@ type Label struct {
|
||||
Name string
|
||||
Schema string
|
||||
Arg string
|
||||
// Opaque marks a label whose name contains a colon but no supported schema,
|
||||
// like "pool:e57e18d4-...". It is kept verbatim and behaves like a host label.
|
||||
Opaque bool
|
||||
}
|
||||
|
||||
func Parse(str string) (*Label, error) {
|
||||
if str == "" {
|
||||
return nil, errors.New("empty label")
|
||||
}
|
||||
|
||||
splits := strings.SplitN(str, ":", 3)
|
||||
label := &Label{
|
||||
Name: splits[0],
|
||||
Schema: "host",
|
||||
Schema: SchemeHost,
|
||||
Arg: "",
|
||||
}
|
||||
if len(splits) >= 2 {
|
||||
@@ -33,7 +40,12 @@ func Parse(str string) (*Label, error) {
|
||||
label.Arg = splits[2]
|
||||
}
|
||||
if label.Schema != SchemeHost && label.Schema != SchemeDocker {
|
||||
return nil, fmt.Errorf("unsupported schema: %s", label.Schema)
|
||||
// Not a schema we know: the colon belongs to the label name itself.
|
||||
return &Label{
|
||||
Name: str,
|
||||
Schema: SchemeHost,
|
||||
Opaque: true,
|
||||
}, nil
|
||||
}
|
||||
return label, nil
|
||||
}
|
||||
@@ -59,7 +71,7 @@ func (l Labels) PickPlatform(runsOn []string) string {
|
||||
case SchemeHost:
|
||||
platforms[label.Name] = "-self-hosted"
|
||||
default:
|
||||
// It should not happen, because Parse has checked it.
|
||||
// unreachable: Parse only produces host or docker schemas
|
||||
continue
|
||||
}
|
||||
}
|
||||
@@ -94,7 +106,7 @@ func (l Labels) ToStrings() []string {
|
||||
ls := make([]string, 0, len(l))
|
||||
for _, label := range l {
|
||||
lbl := label.Name
|
||||
if label.Schema != "" {
|
||||
if !label.Opaque && label.Schema != "" {
|
||||
lbl += ":" + label.Schema
|
||||
if label.Arg != "" {
|
||||
lbl += ":" + label.Arg
|
||||
|
||||
@@ -44,7 +44,27 @@ func TestParse(t *testing.T) {
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
args: "ubuntu:vm:ubuntu-18.04",
|
||||
args: "pool:e57e18d4-10d4-406f-93bf-60f127221bdd",
|
||||
want: &Label{
|
||||
Name: "pool:e57e18d4-10d4-406f-93bf-60f127221bdd",
|
||||
Schema: "host",
|
||||
Arg: "",
|
||||
Opaque: true,
|
||||
},
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
args: "ubuntu:vm:ubuntu-18.04",
|
||||
want: &Label{
|
||||
Name: "ubuntu:vm:ubuntu-18.04",
|
||||
Schema: "host",
|
||||
Arg: "",
|
||||
Opaque: true,
|
||||
},
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
args: "",
|
||||
want: nil,
|
||||
wantErr: true,
|
||||
},
|
||||
@@ -61,3 +81,91 @@ func TestParse(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// mustParse parses the given label strings, failing the test on any error.
|
||||
func mustParse(t *testing.T, strs ...string) Labels {
|
||||
t.Helper()
|
||||
ls := make(Labels, 0, len(strs))
|
||||
for _, s := range strs {
|
||||
l, err := Parse(s)
|
||||
require.NoError(t, err)
|
||||
ls = append(ls, l)
|
||||
}
|
||||
return ls
|
||||
}
|
||||
|
||||
func TestRequireDocker(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
strs []string
|
||||
want bool
|
||||
}{
|
||||
{"empty", nil, false},
|
||||
{"only host", []string{"ubuntu:host", "self-hosted"}, false},
|
||||
{"has docker", []string{"ubuntu:host", "ubuntu:docker://node:18"}, true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
require.Equal(t, tt.want, mustParse(t, tt.strs...).RequireDocker())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPickPlatform(t *testing.T) {
|
||||
ls := mustParse(t,
|
||||
"ubuntu:docker://node:18",
|
||||
"self-hosted:host",
|
||||
)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
runsOn []string
|
||||
want string
|
||||
}{
|
||||
{"docker strips leading slashes", []string{"ubuntu"}, "node:18"},
|
||||
{"host maps to self-hosted marker", []string{"self-hosted"}, "-self-hosted"},
|
||||
{"first match wins", []string{"self-hosted", "ubuntu"}, "-self-hosted"},
|
||||
{"unknown falls back to default", []string{"windows"}, "docker.gitea.com/runner-images:ubuntu-latest"},
|
||||
{"no runsOn falls back to default", nil, "docker.gitea.com/runner-images:ubuntu-latest"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
require.Equal(t, tt.want, ls.PickPlatform(tt.runsOn))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNames(t *testing.T) {
|
||||
ls := mustParse(t, "ubuntu:docker://node:18", "self-hosted:host", "pool:e57e18d4")
|
||||
require.Equal(t, []string{"ubuntu", "self-hosted", "pool:e57e18d4"}, ls.Names())
|
||||
require.Empty(t, Labels{}.Names())
|
||||
}
|
||||
|
||||
func TestToStrings(t *testing.T) {
|
||||
ls := mustParse(t,
|
||||
"ubuntu:docker://node:18",
|
||||
"self-hosted:host",
|
||||
"bare",
|
||||
"pool:e57e18d4",
|
||||
)
|
||||
require.Equal(t, []string{
|
||||
"ubuntu:docker://node:18",
|
||||
"self-hosted:host",
|
||||
"bare:host",
|
||||
"pool:e57e18d4",
|
||||
}, ls.ToStrings())
|
||||
}
|
||||
|
||||
// a colon-containing name must survive a write to and read back from the .runner file
|
||||
func TestOpaqueLabelRoundTrip(t *testing.T) {
|
||||
const raw = "pool:e57e18d4-10d4-406f-93bf-60f127221bdd"
|
||||
|
||||
ls := mustParse(t, raw)
|
||||
require.Equal(t, []string{raw}, ls.ToStrings())
|
||||
|
||||
again := mustParse(t, ls.ToStrings()...)
|
||||
require.Equal(t, ls, again)
|
||||
require.Equal(t, []string{raw}, again.Names())
|
||||
require.False(t, again.RequireDocker())
|
||||
require.Equal(t, "-self-hosted", again.PickPlatform([]string{raw}))
|
||||
}
|
||||
|
||||
95
internal/pkg/metrics/metrics_test.go
Normal file
95
internal/pkg/metrics/metrics_test.go
Normal file
@@ -0,0 +1,95 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package metrics
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
runnerv1 "gitea.dev/actions-proto-go/runner/v1"
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
dto "github.com/prometheus/client_model/go"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestResultToStatusLabel(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
result runnerv1.Result
|
||||
want string
|
||||
}{
|
||||
{"success", runnerv1.Result_RESULT_SUCCESS, LabelStatusSuccess},
|
||||
{"failure", runnerv1.Result_RESULT_FAILURE, LabelStatusFailure},
|
||||
{"cancelled", runnerv1.Result_RESULT_CANCELLED, LabelStatusCancelled},
|
||||
{"skipped", runnerv1.Result_RESULT_SKIPPED, LabelStatusSkipped},
|
||||
{"unspecified", runnerv1.Result_RESULT_UNSPECIFIED, LabelStatusUnknown},
|
||||
{"out of range", runnerv1.Result(999), LabelStatusUnknown},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
require.Equal(t, tt.want, ResultToStatusLabel(tt.result))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestInitAndDynamicMetricRegistration(t *testing.T) {
|
||||
oldRegistry := Registry
|
||||
t.Cleanup(func() {
|
||||
Registry = oldRegistry
|
||||
})
|
||||
|
||||
Registry = prometheus.NewRegistry()
|
||||
initOnce = sync.Once{}
|
||||
|
||||
Init()
|
||||
Init()
|
||||
RunnerInfo.WithLabelValues("test", "runner").Set(1)
|
||||
RegisterUptimeFunc(time.Now().Add(-time.Second))
|
||||
RegisterRunningJobsFunc(func() int64 { return 2 }, 4)
|
||||
|
||||
metrics, err := Registry.Gather()
|
||||
require.NoError(t, err)
|
||||
|
||||
require.True(t, hasMetric(metrics, "gitea_runner_info"))
|
||||
require.True(t, hasMetric(metrics, "gitea_runner_uptime_seconds"))
|
||||
require.True(t, hasMetric(metrics, "gitea_runner_job_running"))
|
||||
require.True(t, hasMetric(metrics, "gitea_runner_job_capacity_utilization_ratio"))
|
||||
}
|
||||
|
||||
func TestRegisterRunningJobsFuncZeroCapacity(t *testing.T) {
|
||||
oldRegistry := Registry
|
||||
t.Cleanup(func() { Registry = oldRegistry })
|
||||
Registry = prometheus.NewRegistry()
|
||||
|
||||
RegisterRunningJobsFunc(func() int64 { return 3 }, 0)
|
||||
|
||||
metrics, err := Registry.Gather()
|
||||
require.NoError(t, err)
|
||||
for _, mf := range metrics {
|
||||
if mf.GetName() == "gitea_runner_job_capacity_utilization_ratio" {
|
||||
require.Len(t, mf.GetMetric(), 1)
|
||||
require.InDelta(t, 0, mf.GetMetric()[0].GetGauge().GetValue(), 0)
|
||||
return
|
||||
}
|
||||
}
|
||||
t.Fatal("capacity utilization metric not gathered")
|
||||
}
|
||||
|
||||
func TestStartServerCanBeCancelled(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
StartServer(ctx, "127.0.0.1:0")
|
||||
cancel()
|
||||
}
|
||||
|
||||
func hasMetric(metrics []*dto.MetricFamily, name string) bool {
|
||||
for _, mf := range metrics {
|
||||
if strings.EqualFold(mf.GetName(), name) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
23
internal/pkg/process/sysprocattr_unix_test.go
Normal file
23
internal/pkg/process/sysprocattr_unix_test.go
Normal file
@@ -0,0 +1,23 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
//go:build !windows && !plan9
|
||||
|
||||
package process
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestSysProcAttrUnixModes(t *testing.T) {
|
||||
plain := SysProcAttr("", false)
|
||||
require.True(t, plain.Setpgid)
|
||||
require.False(t, plain.Setsid)
|
||||
|
||||
tty := SysProcAttr("", true)
|
||||
require.True(t, tty.Setsid)
|
||||
require.True(t, tty.Setctty)
|
||||
require.False(t, tty.Setpgid)
|
||||
}
|
||||
36
internal/pkg/process/treekill_test.go
Normal file
36
internal/pkg/process/treekill_test.go
Normal file
@@ -0,0 +1,36 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package process
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os/exec"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestNewTreeKillConfiguresCommand(t *testing.T) {
|
||||
cmd := exec.CommandContext(context.Background(), "sleep", "1")
|
||||
tk := NewTreeKill(cmd)
|
||||
|
||||
require.NotNil(t, tk)
|
||||
require.NotNil(t, cmd.Cancel)
|
||||
require.Equal(t, treeKillWaitDelay, cmd.WaitDelay)
|
||||
require.NoError(t, cmd.Cancel())
|
||||
}
|
||||
|
||||
func TestTreeKillCaptureStoresKiller(t *testing.T) {
|
||||
cmd := exec.CommandContext(context.Background(), "sleep", "10")
|
||||
cmd.SysProcAttr = SysProcAttr("", false)
|
||||
tk := NewTreeKill(cmd)
|
||||
require.NoError(t, cmd.Start())
|
||||
defer func() { _ = cmd.Wait() }()
|
||||
|
||||
killer, err := tk.Capture(cmd.Process)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, killer)
|
||||
require.NoError(t, cmd.Cancel())
|
||||
require.NoError(t, killer.Close())
|
||||
}
|
||||
@@ -26,6 +26,12 @@ import (
|
||||
"google.golang.org/protobuf/types/known/timestamppb"
|
||||
)
|
||||
|
||||
// Size limits for the outputs reported to the server.
|
||||
const (
|
||||
maxOutputKeyLen = 255
|
||||
maxOutputValueLen = 1024 * 1024 // 1 MiB
|
||||
)
|
||||
|
||||
type Reporter struct {
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
@@ -390,13 +396,15 @@ func (r *Reporter) SetOutputs(outputs map[string]string) {
|
||||
defer r.stateMu.Unlock()
|
||||
|
||||
for k, v := range outputs {
|
||||
if len(k) > 255 {
|
||||
r.logf("ignore output because the key is too long: %q", k)
|
||||
if l := len(k); l > maxOutputKeyLen {
|
||||
log.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
|
||||
}
|
||||
if l := len(v); l > 1024*1024 {
|
||||
log.Println("ignore output because the value is too long:", k, l)
|
||||
r.logf("ignore output because the value %q is too long: %d", k, l)
|
||||
if l := len(v); l > maxOutputValueLen {
|
||||
log.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 _, ok := r.outputs.Load(k); ok {
|
||||
continue
|
||||
|
||||
@@ -983,3 +983,88 @@ func TestReporter_StopHeartbeats(t *testing.T) {
|
||||
assert.Greater(t, updateTaskCalls.Load(), beforeStop,
|
||||
"Close() must still send a final UpdateTask after StopHeartbeats")
|
||||
}
|
||||
|
||||
func TestAppendIfNotNil(t *testing.T) {
|
||||
var s []*int
|
||||
s = appendIfNotNil(s, nil)
|
||||
assert.Empty(t, s)
|
||||
|
||||
v := 7
|
||||
s = appendIfNotNil(s, &v)
|
||||
require.Len(t, s, 1)
|
||||
assert.Equal(t, &v, s[0])
|
||||
|
||||
s = appendIfNotNil(s, nil)
|
||||
require.Len(t, s, 1)
|
||||
}
|
||||
|
||||
func TestReporter_Levels(t *testing.T) {
|
||||
assert.Equal(t, log.AllLevels, (&Reporter{}).Levels())
|
||||
}
|
||||
|
||||
func TestReporter_Result(t *testing.T) {
|
||||
r := &Reporter{state: &runnerv1.TaskState{Result: runnerv1.Result_RESULT_SUCCESS}}
|
||||
assert.Equal(t, runnerv1.Result_RESULT_SUCCESS, r.Result())
|
||||
}
|
||||
|
||||
func TestReporter_SetOutputs(t *testing.T) {
|
||||
r := &Reporter{state: &runnerv1.TaskState{}}
|
||||
|
||||
r.SetOutputs(map[string]string{"foo": "bar"})
|
||||
got, ok := r.outputs.Load("foo")
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, "bar", got)
|
||||
|
||||
// first value wins: a later write to the same key is ignored
|
||||
r.SetOutputs(map[string]string{"foo": "baz"})
|
||||
got, _ = r.outputs.Load("foo")
|
||||
assert.Equal(t, "bar", got)
|
||||
|
||||
// keys longer than maxOutputKeyLen are dropped
|
||||
longKey := strings.Repeat("k", maxOutputKeyLen+1)
|
||||
r.SetOutputs(map[string]string{longKey: "v"})
|
||||
_, ok = r.outputs.Load(longKey)
|
||||
assert.False(t, ok)
|
||||
|
||||
// values longer than maxOutputValueLen are dropped
|
||||
longValue := strings.Repeat("v", maxOutputValueLen+1)
|
||||
r.SetOutputs(map[string]string{"big": longValue})
|
||||
_, ok = r.outputs.Load("big")
|
||||
assert.False(t, ok)
|
||||
|
||||
// a value at exactly the limit is still stored
|
||||
maxValue := strings.Repeat("v", maxOutputValueLen)
|
||||
r.SetOutputs(map[string]string{"atlimit": maxValue})
|
||||
got, ok = r.outputs.Load("atlimit")
|
||||
require.True(t, ok)
|
||||
assert.Len(t, got, maxOutputValueLen)
|
||||
}
|
||||
|
||||
func TestReporter_EffectiveCloseTimeout(t *testing.T) {
|
||||
assert.Equal(t, 10*time.Second, (&Reporter{}).effectiveCloseTimeout())
|
||||
assert.Equal(t, 5*time.Second, (&Reporter{closeTimeout: 5 * time.Second}).effectiveCloseTimeout())
|
||||
}
|
||||
|
||||
func TestReporter_ParseResult(t *testing.T) {
|
||||
r := &Reporter{}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
input any
|
||||
want runnerv1.Result
|
||||
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},
|
||||
{"unknown string", "bogus", runnerv1.Result_RESULT_UNSPECIFIED, false},
|
||||
{"unsupported type", 123, runnerv1.Result_RESULT_UNSPECIFIED, false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got, ok := r.parseResult(tt.input)
|
||||
assert.Equal(t, tt.wantOk, ok)
|
||||
assert.Equal(t, tt.want, got)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
13
internal/pkg/ver/version_test.go
Normal file
13
internal/pkg/ver/version_test.go
Normal file
@@ -0,0 +1,13 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package ver
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestVersion(t *testing.T) {
|
||||
// version defaults to "dev" and is overridden at build time via -ldflags
|
||||
if got := Version(); got != version {
|
||||
t.Errorf("Version() = %q, want %q", got, version)
|
||||
}
|
||||
}
|
||||
@@ -12,14 +12,18 @@ CONFIG_ARG=""
|
||||
if [[ ! -z "${CONFIG_FILE}" ]]; then
|
||||
CONFIG_ARG="--config ${CONFIG_FILE}"
|
||||
fi
|
||||
EXTRA_ARGS=""
|
||||
LABEL_ARGS=""
|
||||
if [[ ! -z "${GITEA_RUNNER_LABELS}" ]]; then
|
||||
EXTRA_ARGS="${EXTRA_ARGS} --labels ${GITEA_RUNNER_LABELS}"
|
||||
LABEL_ARGS="--labels ${GITEA_RUNNER_LABELS}"
|
||||
fi
|
||||
EXTRA_ARGS="${LABEL_ARGS}"
|
||||
if [[ ! -z "${GITEA_RUNNER_EPHEMERAL}" ]]; then
|
||||
EXTRA_ARGS="${EXTRA_ARGS} --ephemeral"
|
||||
fi
|
||||
RUN_ARGS=""
|
||||
# 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
|
||||
|
||||
162
tools/coverage-report.ts
Normal file
162
tools/coverage-report.ts
Normal file
@@ -0,0 +1,162 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
// Turns a `go test -coverprofile` file into a human-friendly Markdown report:
|
||||
// an overall total, a per-package summary sorted worst-first, and collapsible
|
||||
// per-file details for each package.
|
||||
//
|
||||
// Coverage is statement-weighted (covered statements / total statements),
|
||||
// matching `go tool cover -func`'s total, instead of naively averaging
|
||||
// per-function percentages.
|
||||
//
|
||||
// Usage: node ./tools/coverage-report.ts -i coverage.txt -o .tmp/coverage.md
|
||||
|
||||
import {readFileSync, writeFileSync} from 'node:fs';
|
||||
import {basename, dirname} from 'node:path';
|
||||
import {argv, exit, stderr} from 'node:process';
|
||||
|
||||
const modulePrefix = 'gitea.com/gitea/runner/';
|
||||
|
||||
type Counter = {
|
||||
covered: number;
|
||||
total: number;
|
||||
};
|
||||
|
||||
function percent(c: Counter): number {
|
||||
if (c.total === 0) {
|
||||
return 0;
|
||||
}
|
||||
return (c.covered / c.total) * 100;
|
||||
}
|
||||
|
||||
function addCounter(a: Counter, b: Counter): Counter {
|
||||
return {covered: a.covered + b.covered, total: a.total + b.total};
|
||||
}
|
||||
|
||||
function parseArgs(): {input: string; output: string} {
|
||||
let input = 'coverage.txt';
|
||||
let output = '.tmp/coverage.md';
|
||||
for (let i = 2; i < argv.length; i++) {
|
||||
const arg = argv[i];
|
||||
if (arg === '-i' && argv[i + 1]) {
|
||||
input = argv[++i];
|
||||
} else if (arg === '-o' && argv[i + 1]) {
|
||||
output = argv[++i];
|
||||
}
|
||||
}
|
||||
return {input, output};
|
||||
}
|
||||
|
||||
function parseProfile(name: string): Map<string, Counter> {
|
||||
const files = new Map<string, Counter>();
|
||||
const content = readFileSync(name, 'utf8');
|
||||
for (const line of content.split('\n')) {
|
||||
if (line === '' || line.startsWith('mode:')) {
|
||||
continue;
|
||||
}
|
||||
// Format: path:start.col,end.col numStmt count
|
||||
const colon = line.lastIndexOf(':');
|
||||
const fields = line.trimEnd().split(/\s+/);
|
||||
if (colon < 0 || fields.length < 3) {
|
||||
continue;
|
||||
}
|
||||
const file = line.slice(0, colon).replace(modulePrefix, '');
|
||||
const stmts = Number.parseInt(fields.at(-2)!, 10);
|
||||
const count = Number.parseInt(fields.at(-1)!, 10);
|
||||
if (Number.isNaN(stmts) || Number.isNaN(count)) {
|
||||
continue;
|
||||
}
|
||||
const c = files.get(file) ?? {covered: 0, total: 0};
|
||||
c.total += stmts;
|
||||
if (count > 0) {
|
||||
c.covered += stmts;
|
||||
}
|
||||
files.set(file, c);
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
function render(files: Map<string, Counter>): string {
|
||||
const pkgCounts = new Map<string, Counter>();
|
||||
const pkgFiles = new Map<string, string[]>();
|
||||
let total: Counter = {covered: 0, total: 0};
|
||||
|
||||
for (const [file, c] of files) {
|
||||
const pkg = dirname(file);
|
||||
pkgCounts.set(pkg, addCounter(pkgCounts.get(pkg) ?? {covered: 0, total: 0}, c));
|
||||
const names = pkgFiles.get(pkg) ?? [];
|
||||
names.push(file);
|
||||
pkgFiles.set(pkg, names);
|
||||
total = addCounter(total, c);
|
||||
}
|
||||
|
||||
const pkgs = [...pkgCounts.keys()];
|
||||
pkgs.sort((a, b) => {
|
||||
const ci = pkgCounts.get(a)!;
|
||||
const cj = pkgCounts.get(b)!;
|
||||
const pi = percent(ci);
|
||||
const pj = percent(cj);
|
||||
if (pi !== pj) {
|
||||
return pi - pj;
|
||||
}
|
||||
if (ci.total !== cj.total) {
|
||||
return cj.total - ci.total;
|
||||
}
|
||||
return a.localeCompare(b);
|
||||
});
|
||||
|
||||
const lines: string[] = [];
|
||||
lines.push('# Coverage\n');
|
||||
lines.push(
|
||||
`**Total: ${percent(total).toFixed(1)}%** · ${total.covered} / ${total.total} statements covered · ${pkgs.length} packages\n`,
|
||||
);
|
||||
|
||||
lines.push('## Packages\n');
|
||||
lines.push('| Package | Coverage | Statements |');
|
||||
lines.push('|---------|---------:|-----------:|');
|
||||
for (const pkg of pkgs) {
|
||||
const c = pkgCounts.get(pkg)!;
|
||||
lines.push(`| ${pkg} | ${percent(c).toFixed(1)}% | ${c.covered} / ${c.total} |`);
|
||||
}
|
||||
lines.push('');
|
||||
|
||||
lines.push('## Files\n');
|
||||
for (const pkg of pkgs) {
|
||||
const c = pkgCounts.get(pkg)!;
|
||||
const names = [...(pkgFiles.get(pkg) ?? [])];
|
||||
names.sort((a, b) => {
|
||||
const ci = files.get(a)!;
|
||||
const cj = files.get(b)!;
|
||||
const pi = percent(ci);
|
||||
const pj = percent(cj);
|
||||
if (pi !== pj) {
|
||||
return pi - pj;
|
||||
}
|
||||
return a.localeCompare(b);
|
||||
});
|
||||
lines.push(
|
||||
`<details><summary><strong>${pkg}</strong> — ${percent(c).toFixed(1)}% (${c.covered}/${c.total})</summary>\n`,
|
||||
);
|
||||
lines.push('| File | Coverage | Statements |');
|
||||
lines.push('|------|---------:|-----------:|');
|
||||
for (const file of names) {
|
||||
const fc = files.get(file)!;
|
||||
lines.push(`| ${basename(file)} | ${percent(fc).toFixed(1)}% | ${fc.covered} / ${fc.total} |`);
|
||||
}
|
||||
lines.push('\n</details>\n');
|
||||
}
|
||||
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
function main(): void {
|
||||
const {input, output} = parseArgs();
|
||||
try {
|
||||
const files = parseProfile(input);
|
||||
writeFileSync(output, render(files), {mode: 0o644});
|
||||
} catch (err) {
|
||||
stderr.write(`coverage-report: ${err}\n`);
|
||||
exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
Reference in New Issue
Block a user