mirror of
https://gitea.com/gitea/act_runner.git
synced 2026-11-28 06:42:21 +08:00
enhance: add host.stable_workdir for predictable host job paths (#1402)
- Add opt-in `host.stable_workdir`, which runs Linux host jobs in `<host.workdir_parent>/workspaces/<owner>/<repo>/<repo>`, like GitHub's `_work/<repo>/<repo>`, instead of a random directory - Give each job a private mount namespace, so concurrent jobs of a repository share that path with separate files, and show one running job's files at the path on the host - Needs `CAP_SYS_ADMIN`, without it jobs keep the random directory and log a warning Fixes: https://gitea.com/gitea/runner/issues/1373 Co-authored-by: silverwind <me@silverwind.io> Reviewed-on: https://gitea.com/gitea/runner/pulls/1402 Reviewed-by: silverwind <2021+silverwind@noreply.gitea.com> Co-authored-by: bircni <bircni@icloud.com>
This commit is contained in:
@@ -45,6 +45,37 @@ type HostEnvironment struct {
|
||||
// it while a step is still starting.
|
||||
procGroupOnce sync.Once
|
||||
procGroup atomic.Pointer[process.Group]
|
||||
|
||||
thread *jobThread
|
||||
mountTarget, mountSource string
|
||||
undo func()
|
||||
}
|
||||
|
||||
// jobThread runs calls on the OS thread whose children enter the job's mount namespace, a nil one runs them in place.
|
||||
type jobThread struct {
|
||||
calls chan func()
|
||||
stopped chan struct{}
|
||||
}
|
||||
|
||||
func (t *jobThread) run(call func()) {
|
||||
if t != nil {
|
||||
done := make(chan struct{})
|
||||
select {
|
||||
case t.calls <- func() { defer close(done); call() }:
|
||||
<-done
|
||||
return
|
||||
case <-t.stopped:
|
||||
}
|
||||
}
|
||||
call()
|
||||
}
|
||||
|
||||
// HostPath maps a path the job's processes see to the one the runner sees.
|
||||
func (e *HostEnvironment) HostPath(path string) string {
|
||||
if rest, ok := strings.CutPrefix(path, e.mountTarget); ok && (rest == "" || os.IsPathSeparator(rest[0])) {
|
||||
return e.mountSource + rest
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
// processGroup returns the job-scoped process group, creating it on first use.
|
||||
@@ -70,6 +101,7 @@ func (e *HostEnvironment) Close() common.Executor {
|
||||
}
|
||||
|
||||
func (e *HostEnvironment) Copy(destPath string, files ...*FileEntry) common.Executor {
|
||||
destPath = e.HostPath(destPath)
|
||||
return func(ctx context.Context) error {
|
||||
for _, f := range files {
|
||||
if err := os.MkdirAll(filepath.Dir(filepath.Join(destPath, f.Name)), 0o777); err != nil {
|
||||
@@ -84,6 +116,7 @@ func (e *HostEnvironment) Copy(destPath string, files ...*FileEntry) common.Exec
|
||||
}
|
||||
|
||||
func (e *HostEnvironment) CopyDir(destPath, srcPath string, useGitIgnore, skipGitDir bool) common.Executor {
|
||||
destPath, srcPath = e.HostPath(destPath), e.HostPath(srcPath)
|
||||
return func(ctx context.Context) error {
|
||||
logger := common.Logger(ctx)
|
||||
srcPrefix := filepath.Dir(srcPath)
|
||||
@@ -113,7 +146,7 @@ func (e *HostEnvironment) Inspect(_ context.Context) (*Info, error) {
|
||||
}
|
||||
|
||||
func (e *HostEnvironment) GetContainerArchive(ctx context.Context, srcPath string) (io.ReadCloser, error) {
|
||||
srcPath = filepath.Clean(srcPath)
|
||||
srcPath = e.HostPath(filepath.Clean(srcPath))
|
||||
fi, err := os.Lstat(srcPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -258,7 +291,9 @@ func (e *HostEnvironment) exec(ctx context.Context, command []string, cmdline st
|
||||
defer common.FlushWriter(e.StdOut)
|
||||
process.UTF8Console()
|
||||
|
||||
f, err := lookupPathHost(command[0], env, e.StdOut)
|
||||
var f string
|
||||
var err error
|
||||
e.thread.run(func() { f, err = lookupPathHost(command[0], env, e.StdOut) })
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -311,7 +346,8 @@ func (e *HostEnvironment) exec(ctx context.Context, command []string, cmdline st
|
||||
}()
|
||||
go writeKeepAlive(logctx, ppty)
|
||||
}
|
||||
if err := cmd.Start(); err != nil {
|
||||
e.thread.run(func() { err = cmd.Start() })
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if tracked {
|
||||
@@ -420,6 +456,9 @@ func (e *HostEnvironment) Remove() common.Executor {
|
||||
} else if killed > 0 {
|
||||
logger.Debugf("killed %d leftover process(es) of the job", killed)
|
||||
}
|
||||
if e.undo != nil {
|
||||
e.undo()
|
||||
}
|
||||
|
||||
// Detach: a cancelled ctx would skip removePathWithRetry's retries,
|
||||
// which absorb Windows file-handle release lag after the kill above.
|
||||
|
||||
154
act/container/host_workspace_linux.go
Normal file
154
act/container/host_workspace_linux.go
Normal file
@@ -0,0 +1,154 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package container
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
var safePathName = regexp.MustCompile(`^[\w.-]*[\w-][\w.-]*$`) // not only dots
|
||||
|
||||
// UseWorkspace runs the job at root/<owner>/<repo>/<repo>, its parent showing a directory of the job's own to its processes, and to the host while no other job does.
|
||||
func (e *HostEnvironment) UseWorkspace(root, repository string) error {
|
||||
owner, repo, ok := strings.Cut(repository, "/")
|
||||
if !ok || !safePathName.MatchString(owner) || !safePathName.MatchString(repo) {
|
||||
return fmt.Errorf("repository %q is unsafe in a path", repository)
|
||||
}
|
||||
target, source := filepath.Join(root, owner, repo), filepath.Join(e.Root, "work")
|
||||
if err := os.MkdirAll(filepath.Join(source, repo), 0o777); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.MkdirAll(target, 0o777); err != nil {
|
||||
return err
|
||||
}
|
||||
releaseRoot, err := privateMount(root)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
thread, err := startJobThread(source, target)
|
||||
if err != nil {
|
||||
releaseRoot()
|
||||
return err
|
||||
}
|
||||
releaseView := shareView(target+".lock", source, target)
|
||||
e.Path, e.thread, e.mountTarget, e.mountSource = filepath.Join(target, repo), thread, target, source
|
||||
e.undo = func() {
|
||||
close(thread.stopped)
|
||||
releaseView()
|
||||
releaseRoot()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var privateMounts sync.Mutex // threads would each bind dir
|
||||
|
||||
// privateMount keeps dir a mount that propagates nowhere while a job of any runner uses it, so binds below it stay in the namespace that makes them.
|
||||
func privateMount(dir string) (release func(), err error) {
|
||||
lock, err := os.OpenFile(dir+".lock", os.O_CREATE|os.O_RDONLY, 0o666)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := unix.Flock(int(lock.Fd()), unix.LOCK_SH); err != nil {
|
||||
return nil, errors.Join(err, lock.Close())
|
||||
}
|
||||
privateMounts.Lock()
|
||||
defer privateMounts.Unlock()
|
||||
if unix.Mount("", dir, "", unix.MS_PRIVATE, "") != nil {
|
||||
if err := unix.Mount(dir, dir, "", unix.MS_BIND|unix.MS_REC, ""); err != nil {
|
||||
return nil, errors.Join(err, lock.Close())
|
||||
}
|
||||
if err := unix.Mount("", dir, "", unix.MS_PRIVATE, ""); err != nil {
|
||||
return nil, errors.Join(err, unix.Unmount(dir, unix.MNT_DETACH), lock.Close())
|
||||
}
|
||||
}
|
||||
return func() {
|
||||
if unix.Flock(int(lock.Fd()), unix.LOCK_EX|unix.LOCK_NB) == nil {
|
||||
_ = unix.Unmount(dir, unix.MNT_DETACH)
|
||||
}
|
||||
lock.Close()
|
||||
}, nil
|
||||
}
|
||||
|
||||
// startJobThread starts a locked thread, ending with its goroutine, whose children see source at target and get no ambient CAP_SYS_ADMIN.
|
||||
func startJobThread(source, target string) (*jobThread, error) {
|
||||
thread := &jobThread{calls: make(chan func()), stopped: make(chan struct{})}
|
||||
started := make(chan error)
|
||||
go func() {
|
||||
runtime.LockOSThread()
|
||||
err := unix.Unshare(unix.CLONE_NEWNS)
|
||||
if err == nil {
|
||||
unmountAll(target)
|
||||
err = unix.Mount(source, target, "", unix.MS_BIND, "")
|
||||
}
|
||||
_ = unix.Prctl(unix.PR_CAP_AMBIENT, unix.PR_CAP_AMBIENT_LOWER, unix.CAP_SYS_ADMIN, 0, 0)
|
||||
started <- err
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for {
|
||||
select {
|
||||
case call := <-thread.calls:
|
||||
call()
|
||||
case <-thread.stopped:
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
return thread, <-started
|
||||
}
|
||||
|
||||
// shareView binds source at target on the host whenever no other job holds lock, trying at once and then every second, until release.
|
||||
func shareView(lock, source, target string) (release func()) {
|
||||
file, err := os.OpenFile(lock, os.O_CREATE|os.O_RDONLY, 0o666)
|
||||
if err != nil {
|
||||
return func() {}
|
||||
}
|
||||
bind := func() bool {
|
||||
if unix.Flock(int(file.Fd()), unix.LOCK_EX|unix.LOCK_NB) != nil {
|
||||
return false
|
||||
}
|
||||
unmountAll(target)
|
||||
if unix.Mount(source, target, "", unix.MS_BIND, "") != nil {
|
||||
_ = unix.Flock(int(file.Fd()), unix.LOCK_UN)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
stop, stopped := make(chan struct{}), make(chan struct{})
|
||||
bound := bind()
|
||||
go func() {
|
||||
defer close(stopped)
|
||||
defer file.Close()
|
||||
for !bound {
|
||||
select {
|
||||
case <-stop:
|
||||
return
|
||||
case <-time.After(time.Second):
|
||||
bound = bind()
|
||||
}
|
||||
}
|
||||
<-stop
|
||||
_ = unix.Unmount(target, unix.MNT_DETACH)
|
||||
}()
|
||||
return func() {
|
||||
close(stop)
|
||||
<-stopped
|
||||
}
|
||||
}
|
||||
|
||||
// unmountAll drops the binds at target, copies of other jobs' views or ones a crashed runner left.
|
||||
func unmountAll(target string) {
|
||||
for unix.Unmount(target, unix.MNT_DETACH) == nil {
|
||||
}
|
||||
}
|
||||
56
act/container/host_workspace_linux_test.go
Normal file
56
act/container/host_workspace_linux_test.go
Normal file
@@ -0,0 +1,56 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package container
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
func TestUseWorkspaceGivesConcurrentJobsOnePathAndHandsTheHostViewOn(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
root := filepath.Join(dir, "workspaces")
|
||||
workspace := filepath.Join(root, "owner", "repo", "repo")
|
||||
require.ErrorContains(t, (&HostEnvironment{Root: dir}).UseWorkspace(root, "owner/.."), "unsafe")
|
||||
|
||||
start := func(name string) *HostEnvironment {
|
||||
env := &HostEnvironment{Root: filepath.Join(dir, name), TrackingID: name}
|
||||
err := env.UseWorkspace(root, "owner/repo")
|
||||
if errors.Is(err, unix.EPERM) {
|
||||
t.Skip("needs CAP_SYS_ADMIN")
|
||||
}
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, os.WriteFile(env.HostPath(filepath.Join(env.Path, "name")), []byte(name), 0o644))
|
||||
return env
|
||||
}
|
||||
read := func(env *HostEnvironment) string {
|
||||
var out bytes.Buffer
|
||||
env.StdOut = &out
|
||||
require.NoError(t, env.Exec([]string{"cat", "name"}, map[string]string{"PATH": os.Getenv("PATH")}, "", "")(t.Context()))
|
||||
return out.String()
|
||||
}
|
||||
first, second := start("first"), start("second")
|
||||
assert.Equal(t, workspace, second.Path)
|
||||
assert.Equal(t, "first", read(first))
|
||||
assert.Equal(t, "second", read(second))
|
||||
shown, err := os.ReadFile(filepath.Join(workspace, "name"))
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "first", string(shown))
|
||||
|
||||
require.NoError(t, first.Remove()(t.Context()))
|
||||
assert.Equal(t, "second", read(second))
|
||||
assert.Eventually(t, func() bool {
|
||||
shown, _ := os.ReadFile(filepath.Join(workspace, "name"))
|
||||
return string(shown) == "second"
|
||||
}, 5*time.Second, 50*time.Millisecond)
|
||||
require.NoError(t, second.Remove()(t.Context()))
|
||||
}
|
||||
12
act/container/host_workspace_other.go
Normal file
12
act/container/host_workspace_other.go
Normal file
@@ -0,0 +1,12 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
//go:build !linux
|
||||
|
||||
package container
|
||||
|
||||
import "errors"
|
||||
|
||||
func (e *HostEnvironment) UseWorkspace(_root, _repository string) error {
|
||||
return errors.ErrUnsupported
|
||||
}
|
||||
@@ -254,7 +254,7 @@ func (rc *RunContext) validVolumes() []string {
|
||||
name := rc.jobContainerName()
|
||||
volumes := slices.Clone(rc.Config.ValidVolumes)
|
||||
if hostEnv, ok := rc.JobContainer.(*container.HostEnvironment); ok {
|
||||
volumes = append(volumes, hostEnv.Path, hostEnv.GetActPath())
|
||||
volumes = append(volumes, hostEnv.HostPath(hostEnv.Path), hostEnv.GetActPath())
|
||||
}
|
||||
if rc.Config.SharedToolCache {
|
||||
volumes = append(volumes, rc.toolCacheVolume())
|
||||
@@ -388,7 +388,7 @@ func (rc *RunContext) GetBindsAndMounts(ctx context.Context) ([]string, map[stri
|
||||
}
|
||||
}
|
||||
if hostEnv, ok := rc.JobContainer.(*container.HostEnvironment); ok {
|
||||
binds = append(binds, hostEnv.Path+":"+hostEnv.Path, hostEnv.GetActPath()+":"+hostEnv.GetActPath())
|
||||
binds = append(binds, hostEnv.HostPath(hostEnv.Path)+":"+hostEnv.Path, hostEnv.GetActPath()+":"+hostEnv.GetActPath())
|
||||
}
|
||||
mounts[name+"-env"] = ext.GetActPath() // runner-internal, never overridable
|
||||
|
||||
@@ -451,7 +451,7 @@ func (rc *RunContext) startHostEnvironment() common.Executor {
|
||||
if err := os.MkdirAll(toolCache, 0o777); err != nil {
|
||||
return err
|
||||
}
|
||||
rc.JobContainer = &container.HostEnvironment{
|
||||
hostEnv := &container.HostEnvironment{
|
||||
Path: path,
|
||||
TmpDir: runnerTmp,
|
||||
ToolCache: toolCache,
|
||||
@@ -462,7 +462,13 @@ func (rc *RunContext) startHostEnvironment() common.Executor {
|
||||
StdOut: logWriter,
|
||||
AllocatePTY: rc.Config.AllocatePTY,
|
||||
}
|
||||
rc.cleanUpJobContainer = rc.JobContainer.Remove()
|
||||
rc.JobContainer = hostEnv
|
||||
rc.cleanUpJobContainer = hostEnv.Remove()
|
||||
if preset := rc.Config.PresetGitHubContext; rc.Config.StableHostWorkdir && preset != nil {
|
||||
if err := hostEnv.UseWorkspace(filepath.Join(cacheDir, "workspaces"), preset.Repository); err != nil {
|
||||
common.Logger(ctx).Warnf("host.stable_workdir needs Linux and CAP_SYS_ADMIN, using a random workspace path: %v", err)
|
||||
}
|
||||
}
|
||||
rc.setRunnerContextEnv(ctx)
|
||||
rc.importHostEnv(os.Environ())
|
||||
|
||||
|
||||
@@ -87,6 +87,7 @@ type Config struct {
|
||||
ContainerVolumes []string // mounted into every job, service and docker action container
|
||||
SharedToolCache bool // keeps the tool cache across jobs instead of one per job
|
||||
ToolCacheSlot string // keeps concurrent tasks' tool caches apart, empty for slot 0 and in exec
|
||||
StableHostWorkdir bool // host jobs run at a stable path per repository, see HostEnvironment.UseWorkspace
|
||||
InsecureSkipTLS bool // whether to skip verifying TLS certificate of the Gitea instance
|
||||
ClientCertFile, ClientKeyFile string // PEM client certificate for the Gitea instance
|
||||
CAFile string // PEM CA certificates the Gitea instance's certificate chains to
|
||||
|
||||
@@ -1,4 +1,12 @@
|
||||
# Host-mode background processes
|
||||
# Host mode
|
||||
|
||||
## Stable workspace
|
||||
|
||||
Host jobs run in a random `<host.workdir_parent>/<16 hex>/hostexecutor` directory. With `host.stable_workdir: true`, Linux host jobs run in `<host.workdir_parent>/workspaces/<owner>/<repo>/<repo>` instead, like GitHub's `_work/<repo>/<repo>`. This needs `CAP_SYS_ADMIN`, so run the runner as root or with `AmbientCapabilities=CAP_SYS_ADMIN` in its systemd unit. Steps don't get the capability. Without it, jobs keep the random directory and log a warning.
|
||||
|
||||
Concurrent jobs of a repository use the same path, each with its own files, through a private mount namespace. On the host, the path shows the files of one of them, so processes started outside a job, like containers from `docker run -v "$PWD:/src"` or systemd services, only see the right files there in that job. Every job starts with an empty workspace.
|
||||
|
||||
## Background processes
|
||||
|
||||
Host jobs clean up background step processes at job completion. A step can opt out:
|
||||
|
||||
|
||||
@@ -638,6 +638,7 @@ func (r *Runner) run(ctx context.Context, task *runnerv1.Task, reporter *report.
|
||||
ContainerVolumes: r.cfg.Container.Volumes,
|
||||
SharedToolCache: r.cfg.Runner.ToolCacheMode == config.ToolCacheModeShared,
|
||||
ToolCacheSlot: toolCacheSlot(r.cfg.Runner.ToolCacheMode, slot),
|
||||
StableHostWorkdir: r.cfg.Host.StableWorkdir,
|
||||
InsecureSkipTLS: r.cfg.Runner.Insecure,
|
||||
ClientCertFile: r.cfg.Runner.ClientCertFile,
|
||||
ClientKeyFile: r.cfg.Runner.ClientKeyFile,
|
||||
|
||||
@@ -325,6 +325,9 @@ host:
|
||||
# The parent directory of a job's working directory.
|
||||
# If it's empty, $HOME/.cache/act/ will be used.
|
||||
#workdir_parent:
|
||||
# Run Linux host jobs at workdir_parent/workspaces/<owner>/<repo>/<repo> instead of a random
|
||||
# directory. Needs CAP_SYS_ADMIN, see docs/host-mode.md.
|
||||
#stable_workdir: false
|
||||
|
||||
# Jobs that run as Kubernetes pods, see docs/kubernetes.md.
|
||||
kubernetes:
|
||||
|
||||
@@ -226,6 +226,7 @@ type ContainerNetworkCreateOptions struct {
|
||||
// Host represents the configuration for the host.
|
||||
type Host struct {
|
||||
WorkdirParent string `yaml:"workdir_parent"` // WorkdirParent specifies the parent directory for the host's working directory.
|
||||
StableWorkdir bool `yaml:"stable_workdir"` // StableWorkdir runs Linux host jobs at workspaces/<owner>/<repo>/<repo> in WorkdirParent, which needs CAP_SYS_ADMIN.
|
||||
}
|
||||
|
||||
// Kubernetes configures the pods jobs run in.
|
||||
|
||||
Reference in New Issue
Block a user