mirror of
https://gitea.com/gitea/runner.git
synced 2026-08-21 11:27:45 +00:00
fix: stop a failed step disabling the toolkit patch (#1177)
A step that failed, for any reason, made the runner restore the action's stock bundle and mark it never to be patched again. Every later `actions/upload-artifact` run then failed with `GHESNotSupportedError`, and nothing in the log said why. The edit is now made as the action is copied into the job container, under the lock that guards the copy, and nothing reverts it. That also closes the race where another job's checkout reset the bundle mid-job. `cache.v2` no longer decides whether the edit is made, it only withdraws the v2 advertisement, so artifacts work whatever the cache is set to. Also added a new `runner.patch_actions` option to turn the edit off if it ever breaks an action. Fixes https://gitea.com/gitea/runner/issues/1176 Reviewed-on: https://gitea.com/gitea/runner/pulls/1177 Reviewed-by: bircni <bircni@icloud.com> Co-authored-by: silverwind <me@silverwind.io>
This commit is contained in:
@@ -314,7 +314,7 @@ cache:
|
||||
v2: false
|
||||
```
|
||||
|
||||
Those actions refuse any host they do not take for GitHub. Rather than misreport the server URL, the runner edits that check out of the action's own bundle and keeps the untouched copy beside it; a bundle it does not recognise is left alone and keeps to v1. The same edit lets the stock `actions/upload-artifact` and `actions/download-artifact` work from `v4.4.0` on, without the `gitea-upload-artifact` fork.
|
||||
Those actions refuse any host they do not take for GitHub. Rather than misreport the server URL, the runner edits that check out of the action's own bundle on its way into the job, undone whenever the action is downloaded again. A bundle it does not recognise is left alone and keeps to v1. The same edit lets the stock `actions/upload-artifact` and `actions/download-artifact` work from `v4.4.0` on, without the `gitea-upload-artifact` fork, so it is made whatever `v2` says: that setting only governs the API the runner advertises. Set `runner.patch_actions: false` to leave every bundle exactly as shipped, an escape hatch for an action the edit breaks. The artifact actions then refuse again and the cache client keeps to v1.
|
||||
|
||||
**Shared cache across multiple runners**
|
||||
|
||||
|
||||
@@ -167,6 +167,11 @@ func maybeCopyToActionDir(ctx context.Context, step actionStep, actionDir, actio
|
||||
|
||||
defer git.AcquireCloneLock(actionDir)()
|
||||
|
||||
if !rc.Config.NoActionPatch {
|
||||
// A concurrent job's prepare resets this directory, so patch under the copy's lock.
|
||||
patchActions(ctx, actionScriptPaths(filepath.Join(actionDir, actionPath), step.getActionModel()))
|
||||
}
|
||||
|
||||
if err := removeGitIgnore(ctx, actionDir); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -12,7 +12,6 @@ import (
|
||||
"strings"
|
||||
|
||||
"gitea.com/gitea/runner/act/common"
|
||||
"gitea.com/gitea/runner/act/common/git"
|
||||
|
||||
"gitea.dev/actionslib/pkg/model"
|
||||
)
|
||||
@@ -41,8 +40,7 @@ const (
|
||||
cacheURLEnv = "ACTIONS_CACHE_URL"
|
||||
resultsURLEnv = "ACTIONS_RESULTS_URL"
|
||||
|
||||
// localhostHost is the suffix isGhes accepts; emptying the test is what opens the gate,
|
||||
// because every hostname ends with the empty string.
|
||||
// localhostHost is the suffix isGhes accepts.
|
||||
localhostHost = ".LOCALHOST"
|
||||
|
||||
// artifactRefusal is the only thing the gate guards in @actions/artifact, which is what makes
|
||||
@@ -50,13 +48,6 @@ const (
|
||||
// runner has not looked at, and is left alone.
|
||||
artifactRefusal = "GHESNotSupportedError"
|
||||
|
||||
// sidecarSuffix names the directory of untouched copies, a sibling of the action directory
|
||||
// because that directory is copied wholesale into job containers.
|
||||
sidecarSuffix = ".toolkit-patch"
|
||||
|
||||
// skipMarker in the sidecar means a patched bundle already failed once here.
|
||||
skipMarker = "skip"
|
||||
|
||||
maxBundleSize = 64 << 20
|
||||
)
|
||||
|
||||
@@ -101,156 +92,64 @@ func actionScriptPaths(dir string, action *model.Action) []string {
|
||||
}
|
||||
var paths []string
|
||||
for _, script := range []string{action.Runs.Pre, action.Runs.Main, action.Runs.Post} {
|
||||
if script != "" {
|
||||
paths = append(paths, filepath.Join(dir, script))
|
||||
if script == "" {
|
||||
continue
|
||||
}
|
||||
path := filepath.Join(dir, script)
|
||||
// `runs` is the action's own yaml, and a key pointing outside its directory is not ours.
|
||||
if rel, err := filepath.Rel(dir, path); err != nil || strings.HasPrefix(rel, "..") {
|
||||
continue
|
||||
}
|
||||
paths = append(paths, path)
|
||||
}
|
||||
return paths
|
||||
}
|
||||
|
||||
// patchToolkit edits the toolkit in an action's bundles, keeping each original beside them. Every
|
||||
// failure is silent and leaves the bundle as it was, which costs the cache client the v2 API and
|
||||
// an artifact action nothing at all.
|
||||
func patchToolkit(ctx context.Context, actionDir string, scripts []string) {
|
||||
if len(scripts) == 0 {
|
||||
return
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(sidecarDir(actionDir), skipMarker)); err == nil {
|
||||
return
|
||||
}
|
||||
defer git.AcquireCloneLock(actionDir)()
|
||||
|
||||
// patchActions edits the toolkit in an action's bundles. The caller holds the action directory's
|
||||
// clone lock, which is what keeps another job's checkout from resetting them before the copy.
|
||||
func patchActions(ctx context.Context, scripts []string) {
|
||||
for _, script := range scripts {
|
||||
if err := patchBundle(script, originalFor(actionDir, script)); err != nil {
|
||||
common.Logger(ctx).Debugf("actions toolkit: %s left unpatched: %v", filepath.Base(script), err)
|
||||
switch patched, err := patchBundle(script); {
|
||||
case err != nil:
|
||||
common.Logger(ctx).Warnf("actions toolkit: %s left unpatched: %v", script, err)
|
||||
case patched:
|
||||
common.Logger(ctx).Debugf("actions toolkit: patched %s", script)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// revertToolkit puts the originals back and stops this action being patched again, so the next job
|
||||
// runs it exactly as shipped. Called when a step failed with a patched bundle; it does not re-run
|
||||
// the step, because a step's outputs and env-file writes are already recorded by then.
|
||||
func revertToolkit(ctx context.Context, actionDir string, scripts []string) {
|
||||
if len(scripts) == 0 {
|
||||
return
|
||||
}
|
||||
if _, err := os.Stat(sidecarDir(actionDir)); err != nil {
|
||||
return
|
||||
}
|
||||
defer git.AcquireCloneLock(actionDir)()
|
||||
|
||||
reverted := false
|
||||
for _, script := range scripts {
|
||||
original := originalFor(actionDir, script)
|
||||
if !isPatchOf(original, script) {
|
||||
continue
|
||||
}
|
||||
if err := os.Rename(original, script); err == nil {
|
||||
reverted = true
|
||||
}
|
||||
}
|
||||
if reverted {
|
||||
_ = os.WriteFile(filepath.Join(sidecarDir(actionDir), skipMarker), nil, 0o600)
|
||||
common.Logger(ctx).Warnf("actions toolkit: restored the original %s, it will not be patched again", filepath.Base(actionDir))
|
||||
}
|
||||
}
|
||||
|
||||
// sidecarDir holds an action's untouched bundles, and the marker that stops it being patched.
|
||||
func sidecarDir(actionDir string) string {
|
||||
return actionDir + sidecarSuffix
|
||||
}
|
||||
|
||||
// originalFor is where a script's untouched copy lives, or "" for a script the action's own
|
||||
// `runs` keys placed outside its directory, which is not this runner's to rewrite.
|
||||
func originalFor(actionDir, script string) string {
|
||||
rel, err := filepath.Rel(actionDir, script)
|
||||
if err != nil || strings.HasPrefix(rel, "..") {
|
||||
return ""
|
||||
}
|
||||
return filepath.Join(sidecarDir(actionDir), rel)
|
||||
}
|
||||
|
||||
// patchBundle rewrites one entrypoint in place. The untouched copy kept beside it is what marks
|
||||
// the bundle as already patched.
|
||||
func patchBundle(script, original string) error {
|
||||
if original == "" {
|
||||
return nil
|
||||
}
|
||||
if _, err := os.Stat(original); err == nil {
|
||||
if isPatchOf(original, script) {
|
||||
return nil
|
||||
}
|
||||
// The action's ref moved and git checked the new bundle out over the patched one, so
|
||||
// the pair no longer belongs together. Patch afresh rather than keep an original that
|
||||
// would restore an older version of the action.
|
||||
if err := os.Remove(original); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
func patchBundle(script string) (bool, error) {
|
||||
info, err := os.Stat(script)
|
||||
if err != nil {
|
||||
return err
|
||||
return false, err
|
||||
}
|
||||
if info.Size() > maxBundleSize {
|
||||
return nil
|
||||
return false, nil
|
||||
}
|
||||
data, err := os.ReadFile(script)
|
||||
if err != nil {
|
||||
return err
|
||||
return false, err
|
||||
}
|
||||
patched, ok := patchedBundle(data)
|
||||
if !ok {
|
||||
return nil
|
||||
return false, nil
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(original), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
// The copy is taken before the bundle is replaced, so a write that fails part way can put the
|
||||
// action back as it was. A crash needs no handling: the clone executor checks the action out
|
||||
// and hard resets it on every prepare, so a half-written bundle never outlives the job.
|
||||
if err := os.WriteFile(original, data, info.Mode().Perm()); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.WriteFile(script, patched, info.Mode().Perm()); err != nil {
|
||||
_ = os.Rename(original, script)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// isPatchOf reports whether script is exactly what patching original produced. It is what proves
|
||||
// the two still belong together: an action whose ref moved is checked out over the patched bundle,
|
||||
// leaving an original that would restore the version before the move.
|
||||
func isPatchOf(original, script string) bool {
|
||||
data, err := os.ReadFile(original)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
current, err := os.ReadFile(script)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
patched, ok := patchedBundle(data)
|
||||
return ok && bytes.Equal(patched, current)
|
||||
// No atomic write needed: every prepare checks the action out and hard resets it.
|
||||
return true, os.WriteFile(script, patched, info.Mode().Perm())
|
||||
}
|
||||
|
||||
// patchedBundle opens the GHES gate, and where the cache toolkit is present, points the cache
|
||||
// service at the cache server. A bundle this runner cannot account for comes back untouched.
|
||||
func patchedBundle(data []byte) ([]byte, bool) {
|
||||
if !localhostTest.Match(data) {
|
||||
// Literals before regex: most bundles carry neither toolkit and stop here. The artifact gate
|
||||
// guards a refusal with no URL to move, so it opens alone; the cache gate opens only with its
|
||||
// service URL, since a bundle whose getter this cannot find is better left on v1.
|
||||
artifact := bytes.Contains(data, []byte(artifactRefusal))
|
||||
cache := bytes.Contains(data, []byte(CacheServiceV2Env)) && serviceURLBranches.Match(data)
|
||||
if !artifact && !cache {
|
||||
return data, false
|
||||
}
|
||||
switch {
|
||||
case bytes.Contains(data, []byte(CacheServiceV2Env)):
|
||||
// The cache toolkit: both edits or neither, because choosing v2 without redirecting the
|
||||
// URL would send the client to a results URL that serves no cache service.
|
||||
if !serviceURLBranches.Match(data) {
|
||||
return data, false
|
||||
}
|
||||
case bytes.Contains(data, []byte(artifactRefusal)):
|
||||
// The artifact toolkit, where the gate is a plain refusal and there is no URL to move:
|
||||
// artifacts already go to Gitea, which implements that service.
|
||||
default:
|
||||
if !localhostTest.Match(data) {
|
||||
return data, false
|
||||
}
|
||||
|
||||
@@ -259,5 +158,8 @@ func patchedBundle(data []byte) ([]byte, bool) {
|
||||
// quoting survives and the result stays valid even inside a string literal.
|
||||
return bytes.Replace(test, []byte(localhostHost), nil, 1)
|
||||
})
|
||||
return serviceURLBranches.ReplaceAll(opened, cacheURLFirst), true
|
||||
if cache {
|
||||
opened = serviceURLBranches.ReplaceAll(opened, cacheURLFirst)
|
||||
}
|
||||
return opened, true
|
||||
}
|
||||
@@ -108,17 +108,15 @@ func runActionEntrypoint(t *testing.T, script string, env jobEnv, inputs map[str
|
||||
return string(out)
|
||||
}
|
||||
|
||||
// patchedAction downloads one entrypoint and patches it exactly as a downloaded action would be,
|
||||
// keeping the untouched original in the sidecar beside it.
|
||||
// patchedAction downloads one entrypoint and patches it exactly as a downloaded action would be.
|
||||
func patchedAction(t *testing.T, repo, ref, entrypoint string) string {
|
||||
t.Helper()
|
||||
|
||||
body, err := os.ReadFile(bundleFromGitHub(t, repo, ref, entrypoint))
|
||||
require.NoError(t, err)
|
||||
dir := tempDirPath(t)
|
||||
script := filepath.Join(dir, filepath.Base(entrypoint))
|
||||
script := filepath.Join(tempDirPath(t), filepath.Base(entrypoint))
|
||||
require.NoError(t, os.WriteFile(script, body, 0o600))
|
||||
patchToolkit(t.Context(), dir, []string{script})
|
||||
patchActions(t.Context(), []string{script})
|
||||
return script
|
||||
}
|
||||
|
||||
@@ -184,7 +182,7 @@ func TestCacheServiceV2EndToEnd(t *testing.T) {
|
||||
// cache server on its own address. That is what a runner without a results service of its own
|
||||
// leaves its jobs with, so it has to round trip too.
|
||||
env.workspace = tempDirPath(t)
|
||||
v1 := runActionEntrypoint(t, filepath.Join(sidecarDir(filepath.Dir(restore)), "index.js"), env, inputs)
|
||||
v1 := runActionEntrypoint(t, bundleFromGitHub(t, "actions/cache", actionsCacheRef, "dist/restore/index.js"), env, inputs)
|
||||
require.Contains(t, v1, "Cache service version: v1")
|
||||
require.Contains(t, v1, "Cache restored from key: "+key)
|
||||
}
|
||||
@@ -194,7 +192,7 @@ func TestCacheServiceV2EndToEnd(t *testing.T) {
|
||||
// anchored on that distance. One entrypoint from each of the families that bundle the cache
|
||||
// toolkit, patched but not run, is what keeps a future release from quietly matching only one of
|
||||
// the two shapes and leaving every cache on v1.
|
||||
func TestToolkitPatchAcrossActions(t *testing.T) {
|
||||
func TestPatchedBundleAcrossActions(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
repo, ref, path string
|
||||
wantPatched bool
|
||||
@@ -5,7 +5,6 @@ package runner
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
@@ -14,6 +13,7 @@ import (
|
||||
|
||||
"gitea.dev/actionslib/pkg/model"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/mock"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
@@ -172,51 +172,42 @@ func TestPatchedBundleSurvivesInsideAStringLiteral(t *testing.T) {
|
||||
require.NoError(t, err, "%s", checked)
|
||||
}
|
||||
|
||||
func TestPatchBundleKeepsTheOriginal(t *testing.T) {
|
||||
dir, script := bundleFile(t, gateTSC)
|
||||
original := originalFor(dir, script)
|
||||
// An action with a pre step is copied, and so patched, twice.
|
||||
func TestPatchBundleIsIdempotent(t *testing.T) {
|
||||
script := bundleFile(t, gateTSC)
|
||||
|
||||
require.NoError(t, patchBundle(script, original))
|
||||
done, err := patchBundle(script)
|
||||
require.NoError(t, err)
|
||||
require.True(t, done)
|
||||
patched, err := os.ReadFile(script)
|
||||
require.NoError(t, err)
|
||||
assert.True(t, gateOpened(string(patched)))
|
||||
require.True(t, gateOpened(string(patched)))
|
||||
|
||||
kept, err := os.ReadFile(original)
|
||||
done, err = patchBundle(script)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, gateTSC, string(kept), "the untouched bundle is kept outside the action tree")
|
||||
assert.NotContains(t, original, dir+string(filepath.Separator), "originals must not ship into job containers")
|
||||
|
||||
// Patching again must not stack, and must not overwrite the kept original.
|
||||
require.NoError(t, patchBundle(script, original))
|
||||
assert.False(t, done, "a patched bundle is not patched again")
|
||||
again, err := os.ReadFile(script)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, string(patched), string(again))
|
||||
kept, err = os.ReadFile(original)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, gateTSC, string(kept))
|
||||
}
|
||||
|
||||
// A bundle with nothing to patch is left exactly as it was, with no original kept beside it.
|
||||
func TestPatchBundleLeavesOtherActionsAlone(t *testing.T) {
|
||||
dir, script := bundleFile(t, `console.log("checkout")`)
|
||||
original := originalFor(dir, script)
|
||||
script := bundleFile(t, `console.log("checkout")`)
|
||||
|
||||
require.NoError(t, patchBundle(script, original))
|
||||
done, err := patchBundle(script)
|
||||
require.NoError(t, err)
|
||||
assert.False(t, done)
|
||||
body, err := os.ReadFile(script)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, `console.log("checkout")`, string(body))
|
||||
_, err = os.Stat(original)
|
||||
assert.True(t, os.IsNotExist(err), "no original is kept for a bundle that was not patched")
|
||||
}
|
||||
|
||||
// bundleFile writes one entrypoint into a fresh action directory.
|
||||
func bundleFile(t *testing.T, body string) (dir, script string) {
|
||||
func bundleFile(t *testing.T, body string) string {
|
||||
t.Helper()
|
||||
|
||||
dir = t.TempDir()
|
||||
script = filepath.Join(dir, "index.js")
|
||||
script := filepath.Join(t.TempDir(), "index.js")
|
||||
require.NoError(t, os.WriteFile(script, []byte(body), 0o600))
|
||||
return dir, script
|
||||
return script
|
||||
}
|
||||
|
||||
func TestActionScriptPaths(t *testing.T) {
|
||||
@@ -226,101 +217,50 @@ func TestActionScriptPaths(t *testing.T) {
|
||||
// Only a node action has a bundle to patch.
|
||||
assert.Nil(t, actionScriptPaths("/a", &model.Action{Runs: model.ActionRuns{Using: "docker", Image: "alpine"}}))
|
||||
assert.Nil(t, actionScriptPaths("/a", nil))
|
||||
|
||||
// An action naming a file outside its own directory does not get it rewritten.
|
||||
escaping := &model.Action{Runs: model.ActionRuns{Using: "node20", Main: "../../elsewhere/index.js"}}
|
||||
assert.Nil(t, actionScriptPaths("/a", escaping))
|
||||
}
|
||||
|
||||
// A step that fails with a patched bundle gets the untouched bundle back, and the action is not
|
||||
// patched again, so later jobs run it exactly as its author shipped it.
|
||||
func TestRevertToolkit(t *testing.T) {
|
||||
dir, script := bundleFile(t, gateTSC)
|
||||
scripts := []string{script}
|
||||
|
||||
patchToolkit(t.Context(), dir, scripts)
|
||||
body, err := os.ReadFile(script)
|
||||
require.NoError(t, err)
|
||||
require.True(t, gateOpened(string(body)), "precondition: the bundle is patched")
|
||||
|
||||
revertToolkit(t.Context(), dir, scripts)
|
||||
body, err = os.ReadFile(script)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, gateTSC, string(body), "the original bundle is back")
|
||||
|
||||
// The skip marker survives, so the action stays unpatched from now on.
|
||||
patchToolkit(t.Context(), dir, scripts)
|
||||
body, err = os.ReadFile(script)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, gateTSC, string(body), "a reverted action stays unpatched")
|
||||
}
|
||||
|
||||
// An action whose ref moves is checked out over the patched bundle. The kept original then
|
||||
// belongs to the version before the move, and must not be restored over the new one.
|
||||
func TestPatchBundleAfterTheActionMoved(t *testing.T) {
|
||||
dir, script := bundleFile(t, gateTSC)
|
||||
original := originalFor(dir, script)
|
||||
scripts := []string{script}
|
||||
|
||||
patchToolkit(t.Context(), dir, scripts)
|
||||
require.NoError(t, os.WriteFile(script, []byte(gateWebpack), 0o600)) // the new version lands
|
||||
|
||||
// Reverting must not roll the action back to the version the original came from.
|
||||
revertToolkit(t.Context(), dir, scripts)
|
||||
body, err := os.ReadFile(script)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, gateWebpack, string(body))
|
||||
|
||||
// Nothing was reverted, so the action is not marked off either: the new version is patched
|
||||
// in its own right, and keeps its own original.
|
||||
require.NoFileExists(t, filepath.Join(sidecarDir(dir), skipMarker))
|
||||
require.NoError(t, patchBundle(script, original))
|
||||
body, err = os.ReadFile(script)
|
||||
require.NoError(t, err)
|
||||
assert.True(t, gateOpened(string(body)))
|
||||
kept, err := os.ReadFile(original)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, gateWebpack, string(kept))
|
||||
}
|
||||
|
||||
// The wiring: a step patches its own bundles only when the runner serves the v2 API, and a step
|
||||
// that fails gets them back. The action's path inside its repository is part of where they live.
|
||||
func TestStepActionRemoteToolkitPatch(t *testing.T) {
|
||||
newStep := func(t *testing.T, patch bool) (*stepActionRemote, string) {
|
||||
// The bundle has to be patched whatever state the shared action directory is in, because a
|
||||
// concurrent job's prepare checks the action out again and resets it.
|
||||
func TestPatchActionsAtTheContainerCopy(t *testing.T) {
|
||||
copiedBundle := func(t *testing.T, noPatch bool) string {
|
||||
t.Helper()
|
||||
|
||||
cm := &containerMock{}
|
||||
sar := &stepActionRemote{
|
||||
Step: &model.Step{Uses: "owner/repo/sub@v1"},
|
||||
remoteAction: &remoteAction{Org: "owner", Repo: "repo", Path: "sub", Ref: "v1"},
|
||||
action: &model.Action{Runs: model.ActionRuns{Using: "node20", Main: "index.js"}},
|
||||
RunContext: &RunContext{
|
||||
Config: &Config{ActionCacheDir: t.TempDir(), PatchToolkit: patch},
|
||||
Config: &Config{ActionCacheDir: t.TempDir(), NoActionPatch: noPatch},
|
||||
JobContainer: cm,
|
||||
},
|
||||
}
|
||||
script := filepath.Join(sar.actionDir(), "sub", "index.js")
|
||||
require.NoError(t, os.MkdirAll(filepath.Dir(script), 0o755))
|
||||
require.NoError(t, os.WriteFile(script, []byte(gateTSC), 0o600))
|
||||
return sar, script
|
||||
|
||||
var copied string
|
||||
cm.On("CopyDir", mock.Anything, mock.Anything, mock.Anything).Return(func(context.Context) error {
|
||||
body, err := os.ReadFile(script)
|
||||
require.NoError(t, err)
|
||||
copied = string(body)
|
||||
return nil
|
||||
})
|
||||
require.NoError(t, maybeCopyToActionDir(t.Context(), sar, sar.actionDir(), "sub", "/var/run/act/actions/repo/sub"))
|
||||
return copied
|
||||
}
|
||||
|
||||
t.Run("left alone when the runner does not patch", func(t *testing.T) {
|
||||
sar, script := newStep(t, false)
|
||||
require.NoError(t, sar.patchActionToolkit(t.Context()))
|
||||
|
||||
body, err := os.ReadFile(script)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, gateTSC, string(body))
|
||||
t.Run("patched on its way in", func(t *testing.T) {
|
||||
assert.True(t, gateOpened(copiedBundle(t, false)))
|
||||
})
|
||||
|
||||
t.Run("patched, and put back when the step fails", func(t *testing.T) {
|
||||
sar, script := newStep(t, true)
|
||||
require.NoError(t, sar.patchActionToolkit(t.Context()))
|
||||
|
||||
body, err := os.ReadFile(script)
|
||||
require.NoError(t, err)
|
||||
require.True(t, gateOpened(string(body)))
|
||||
|
||||
failed := errors.New("the step failed")
|
||||
require.ErrorIs(t, sar.revertToolkitOnFailure(func(context.Context) error { return failed })(t.Context()), failed)
|
||||
|
||||
body, err = os.ReadFile(script)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, gateTSC, string(body))
|
||||
// The escape hatch, for an action the edit breaks: the artifact actions refuse again, and the
|
||||
// cache client keeps to v1.
|
||||
t.Run("as shipped when the runner is told not to patch", func(t *testing.T) {
|
||||
assert.Equal(t, gateTSC, copiedBundle(t, true))
|
||||
})
|
||||
}
|
||||
@@ -74,7 +74,7 @@ type Config struct {
|
||||
ContainerNetworkCreateOptions container.NewDockerNetworkCreateExecutorInput // the default network create options
|
||||
ActionCache ActionCache // Use a custom ActionCache Implementation
|
||||
ProxyEnv map[string]string // the proxy variables the job runs with, also given to service containers and image builds
|
||||
PatchToolkit bool // edit the @actions toolkit bundled into an action so it works against Gitea, see toolkit_patch.go
|
||||
NoActionPatch bool // run actions exactly as published, applying no compatibility patches, see patch_actions.go
|
||||
|
||||
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
|
||||
|
||||
@@ -180,9 +180,6 @@ func (sar *stepActionRemote) prepareActionExecutor() common.Executor {
|
||||
sar.action = actionModel
|
||||
return err
|
||||
},
|
||||
// A stage of its own: it takes the same clone lock, and it has to land before
|
||||
// runAction copies the action into the job container.
|
||||
sar.patchActionToolkit,
|
||||
)(ctx)
|
||||
}
|
||||
}
|
||||
@@ -201,7 +198,7 @@ func (sar *stepActionRemote) pre() common.Executor {
|
||||
|
||||
return common.NewPipelineExecutor(
|
||||
sar.prepareActionExecutor(),
|
||||
runStepExecutor(sar, stepStagePre, sar.revertToolkitOnFailure(runPreStep(sar))).If(hasPreStep(sar)).If(shouldRunPreStep(sar)))
|
||||
runStepExecutor(sar, stepStagePre, runPreStep(sar)).If(hasPreStep(sar)).If(shouldRunPreStep(sar)))
|
||||
}
|
||||
|
||||
func (sar *stepActionRemote) main() common.Executor {
|
||||
@@ -223,47 +220,13 @@ func (sar *stepActionRemote) main() common.Executor {
|
||||
return sar.RunContext.JobContainer.CopyDir(copyToPath, sar.RunContext.Config.Workdir+string(filepath.Separator)+".", sar.RunContext.Config.UseGitIgnore)(ctx)
|
||||
}
|
||||
|
||||
actionDir := sar.actionDir()
|
||||
|
||||
return sar.revertToolkitOnFailure(sar.runAction(sar, actionDir, sar.remoteAction))(ctx)
|
||||
return sar.runAction(sar, sar.actionDir(), sar.remoteAction)(ctx)
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
func (sar *stepActionRemote) post() common.Executor {
|
||||
return runStepExecutor(sar, stepStagePost, sar.revertToolkitOnFailure(runPostStep(sar))).If(hasPostStep(sar)).If(shouldRunPostStep(sar))
|
||||
}
|
||||
|
||||
// toolkitBundles is the action directory and the entrypoints the toolkit may live in.
|
||||
func (sar *stepActionRemote) toolkitBundles() (string, []string) {
|
||||
if sar.remoteAction == nil {
|
||||
return "", nil
|
||||
}
|
||||
dir := sar.actionDir()
|
||||
return dir, actionScriptPaths(filepath.Join(dir, sar.remoteAction.Path), sar.action)
|
||||
}
|
||||
|
||||
// patchActionToolkit edits the bundled toolkit so it works against Gitea: the artifact actions
|
||||
// stop refusing, and the cache client keeps to the cache server whichever API version it picks.
|
||||
func (sar *stepActionRemote) patchActionToolkit(ctx context.Context) error {
|
||||
if sar.RunContext.Config.PatchToolkit {
|
||||
dir, scripts := sar.toolkitBundles()
|
||||
patchToolkit(ctx, dir, scripts)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// revertToolkitOnFailure restores the untouched bundles when the action fails, so a later job
|
||||
// runs it as shipped rather than repeating a failure the patch may have caused.
|
||||
func (sar *stepActionRemote) revertToolkitOnFailure(exec common.Executor) common.Executor {
|
||||
return func(ctx context.Context) error {
|
||||
err := exec(ctx)
|
||||
if err != nil {
|
||||
dir, scripts := sar.toolkitBundles()
|
||||
revertToolkit(ctx, dir, scripts)
|
||||
}
|
||||
return err
|
||||
}
|
||||
return runStepExecutor(sar, stepStagePost, runPostStep(sar)).If(hasPostStep(sar)).If(shouldRunPostStep(sar))
|
||||
}
|
||||
|
||||
func (sar *stepActionRemote) actionDir() string {
|
||||
|
||||
@@ -446,7 +446,6 @@ func runExec(ctx context.Context, execArgs *executeArgs) func(cmd *cobra.Command
|
||||
config := &runner.Config{
|
||||
Workdir: execArgs.Workdir(),
|
||||
BindWorkdir: false,
|
||||
PatchToolkit: true, // the cache server started above is what the patch points at
|
||||
ReuseContainers: false,
|
||||
ForcePull: execArgs.forcePull,
|
||||
ForceRebuild: execArgs.forceRebuild,
|
||||
|
||||
@@ -461,10 +461,13 @@ func (r *Runner) run(ctx context.Context, task *runnerv1.Task, reporter *report.
|
||||
// is that server's responsibility to authenticate requests.
|
||||
revokeCache, resultsURL := r.registerCacheForTask(giteaRuntimeToken, preset.Repository, reporter)
|
||||
defer revokeCache()
|
||||
// A cache server that agreed to forward the artifact half is the whole results service, so
|
||||
// the job is pointed at it and the v2 variable is finally true.
|
||||
// A cache server that agreed to forward the artifact half is the whole results service, so the
|
||||
// job is pointed at it.
|
||||
if resultsURL != "" {
|
||||
envs["ACTIONS_RESULTS_URL"], envs[runner.CacheServiceV2Env] = resultsURL, "true"
|
||||
envs["ACTIONS_RESULTS_URL"] = resultsURL
|
||||
if r.cacheServiceV2() {
|
||||
envs[runner.CacheServiceV2Env] = "true"
|
||||
}
|
||||
}
|
||||
|
||||
eventJSON, err := json.Marshal(preset.Event)
|
||||
@@ -515,7 +518,7 @@ func (r *Runner) run(ctx context.Context, task *runnerv1.Task, reporter *report.
|
||||
AllocatePTY: r.cfg.Runner.AllocatePTY,
|
||||
ActionOfflineMode: r.cfg.Cache.OfflineMode,
|
||||
ActionCloneDepth: actionCloneDepth,
|
||||
PatchToolkit: r.patchToolkit(),
|
||||
NoActionPatch: r.cfg.Runner.PatchActions != nil && !*r.cfg.Runner.PatchActions,
|
||||
|
||||
ReuseContainers: false,
|
||||
ForcePull: r.cfg.Container.ForcePull,
|
||||
@@ -590,10 +593,10 @@ func (r *Runner) run(ctx context.Context, task *runnerv1.Task, reporter *report.
|
||||
return execErr
|
||||
}
|
||||
|
||||
// patchToolkit reports whether act should edit the toolkit bundled into an action. It follows the
|
||||
// cache URL, because that is what the edits point the client at; see act/runner/toolkit_patch.go.
|
||||
func (r *Runner) patchToolkit() bool {
|
||||
return r.envs["ACTIONS_CACHE_URL"] != "" && (r.cfg.Cache.V2 == nil || *r.cfg.Cache.V2)
|
||||
// cacheServiceV2 reports whether jobs are told the cache service speaks v2. It is all cache.v2
|
||||
// turns off: the bundle edit that reaches it is what the artifact actions need too.
|
||||
func (r *Runner) cacheServiceV2() bool {
|
||||
return r.cfg.Cache.V2 == nil || *r.cfg.Cache.V2
|
||||
}
|
||||
|
||||
// registerCacheForTask tells the cache server to accept requests authenticated
|
||||
|
||||
@@ -169,7 +169,6 @@ func TestNewRunnerCacheServiceV2(t *testing.T) {
|
||||
|
||||
assert.Equal(t, "https://gitea.example", r.envs["ACTIONS_RESULTS_URL"])
|
||||
assert.Empty(t, r.envs[runner.CacheServiceV2Env], "a promise the runner has not made yet")
|
||||
assert.True(t, r.patchToolkit())
|
||||
|
||||
// The registration is what makes it true: the cache server takes the results service over,
|
||||
// having been told which instance to forward the artifact half to.
|
||||
@@ -190,6 +189,11 @@ func TestNewRunnerCacheServiceV2(t *testing.T) {
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode, "the advertised results service serves no cache service")
|
||||
|
||||
// Turning v2 off withdraws the advertisement and nothing else.
|
||||
assert.True(t, r.cacheServiceV2())
|
||||
cfg.Cache.V2 = new(bool)
|
||||
assert.False(t, r.cacheServiceV2())
|
||||
}
|
||||
|
||||
// The v1 cache client appends its path to ACTIONS_CACHE_URL without a separator, so a configured
|
||||
@@ -203,9 +207,8 @@ func TestNewRunnerNormalizesTheExternalCacheServer(t *testing.T) {
|
||||
r := NewRunner(cfg, &config.Registration{Name: "runner"}, cli)
|
||||
|
||||
assert.Equal(t, "http://cache.local:8088/", r.envs["ACTIONS_CACHE_URL"])
|
||||
// Nothing to front the results service with, so the variable stays unset, but the bundles are
|
||||
// still patched: artifacts v4 need that, and the patch keeps the cache client on the cache URL.
|
||||
// Nothing to front the results service with, so the variable stays unset and the client keeps
|
||||
// to v1, which reads the cache URL first.
|
||||
assert.Equal(t, "https://gitea.example", r.envs["ACTIONS_RESULTS_URL"])
|
||||
assert.Empty(t, r.envs[runner.CacheServiceV2Env])
|
||||
assert.True(t, r.patchToolkit())
|
||||
}
|
||||
|
||||
@@ -80,6 +80,10 @@ runner:
|
||||
# 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
|
||||
# When true (the default), apply compatibility patches to the actions a job runs, so actions
|
||||
# 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
|
||||
# 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 .
|
||||
@@ -164,10 +168,10 @@ cache:
|
||||
# A moved tag (e.g. a re-tagged "v6") or an updated branch stays at the cached commit
|
||||
# until its cache entry expires or is manually removed.
|
||||
#offline_mode: false
|
||||
# Serve the actions cache service v2 API, used by actions/cache@v4.2 and later. Those actions
|
||||
# refuse any host they do not take for GitHub, so reaching it means editing that check out of
|
||||
# the action's own bundle, keeping the untouched copy beside it. The same edit lets the stock
|
||||
# upload-artifact and download-artifact work here. A bundle that does not match is left alone.
|
||||
# Serve the actions cache service v2 API. The actions that use it refuse any host they do not
|
||||
# take for GitHub, so reaching it means editing that check out of their own bundle, undone
|
||||
# whenever it is downloaded again. That edit is made either way, this only governs the API
|
||||
# advertised. A bundle that does not match is left alone.
|
||||
#v2: true
|
||||
# How the cache server discards entries, ignored when external_server is set since that
|
||||
# server applies its own. Leave a setting out for its default; 0s or 0 turns the three
|
||||
|
||||
@@ -66,6 +66,7 @@ type Runner struct {
|
||||
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.
|
||||
PatchActions *bool `yaml:"patch_actions"` // PatchActions applies compatibility patches to the actions a job runs, so actions written for GitHub work against Gitea, see act/runner/patch_actions.go. It is a pointer to distinguish between false and not set; if not set, it defaults to true. Set it to false to run every action exactly as published, at the price of the artifact actions refusing.
|
||||
AllocatePTY bool `yaml:"allocate_pty"` // AllocatePTY allocates a pseudo-TTY for each step's process. Default is false, matching GitHub's actions/runner. Enable only for jobs that need an interactive terminal; tools like docker build emit redrawing progress frames into the captured log when a TTY is present. Applies to both host and docker backends.
|
||||
DefaultImage string `yaml:"default_image"` // DefaultImage is the image a job runs in when its runs-on matches none of the runner's labels. A runner without docker runs such a job on the host instead.
|
||||
ToolCacheMode string `yaml:"tool_cache_mode"` // ToolCacheMode is what the runner mounts at RUNNER_TOOL_CACHE on both backends: ToolCacheModeNone or ToolCacheModeShared.
|
||||
@@ -90,7 +91,7 @@ type Cache struct {
|
||||
ExternalSecret string `yaml:"external_secret"` // ExternalSecret is a shared secret between this runner and an external gitea-runner cache-server, enabling per-job ACTIONS_RUNTIME_TOKEN authentication and repo scoping over the network. Required whenever ExternalServer is set; ExternalSecretFile is the alternative way to provide it.
|
||||
ExternalSecretFile string `yaml:"external_secret_file"` // ExternalSecretFile is the path to a file holding the ExternalSecret value, so the secret can be mounted instead of stored in the config file. LoadDefault reads it into ExternalSecret; setting both is an error.
|
||||
OfflineMode bool `yaml:"offline_mode"` // OfflineMode reuses a cached action without fetching from the remote; a moved tag or branch stays at the cached commit until the cache entry is removed.
|
||||
V2 *bool `yaml:"v2"` // V2 serves the actions cache service v2 API to jobs, used by actions/cache@v4.2 and later, and edits the action bundles that would otherwise refuse it. Unset means enabled.
|
||||
V2 *bool `yaml:"v2"` // V2 advertises the actions cache service v2 API to jobs. The bundle edit that reaches it is made either way, the artifact actions need it too. Unset means enabled.
|
||||
|
||||
// Eviction settings, ignored when ExternalServer is set since that server applies its own.
|
||||
Retention time.Duration `yaml:"retention"` // Retention removes entries nothing has read or written within this window. Default 168h, 0 keeps them regardless of age.
|
||||
|
||||
Reference in New Issue
Block a user