enhance: run JavaScript actions on a pinned Node.js (#1400)

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

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

_Written by Claude (Opus 5.5)._
Co-authored-by: silverwind <me@silverwind.io>
Co-authored-by: silverwind <2021+silverwind@noreply.gitea.com>
Reviewed-on: https://gitea.com/gitea/runner/pulls/1400
Reviewed-by: silverwind <2021+silverwind@noreply.gitea.com>
This commit is contained in:
bircni
2026-11-27 16:31:36 +00:00
parent 03bb09a656
commit a8d0d8a7e0
28 changed files with 883 additions and 44 deletions

View File

@@ -14,7 +14,6 @@ Gitea Runner runs the jobs of Gitea Actions workflows. Register it with a Gitea
In the job image, or on the host for host jobs:
- `bash` or `sh`, or `pwsh` or `powershell` on Windows.
- `node` for JavaScript actions and `hashFiles()`.
Kubernetes mode needs [a few more tools](docs/kubernetes.md) in job images.
@@ -323,6 +322,13 @@ A regex must match the whole `uses`, and the replacement can insert its capture
Secrets and `::add-mask::` values are hidden in job logs, [local job logs](#local-job-logs-logjobdir), job summaries and container names. As on GitHub, a job output containing one is dropped with a warning.
### Node.js
JavaScript actions and `hashFiles()` run on either:
- Node.js 24, downloaded by the runner from nodejs.org (or `NODEJS_ORG_MIRROR`), and from GitHub for Alpine. `runner.node_version` can be used to use a different version. If the download fails or doesn't run in the job's image, the `node` on `PATH` is used.
- The `node` on `PATH`, with `runner.node_download: false`.
## Operation
### Idle cleanup

View File

@@ -145,6 +145,47 @@ func (cr *containerReference) CopyDir(destPath, srcPath string, useGitIgnore, sk
).IfNot(common.Dryrun)
}
// SeedVolume writes volume unless it already holds marker, so a seeded volume is never rewritten under running jobs, and prunes old volumes named prefix*.
func (cr *containerReference) SeedVolume(volume, prefix, marker string, write func(io.Writer) error) common.Executor {
return cr.connect().Then(func(ctx context.Context) (err error) {
platform, err := cr.containerPlatform(ctx)
if err != nil {
return err
}
const seedPath = "/gitea-runner-volume-seed"
created, err := cr.cli.ContainerCreate(ctx, client.ContainerCreateOptions{
Platform: platform,
Config: &container.Config{Image: cr.input.Image, Cmd: []string{"true"}},
HostConfig: &container.HostConfig{
NetworkMode: "none",
Mounts: []mount.Mount{{
Type: mount.TypeVolume,
Source: volume,
Target: seedPath,
VolumeOptions: &mount.VolumeOptions{NoCopy: true},
}},
},
})
if err != nil {
return fmt.Errorf("failed to create volume seed container: %w", err)
}
helper := &containerReference{cli: cr.cli, id: created.ID}
defer func() { err = errors.Join(err, helper.remove()(context.WithoutCancel(ctx))) }()
if _, err := cr.cli.ContainerStatPath(ctx, helper.id, client.ContainerStatPathOptions{Path: seedPath + "/" + marker}); err == nil {
return nil
}
reader, writer := io.Pipe()
defer reader.Close()
go func() { writer.CloseWithError(write(writer)) }()
if err := helper.upload(ctx, seedPath, reader); err != nil {
return err
}
pruneSeedVolumes(ctx, cr.cli, volume, prefix, time.Now().Add(-7*24*time.Hour))
return nil
}).IfNot(common.Dryrun)
}
func (cr *containerReference) GetContainerArchive(ctx context.Context, srcPath string) (io.ReadCloser, error) {
if common.Dryrun(ctx) {
return nil, errors.New("DRYRUN is not supported in GetContainerArchive")
@@ -720,18 +761,9 @@ func (cr *containerReference) create(capAdd, capDrop []string) common.Executor {
})
}
var platSpecs *specs.Platform
if cr.input.Platform != "" {
// Dropping the platform silently would build for the host arch.
supported, err := supportsContainerImagePlatform(ctx, cr.cli)
if err != nil {
return err
}
if supported {
if platSpecs, err = parsePlatform(cr.input.Platform); err != nil {
return err
}
}
platform, err := cr.containerPlatform(ctx)
if err != nil {
return err
}
hostConfig := &container.HostConfig{
@@ -770,7 +802,7 @@ func (cr *containerReference) create(capAdd, capDrop []string) common.Executor {
Config: config,
HostConfig: hostConfig,
NetworkingConfig: networkingConfig,
Platform: platSpecs,
Platform: platform,
Name: input.Name,
})
if err != nil {
@@ -785,6 +817,21 @@ func (cr *containerReference) create(capAdd, capDrop []string) common.Executor {
}
}
func (cr *containerReference) containerPlatform(ctx context.Context) (*specs.Platform, error) {
platform := cr.input.Platform
if platform != "" {
// Dropping the platform silently would build for the host arch.
supported, err := supportsContainerImagePlatform(ctx, cr.cli)
if err != nil {
return nil, err
}
if !supported {
platform = ""
}
}
return parsePlatform(platform)
}
func (cr *containerReference) exec(cmd []string, env map[string]string, user, workdir string) common.Executor {
return func(ctx context.Context) error {
if cr.id == "" {

View File

@@ -11,6 +11,7 @@ import (
"bufio"
"bytes"
"context"
"crypto/rand"
"encoding/binary"
"errors"
"io"
@@ -23,6 +24,7 @@ import (
"sync"
"sync/atomic"
"testing"
"time"
"gitea.com/gitea/runner/act/common"
"gitea.com/gitea/runner/act/common/logging"
@@ -71,6 +73,58 @@ func TestDockerEnvironmentUsesContainerPath(t *testing.T) {
client.AssertExpectations(t)
}
func TestDockerSeedVolume(t *testing.T) {
requireDocker(t)
ctx := t.Context()
cleanupCtx := context.WithoutCancel(ctx)
require.NoError(t, NewDockerPullExecutor(NewDockerPullExecutorInput{Image: "alpine"})(ctx))
cr := &containerReference{input: &NewContainerInput{Image: "alpine"}}
require.NoError(t, cr.connect()(ctx))
t.Cleanup(func() { assert.NoError(t, cr.Close()(cleanupCtx)) })
prefix := "node-seed-test-" + strings.ToLower(rand.Text()) + "-"
volume, oldVolume := prefix+"current", prefix+"old"
t.Cleanup(func() {
assert.NoError(t, NewDockerVolumeRemoveExecutor(volume, false)(cleanupCtx))
assert.NoError(t, NewDockerVolumeRemoveExecutor(oldVolume, false)(cleanupCtx))
})
_, err := cr.cli.VolumeCreate(ctx, mobyclient.VolumeCreateOptions{Name: oldVolume})
require.NoError(t, err)
for _, body := range []string{"seeded", "reseeded"} {
require.NoError(t, cr.SeedVolume(volume, prefix, "node", func(out io.Writer) error {
return writeFilesTar(ctx, out, 0, 0, &FileEntry{Name: "node", Mode: 0o755, Body: body})
})(ctx))
}
_, err = cr.cli.VolumeInspect(ctx, oldVolume, mobyclient.VolumeInspectOptions{})
require.NoError(t, err)
pruneSeedVolumes(ctx, cr.cli, volume, prefix, time.Now().Add(time.Minute))
_, err = cr.cli.VolumeInspect(ctx, oldVolume, mobyclient.VolumeInspectOptions{})
require.ErrorIs(t, err, cerrdefs.ErrNotFound)
readback, err := cr.cli.ContainerCreate(ctx, mobyclient.ContainerCreateOptions{
Config: &container.Config{Image: "alpine"},
HostConfig: &container.HostConfig{
NetworkMode: "none",
Mounts: []mount.Mount{{Type: mount.TypeVolume, Source: volume, Target: "/readback", ReadOnly: true}},
},
})
require.NoError(t, err)
t.Cleanup(func() {
_, err := cr.cli.ContainerRemove(cleanupCtx, readback.ID, mobyclient.ContainerRemoveOptions{RemoveVolumes: true})
assert.NoError(t, err)
})
archive, err := cr.cli.CopyFromContainer(ctx, readback.ID, mobyclient.CopyFromContainerOptions{SourcePath: "/readback/node"})
require.NoError(t, err)
defer archive.Content.Close()
reader := tar.NewReader(archive.Content)
_, err = reader.Next()
require.NoError(t, err)
content, err := io.ReadAll(reader)
require.NoError(t, err)
assert.Equal(t, "seeded", string(content))
}
type mockDockerClient struct {
mobyclient.APIClient
mock.Mock

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -205,7 +205,7 @@ func runActionScript(ctx context.Context, step actionStep, actionDir, script str
env := step.getEnv()
rc.ApplyExtraPath(ctx, env)
if step.getActionModel().Runs.Using.IsNode() {
args := nodeActionCommand(container.JoinPath(actionDir, script))
args := nodeActionCommand(rc.node(ctx), container.JoinPath(actionDir, script))
common.Logger(ctx).Debugf("executing remote job container: %s", args)
return rc.JobContainer.Exec(args, *env, "", "")(ctx)
}
@@ -217,8 +217,8 @@ func runActionScript(ctx context.Context, step actionStep, actionDir, script str
}
// /var/run is a symlink, so without the flag node's import.meta.url differs from argv[1], which ESM actions compare.
func nodeActionCommand(script string) []string {
return []string{"node", "--preserve-symlinks-main", script}
func nodeActionCommand(node, script string) []string {
return []string{node, "--preserve-symlinks-main", script}
}
// dockerActionImageTag derives the local docker image tag used when an action

View File

@@ -168,7 +168,7 @@ func TestActionRunner(t *testing.T) {
cm.On("CopyDir", containerActionDir, "dir/", false, true).Return(noopExecutor)
for _, script := range []string{"path/pre.js", "path/main.js", "path/post.js"} {
cm.On("Exec", nodeActionCommand(containerActionDir+script), mock.Anything, "", "").Return(noopExecutor).Once().Run(func(args mock.Arguments) {
cm.On("Exec", nodeActionCommand("node", containerActionDir+script), mock.Anything, "", "").Return(noopExecutor).Once().Run(func(args mock.Arguments) {
env := args.Get(1).(map[string]string)
for key, value := range tt.expectedEnv {
if script == "path/pre.js" && strings.HasPrefix(key, "STATE_") {
@@ -271,7 +271,7 @@ if (process.argv[1] !== self) {
require.NoError(t, os.Symlink(actionDir, symlinkedActionDir))
symlinkedEntrypoint := filepath.Join(symlinkedActionDir, "index.mjs")
args := nodeActionCommand(symlinkedEntrypoint)
args := nodeActionCommand("node", symlinkedEntrypoint)
output, err := exec.CommandContext(t.Context(), args[0], args[1:]...).CombinedOutput()
require.NoError(t, err, "%s", output)
}

View File

@@ -50,6 +50,7 @@ func TestDockerProxyMountedJob(t *testing.T) {
ContainerDaemonSocket: dockerClient.DaemonHost(),
ContainerMaxLifetime: 2 * time.Minute,
Sweep: true,
NoNodeDownload: true,
ContainerOptions: "-v /usr/local/bin/docker:/usr/local/bin/docker:ro -v /usr/local/libexec/docker/cli-plugins:/usr/local/libexec/docker/cli-plugins:ro",
ValidVolumes: []string{"/usr/local/bin/docker", "/usr/local/libexec/docker/cli-plugins"},
Env: map[string]string{"PROXY_TEST_RESOURCE": resourceName, "PROXY_TEST_MODE": mode, "PROXY_TEST_IMAGE": baseImage, "COMPOSE_PROJECT_NAME": resourceName},

View File

@@ -85,8 +85,6 @@ func newActionInputsExpressionEvaluator(inputs map[string]string) *ExpressionEva
func getHashFilesFunction(ctx context.Context, rc *RunContext) func(v []reflect.Value) (any, error) {
return func(v []reflect.Value) (any, error) {
if rc.JobContainer != nil {
timeoutCtx, cancel := context.WithTimeout(ctx, 120*time.Second)
defer cancel()
name := "workflow/hashfiles/index.js"
hout := &bytes.Buffer{}
herr := &bytes.Buffer{}
@@ -110,6 +108,9 @@ func getHashFilesFunction(ctx context.Context, rc *RunContext) func(v []reflect.
if followSymlink {
env["followSymbolicLinks"] = "true"
}
node := rc.node(ctx)
timeoutCtx, cancel := context.WithTimeout(ctx, 120*time.Second)
defer cancel()
stdout, stderr := rc.JobContainer.ReplaceLogWriter(hout, herr)
defer rc.JobContainer.ReplaceLogWriter(stdout, stderr)
@@ -117,7 +118,7 @@ func getHashFilesFunction(ctx context.Context, rc *RunContext) func(v []reflect.
Name: name,
Mode: 0o644,
Body: hashfiles,
}).Then(rc.JobContainer.Exec([]string{"node", container.JoinPath(rc.JobContainer.GetActPath(), name)}, env, "", ""))(timeoutCtx)
}).Then(rc.JobContainer.Exec([]string{node, container.JoinPath(rc.JobContainer.GetActPath(), name)}, env, "", ""))(timeoutCtx)
switch {
case err == nil:
case ctx.Err() != nil:

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

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

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

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

View File

@@ -91,6 +91,7 @@ type RunContext struct {
jobEnv map[string]string // workflow and job env as evaluated for the container and service specs
dockerActionImages map[*model.Step]string // Dockerfile action images built for this job, removed when it ends
actionDownloads map[string]*actionDownload // remote action repositories by clone URL and ref, fetched once per job
nodePath string
// summaryFileInitialized tracks which per-step summary files (workflow/step-summary-N.md)
// have already been created on the JobContainer. The runner sets up file-command files
@@ -266,6 +267,9 @@ func (rc *RunContext) validVolumes() []string {
volumes = append(volumes, rc.dockerProxy.Socket)
}
volumes = append(volumes, rc.Config.containerVolumeSources()...)
if !rc.Config.NoNodeDownload {
volumes = append(volumes, rc.Config.nodeVolume()+":ro")
}
// TODO: add a new configuration to control whether the docker daemon can be mounted
return append(volumes, name, name+"-env",
getDockerDaemonSocketMountPath(rc.containerDaemonSocket()))
@@ -686,6 +690,9 @@ func (rc *RunContext) startJobContainer() common.Executor {
rc.startDockerProxy(ctx)
var taskWorkspace string
containerInput.Binds, containerInput.Mounts, taskWorkspace = rc.GetBindsAndMounts(ctx)
if !rc.Config.NoNodeDownload {
containerInput.Binds = append(containerInput.Binds, rc.Config.nodeVolume()+":"+ext.GetActPath()+"/node:ro,nocopy")
}
containerInput.ValidVolumes = rc.validVolumes()
rc.jobNetworkName = networkName

View File

@@ -85,6 +85,8 @@ type Config struct {
JobLoggerLevel *logging.Level // the level of job logger
ValidVolumes []string // only volumes (and bind mounts) in this slice can be mounted on the job container or service containers
ContainerVolumes []string // mounted into every job, service and docker action container
NoNodeDownload bool // run JavaScript actions and hashFiles with the node on PATH, never one the runner downloads
NodeVersion string // the Node.js version to download instead of the pinned one, checked against its published SHA-256
SharedToolCache bool // keeps the tool cache across jobs instead of one per job
ToolCacheSlot string // keeps concurrent tasks' tool caches apart, empty for slot 0 and in exec
StableHostWorkdir bool // host jobs run at a stable path per repository, see HostEnvironment.UseWorkspace

View File

@@ -341,7 +341,7 @@ func TestRunEvent(t *testing.T) {
{workdir, "local-action-docker-url", "push", "", platforms, secrets},
{workdir, "local-action-dockerfile", "push", "", platforms, secrets},
{workdir, "local-action-via-composite-dockerfile", "push", "", platforms, secrets},
{workdir, "local-action-js", "push", "", platforms, secrets},
{workdir, "local-action-js", "push", "", map[string]string{"ubuntu-latest": "ubuntu:24.04"}, secrets},
// Uses
{workdir, "uses-composite", "push", "", platforms, secrets},

View File

@@ -236,8 +236,8 @@ func TestStepActionRemotePreCleanup(t *testing.T) {
_, actionDir := getContainerActionPaths(sar)
expectStepFileCommands(t, cm)
cm.On("CopyDir", actionDir+"/", sar.actionDir+"/", false, true).Return(noopExecutor)
cm.On("Exec", nodeActionCommand(path.Join(actionDir, "pre.js")), mock.Anything, "", "").Return(func(_ctx context.Context) error { return test.preError }).Once()
cm.On("Exec", nodeActionCommand(path.Join(actionDir, "post.js")), mock.Anything, "", "").Return(noopExecutor).Once()
cm.On("Exec", nodeActionCommand("node", path.Join(actionDir, "pre.js")), mock.Anything, "", "").Return(func(_ctx context.Context) error { return test.preError }).Once()
cm.On("Exec", nodeActionCommand("node", path.Join(actionDir, "post.js")), mock.Anything, "", "").Return(noopExecutor).Once()
}
assert.Equal(t, test.preError, sar.pre()(t.Context()))

View File

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

View File

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

View File

@@ -19,6 +19,7 @@ import (
"time"
"gitea.com/gitea/runner/act/common/logging"
actrunner "gitea.com/gitea/runner/act/runner"
"gitea.com/gitea/runner/internal/app/poll"
"gitea.com/gitea/runner/internal/app/run"
"gitea.com/gitea/runner/internal/pkg/client"
@@ -180,6 +181,12 @@ func runDaemon(ctx context.Context, daemArgs *daemonArgs, configFile *string) fu
cfg.Runner.ExtraHeaders,
)
if cfg.Runner.NodeDownload == nil || *cfg.Runner.NodeDownload {
has := func(scheme string) bool {
return slices.ContainsFunc(ls, func(label *labels.Label) bool { return label.Schema == scheme })
}
actrunner.PrefetchNode(filepath.FromSlash(cfg.Host.WorkdirParent), cfg.Runner.NodeVersion, has(labels.SchemeHost), has(labels.SchemeDocker), has(labels.SchemeKubernetes))
}
runner := run.NewRunner(cfg, reg, cli)
defer func() {
if err := runner.Close(); err != nil {

View File

@@ -131,7 +131,7 @@ func TestDaemonRetriesDeclareOutagesAndRemovesOnlyConsumedEphemeralRegistration(
dir := t.TempDir()
regFile := filepath.Join(dir, "registration.json")
configFile := filepath.Join(dir, "config.yaml")
require.NoError(t, os.WriteFile(configFile, []byte("runner:\n file: "+regFile+"\n idle_cleanup_interval: 0s\ncache:\n enabled: false\n"), 0o600))
require.NoError(t, os.WriteFile(configFile, []byte("runner:\n file: "+regFile+"\n idle_cleanup_interval: 0s\n node_download: false\ncache:\n enabled: false\n"), 0o600))
for _, tc := range []struct {
name string

View File

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

View File

@@ -636,6 +636,8 @@ func (r *Runner) run(ctx context.Context, task *runnerv1.Task, reporter *report.
Vars: task.Vars,
ValidVolumes: r.cfg.Container.ValidVolumes,
ContainerVolumes: r.cfg.Container.Volumes,
NoNodeDownload: r.cfg.Runner.NodeDownload != nil && !*r.cfg.Runner.NodeDownload,
NodeVersion: r.cfg.Runner.NodeVersion,
SharedToolCache: r.cfg.Runner.ToolCacheMode == config.ToolCacheModeShared,
ToolCacheSlot: toolCacheSlot(r.cfg.Runner.ToolCacheMode, slot),
StableHostWorkdir: r.cfg.Host.StableWorkdir,

View File

@@ -123,6 +123,10 @@ runner:
# written for GitHub work against this instance. Set to false to run them exactly as published,
# at the price of the stock artifact actions refusing and the cache client keeping to v1.
#patch_actions: true
# Whether to download Node.js for JavaScript actions and hashFiles(). False uses the node on PATH.
#node_download: true
# The Node.js version to download, instead of the runner's default.
#node_version: 24.21.0
# The labels of a runner are used to determine which jobs the runner can run, and how to run them.
# Like: "macos-arm64:host" or "ubuntu-latest:docker://docker.gitea.com/runner-images:ubuntu-latest"
# Find more images provided by Gitea at https://gitea.com/gitea/runner-images .

View File

@@ -40,6 +40,8 @@ const DefaultPostTaskScriptTimeout = 5 * time.Minute
var environmentReference = regexp.MustCompile(`\$?\$\{[A-Za-z_][A-Za-z0-9_]*\}`)
var nodeVersionPattern = regexp.MustCompile(`^[0-9]+\.[0-9]+\.[0-9]+$`)
// Minimal is the smallest config file that runs the runner: options it does not
// name keep their default, and it names none.
const Minimal = `# Minimal config file. Every option it does not set keeps its default.
@@ -88,6 +90,8 @@ type Runner struct {
ActionReplacements []ActionReplacement `yaml:"action_replacements"` // ActionReplacements rewrite the `uses` of steps, see ReplaceUses.
ActionShallowClone *bool `yaml:"action_shallow_clone"` // ActionShallowClone clones only the requested ref at depth 1 instead of every branch's full history, for reusable workflows and actions without an archive. It is a pointer to distinguish between false and not set; if not set, it defaults to true.
SetActEnv *bool `yaml:"set_act_env"` // SetActEnv controls whether the ACT=true environment variable is injected into jobs. It is a pointer to distinguish between false and not set; if not set, it defaults to true. Set it to false so workflows gated on `if: ${{ !env.ACT }}` behave like on GitHub.
NodeDownload *bool `yaml:"node_download"` // NodeDownload sets whether to download Node.js for JavaScript actions and hashFiles(). Unset means true, false uses the node on PATH.
NodeVersion string `yaml:"node_version"` // NodeVersion is an exact Node.js version to download instead of the pinned one, checked against its published SHA-256.
PatchActions *bool `yaml:"patch_actions"` // PatchActions applies compatibility patches to the actions a job runs, so actions written for GitHub work against Gitea, see act/runner/patch_actions.go. It is a pointer to distinguish between false and not set; if not set, it defaults to true. Set it to false to run every action exactly as published, at the price of the artifact actions refusing.
AllocatePTY bool `yaml:"allocate_pty"` // AllocatePTY allocates a pseudo-TTY for each step's process. Default is false, matching GitHub's actions/runner. Enable only for jobs that need an interactive terminal; tools like docker build emit redrawing progress frames into the captured log when a TTY is present. Applies to both host and docker backends.
DefaultImage string `yaml:"default_image"` // DefaultImage is the image a job runs in when its runs-on matches none of the runner's labels. A runner without docker runs such a job on the host instead.
@@ -407,6 +411,9 @@ func LoadDefault(file string) (*Config, error) {
if cfg.Runner.ToolCacheMode == "" {
cfg.Runner.ToolCacheMode = ToolCacheModeNone
}
if cfg.Runner.NodeVersion != "" && !nodeVersionPattern.MatchString(cfg.Runner.NodeVersion) {
return nil, fmt.Errorf("invalid runner.node_version %q: must be an exact version like 24.22.3", cfg.Runner.NodeVersion)
}
if !slices.Contains(ToolCacheModes, cfg.Runner.ToolCacheMode) {
return nil, fmt.Errorf("invalid runner.tool_cache_mode %q: must be one of %q", cfg.Runner.ToolCacheMode, ToolCacheModes)
}

View File

@@ -184,6 +184,17 @@ func TestLoadDefault_ToolCacheMode(t *testing.T) {
assert.Contains(t, err.Error(), "tool_cache_mode")
}
func TestLoadDefault_NodeVersion(t *testing.T) {
path := write(t, "runner:\n node_version: 24.21.0\n")
cfg, err := LoadDefault(path)
require.NoError(t, err)
assert.Equal(t, "24.21.0", cfg.Runner.NodeVersion)
require.NoError(t, os.WriteFile(path, []byte("runner:\n node_version: \"24\"\n"), 0o600))
_, err = LoadDefault(path)
require.ErrorContains(t, err, "node_version")
}
func TestLoadDefault_KubernetesTransferMode(t *testing.T) {
cfg, err := LoadDefault(write(t, "kubernetes:\n transfer:\n host: 10.0.0.5\n"))
require.NoError(t, err)

View File

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