mirror of
https://gitea.com/gitea/runner.git
synced 2026-11-05 14:55:44 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ff9965e940 | ||
|
|
ba4d3c5b4f | ||
|
|
9e3647395a | ||
|
|
c158ac5472 | ||
|
|
1745c7c841 | ||
|
|
7f53eca716 | ||
|
|
fca6b44c60 |
No files matched your search
@@ -74,7 +74,7 @@ jobs:
|
|||||||
fetch-depth: 0 # all history for all branches and tags
|
fetch-depth: 0 # all history for all branches and tags
|
||||||
|
|
||||||
- name: Set up QEMU
|
- name: Set up QEMU
|
||||||
uses: docker/setup-qemu-action@96fe6ef7f33517b61c61be40b68a1882f3264fb8 # v4
|
uses: docker/setup-qemu-action@1f40c72289eff860ee54a304f1438e3cff362e0a # v4
|
||||||
|
|
||||||
- name: Set up Docker BuildX
|
- name: Set up Docker BuildX
|
||||||
uses: docker/setup-buildx-action@37fe631027851001ddb9b187196cc803df7f5f0e # v4
|
uses: docker/setup-buildx-action@37fe631027851001ddb9b187196cc803df7f5f0e # v4
|
||||||
|
|||||||
@@ -77,7 +77,7 @@ jobs:
|
|||||||
fetch-depth: 0 # all history for all branches and tags
|
fetch-depth: 0 # all history for all branches and tags
|
||||||
|
|
||||||
- name: Set up QEMU
|
- name: Set up QEMU
|
||||||
uses: docker/setup-qemu-action@96fe6ef7f33517b61c61be40b68a1882f3264fb8 # v4
|
uses: docker/setup-qemu-action@1f40c72289eff860ee54a304f1438e3cff362e0a # v4
|
||||||
|
|
||||||
- name: Set up Docker BuildX
|
- name: Set up Docker BuildX
|
||||||
uses: docker/setup-buildx-action@37fe631027851001ddb9b187196cc803df7f5f0e # v4
|
uses: docker/setup-buildx-action@37fe631027851001ddb9b187196cc803df7f5f0e # v4
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ jobs:
|
|||||||
- name: pre-pull test images
|
- name: pre-pull test images
|
||||||
env:
|
env:
|
||||||
TEST_JOB_IMAGE: node:24-bookworm-slim@sha256:ba849c60be29959425b8734d57b8b4b7d56f98edd9504c9af091d5281095a71e # renovate: datasource=docker
|
TEST_JOB_IMAGE: node:24-bookworm-slim@sha256:ba849c60be29959425b8734d57b8b4b7d56f98edd9504c9af091d5281095a71e # renovate: datasource=docker
|
||||||
TEST_SERVICE_IMAGE: nginx:alpine@sha256:db35bfc6b2951e7f8a72db5db120288c127ffaeeb4a6d4b95a26fead017d5913 # renovate: datasource=docker
|
TEST_SERVICE_IMAGE: nginx:alpine@sha256:72ba65eb42c10344912a84ff42408db7d34f2feb642204570ab8fc5ffd29f1d3 # renovate: datasource=docker
|
||||||
run: |
|
run: |
|
||||||
for image in "$TEST_JOB_IMAGE" "$TEST_SERVICE_IMAGE"; do
|
for image in "$TEST_JOB_IMAGE" "$TEST_SERVICE_IMAGE"; do
|
||||||
for attempt in 1 2 3; do
|
for attempt in 1 2 3; do
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ DOCKER_TAG ?= nightly
|
|||||||
DOCKER_REF := $(DOCKER_IMAGE):$(DOCKER_TAG)
|
DOCKER_REF := $(DOCKER_IMAGE):$(DOCKER_TAG)
|
||||||
DOCKER_ROOTLESS_REF := $(DOCKER_IMAGE):$(DOCKER_TAG)-dind-rootless
|
DOCKER_ROOTLESS_REF := $(DOCKER_IMAGE):$(DOCKER_TAG)-dind-rootless
|
||||||
|
|
||||||
GOLANGCI_LINT_PACKAGE ?= github.com/golangci/golangci-lint/v2/cmd/[email protected].1 # renovate: datasource=go
|
GOLANGCI_LINT_PACKAGE ?= github.com/golangci/golangci-lint/v2/cmd/[email protected].2 # renovate: datasource=go
|
||||||
GOVULNCHECK_PACKAGE ?= golang.org/x/vuln/cmd/[email protected] # renovate: datasource=go
|
GOVULNCHECK_PACKAGE ?= golang.org/x/vuln/cmd/[email protected] # renovate: datasource=go
|
||||||
|
|
||||||
GOTEST_FLAGS ?= -race -timeout 20m -parallel 8
|
GOTEST_FLAGS ?= -race -timeout 20m -parallel 8
|
||||||
@@ -96,13 +96,8 @@ go-check:
|
|||||||
fi
|
fi
|
||||||
|
|
||||||
.PHONY: fmt-check
|
.PHONY: fmt-check
|
||||||
fmt-check: fmt
|
fmt-check: ## check the Go code formatting
|
||||||
@diff=$$(git diff --color=always -- '*.go'); \
|
$(GO) run $(GOLANGCI_LINT_PACKAGE) fmt --diff-colored
|
||||||
if [ -n "$$diff" ]; then \
|
|
||||||
echo "Please run 'make fmt' and commit the result:"; \
|
|
||||||
printf "%s" "$${diff}"; \
|
|
||||||
exit 1; \
|
|
||||||
fi
|
|
||||||
|
|
||||||
.PHONY: deps-tools
|
.PHONY: deps-tools
|
||||||
deps-tools: ## install tool dependencies
|
deps-tools: ## install tool dependencies
|
||||||
@@ -149,13 +144,8 @@ tidy: ## run go mod tidy
|
|||||||
fi
|
fi
|
||||||
|
|
||||||
.PHONY: tidy-check
|
.PHONY: tidy-check
|
||||||
tidy-check: tidy
|
tidy-check: ## check that go.mod and go.sum are tidy
|
||||||
@diff=$$(git diff --color=always -- go.mod go.sum); \
|
$(GO) mod tidy -diff
|
||||||
if [ -n "$$diff" ]; then \
|
|
||||||
echo "Please run 'make tidy' and commit the result:"; \
|
|
||||||
printf "%s" "$${diff}"; \
|
|
||||||
exit 1; \
|
|
||||||
fi
|
|
||||||
|
|
||||||
.PHONY: test
|
.PHONY: test
|
||||||
test: ## test everything (integration tests self-skip without docker/network)
|
test: ## test everything (integration tests self-skip without docker/network)
|
||||||
|
|||||||
@@ -266,6 +266,17 @@ A job in a container reaches a service by its id on the job network, on the port
|
|||||||
|
|
||||||
Unlike GitHub, a job whose steps run on the host (a `host` label without `container:`) starts no service containers, so `job.services` and `job.container` stay empty. Give such a job a `container:` when it needs services.
|
Unlike GitHub, a job whose steps run on the host (a `host` label without `container:`) starts no service containers, so `job.services` and `job.container` stay empty. Give such a job a `container:` when it needs services.
|
||||||
|
|
||||||
|
#### Docker from a job (`GITEA_DOCKER_WORKSPACE`)
|
||||||
|
|
||||||
|
A container a job starts through the Docker socket cannot bind-mount the workspace by the job's own path, the daemon does not have it. `GITEA_DOCKER_WORKSPACE` holds the path the daemon sees. Use it as the prefix of workspace binds, with `.` as the fallback for local use, here in a `docker-compose.yaml`:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
volumes:
|
||||||
|
- ${GITEA_DOCKER_WORKSPACE:-.}/data:/app/data
|
||||||
|
```
|
||||||
|
|
||||||
|
Linux container jobs use a Docker proxy when socket sharing and permissions allow it. Other setups use the daemon socket directly. The proxy removes containers, networks and volumes after post steps and the completed hook. Named volumes created through it are job-scoped. To retain resources, mount the daemon socket explicitly in `container.options`. Host jobs use their existing Docker access, where `.` works.
|
||||||
|
|
||||||
#### Proxy
|
#### Proxy
|
||||||
|
|
||||||
Set these variables in the runner's environment, with systemd `Environment=`, `docker run -e`, or Kubernetes `env:`:
|
Set these variables in the runner's environment, with systemd `Environment=`, `docker run -e`, or Kubernetes `env:`:
|
||||||
|
|||||||
+90
-37
@@ -391,7 +391,11 @@ func NewGitCloneExecutor(input NewGitCloneExecutorInput) common.Executor {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if !isOfflineMode {
|
// A just-cloned ref is as current as a fetch would make it, and a commit hash never moves.
|
||||||
|
_, _, present := refRevision(r, input.Ref)
|
||||||
|
refresh := !isOfflineMode && (!present || (reused && !plumbing.IsHash(input.Ref)))
|
||||||
|
|
||||||
|
if refresh {
|
||||||
err = r.FetchContext(ctx, &fetchOptions)
|
err = r.FetchContext(ctx, &fetchOptions)
|
||||||
if err != nil && !errors.Is(err, git.NoErrAlreadyUpToDate) {
|
if err != nil && !errors.Is(err, git.NoErrAlreadyUpToDate) {
|
||||||
return err
|
return err
|
||||||
@@ -411,23 +415,7 @@ func NewGitCloneExecutor(input NewGitCloneExecutorInput) common.Executor {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// At this point we need to know if it's a tag or a branch
|
rev, refType, _ := refRevision(r, input.Ref)
|
||||||
// And the easiest way to do it is duck typing
|
|
||||||
//
|
|
||||||
// If err is nil, it's a tag so let's proceed with that hash like we would if
|
|
||||||
// it was a sha
|
|
||||||
refType := "tag"
|
|
||||||
rev = plumbing.Revision(path.Join("refs", "tags", input.Ref))
|
|
||||||
if _, err := r.Tag(input.Ref); errors.Is(err, git.ErrTagNotFound) {
|
|
||||||
rName := plumbing.ReferenceName(path.Join("refs", "remotes", "origin", input.Ref))
|
|
||||||
if _, err := r.Reference(rName, false); errors.Is(err, plumbing.ErrReferenceNotFound) {
|
|
||||||
refType = "sha"
|
|
||||||
rev = plumbing.Revision(input.Ref)
|
|
||||||
} else {
|
|
||||||
refType = "branch"
|
|
||||||
rev = plumbing.Revision(rName)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if hash, err = r.ResolveRevision(rev); err != nil {
|
if hash, err = r.ResolveRevision(rev); err != nil {
|
||||||
logger.Errorf("Unable to resolve %s: %v", input.Ref, err)
|
logger.Errorf("Unable to resolve %s: %v", input.Ref, err)
|
||||||
@@ -459,7 +447,7 @@ func NewGitCloneExecutor(input NewGitCloneExecutorInput) common.Executor {
|
|||||||
reusedMsg := ""
|
reusedMsg := ""
|
||||||
|
|
||||||
switch {
|
switch {
|
||||||
case !isOfflineMode && !shallow:
|
case refresh && !shallow:
|
||||||
// In shallow mode the depth-limited fetch above already advanced the ref.
|
// In shallow mode the depth-limited fetch above already advanced the ref.
|
||||||
if err = w.PullContext(ctx, &pullOptions); err != nil && !errors.Is(err, git.NoErrAlreadyUpToDate) {
|
if err = w.PullContext(ctx, &pullOptions); err != nil && !errors.Is(err, git.NoErrAlreadyUpToDate) {
|
||||||
logger.Debugf("Unable to pull %s: %v", refName, err)
|
logger.Debugf("Unable to pull %s: %v", refName, err)
|
||||||
@@ -501,27 +489,37 @@ func NewGitCloneExecutor(input NewGitCloneExecutorInput) common.Executor {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// cloneAtDepth clones input.URL into input.Dir using opts.
|
// cloneAtDepth falls back to a full clone when the shallow attempt fails.
|
||||||
// With input.Depth > 0 it first tries a shallow, single-branch clone of input.Ref, falling back when error.
|
|
||||||
func cloneAtDepth(ctx context.Context, input NewGitCloneExecutorInput, opts git.CloneOptions, logger log.FieldLogger) (*git.Repository, error) {
|
func cloneAtDepth(ctx context.Context, input NewGitCloneExecutorInput, opts git.CloneOptions, logger log.FieldLogger) (*git.Repository, error) {
|
||||||
if input.Depth > 0 {
|
if input.Depth > 0 {
|
||||||
for _, refName := range []plumbing.ReferenceName{
|
if plumbing.IsHash(input.Ref) {
|
||||||
plumbing.NewBranchReferenceName(input.Ref),
|
r, err := fetchPinnedSHA(ctx, input, opts)
|
||||||
plumbing.NewTagReferenceName(input.Ref),
|
|
||||||
} {
|
|
||||||
shallowOpts := opts
|
|
||||||
shallowOpts.Depth = input.Depth
|
|
||||||
shallowOpts.SingleBranch = true
|
|
||||||
shallowOpts.ReferenceName = refName
|
|
||||||
shallowOpts.Tags = git.NoTags
|
|
||||||
|
|
||||||
r, err := git.PlainCloneContext(ctx, input.Dir, false, &shallowOpts)
|
|
||||||
if err == nil {
|
if err == nil {
|
||||||
return r, nil
|
return r, nil
|
||||||
}
|
}
|
||||||
logger.Debugf("Shallow clone of %s as %s failed: %v", input.URL, refName, err)
|
logger.Debugf("Shallow fetch of %s at %s failed: %v", input.URL, input.Ref, err)
|
||||||
if rmErr := os.RemoveAll(input.Dir); rmErr != nil {
|
if err := removePartialClone(input.Dir); err != nil {
|
||||||
return nil, fmt.Errorf("remove partial clone %s: %w", input.Dir, rmErr)
|
return nil, err
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
for _, refName := range []plumbing.ReferenceName{
|
||||||
|
plumbing.NewBranchReferenceName(input.Ref),
|
||||||
|
plumbing.NewTagReferenceName(input.Ref),
|
||||||
|
} {
|
||||||
|
shallowOpts := opts
|
||||||
|
shallowOpts.Depth = input.Depth
|
||||||
|
shallowOpts.SingleBranch = true
|
||||||
|
shallowOpts.ReferenceName = refName
|
||||||
|
shallowOpts.Tags = git.NoTags
|
||||||
|
|
||||||
|
r, err := git.PlainCloneContext(ctx, input.Dir, false, &shallowOpts)
|
||||||
|
if err == nil {
|
||||||
|
return r, nil
|
||||||
|
}
|
||||||
|
logger.Debugf("Shallow clone of %s as %s failed: %v", input.URL, refName, err)
|
||||||
|
if err := removePartialClone(input.Dir); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
logger.Debugf("Falling back to a full clone of %s for ref %q", input.URL, input.Ref)
|
logger.Debugf("Falling back to a full clone of %s for ref %q", input.URL, input.Ref)
|
||||||
@@ -530,14 +528,65 @@ func cloneAtDepth(ctx context.Context, input NewGitCloneExecutorInput, opts git.
|
|||||||
return git.PlainCloneContext(ctx, input.Dir, false, &opts)
|
return git.PlainCloneContext(ctx, input.Dir, false, &opts)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func removePartialClone(dir string) error {
|
||||||
|
if err := os.RemoveAll(dir); err != nil {
|
||||||
|
return fmt.Errorf("remove partial clone %s: %w", dir, err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func fetchPinnedSHA(ctx context.Context, input NewGitCloneExecutorInput, opts git.CloneOptions) (*git.Repository, error) {
|
||||||
|
r, err := git.PlainInit(input.Dir, false)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if _, err := r.CreateRemote(&config.RemoteConfig{Name: "origin", URLs: []string{input.URL}}); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := r.FetchContext(ctx, &git.FetchOptions{
|
||||||
|
RefSpecs: []config.RefSpec{pinnedRefSpec(input.Ref)},
|
||||||
|
Depth: input.Depth,
|
||||||
|
Tags: git.NoTags,
|
||||||
|
Auth: opts.Auth,
|
||||||
|
Progress: opts.Progress,
|
||||||
|
InsecureSkipTLS: opts.InsecureSkipTLS,
|
||||||
|
}); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return r, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// pinnedRefSpec keeps a hash-shaped name out of refs/heads and refs/tags.
|
||||||
|
func pinnedRefSpec(sha string) config.RefSpec {
|
||||||
|
return config.RefSpec(fmt.Sprintf("+%s:refs/pinned/%s", sha, sha))
|
||||||
|
}
|
||||||
|
|
||||||
|
// refRevision picks the revision to check out and reports whether it resolves locally.
|
||||||
|
func refRevision(r *git.Repository, ref string) (plumbing.Revision, string, bool) {
|
||||||
|
if plumbing.IsHash(ref) {
|
||||||
|
// git ignores a ref named as 40 hex digits, so a full hash always denotes the commit itself.
|
||||||
|
_, err := r.CommitObject(plumbing.NewHash(ref))
|
||||||
|
return plumbing.Revision(ref), "sha", err == nil
|
||||||
|
}
|
||||||
|
if _, err := r.Tag(ref); err == nil {
|
||||||
|
return plumbing.Revision(path.Join("refs", "tags", ref)), "tag", true
|
||||||
|
}
|
||||||
|
remoteRef := plumbing.ReferenceName(path.Join("refs", "remotes", "origin", ref))
|
||||||
|
if _, err := r.Reference(remoteRef, false); err == nil {
|
||||||
|
return plumbing.Revision(remoteRef), "branch", true
|
||||||
|
}
|
||||||
|
rev := plumbing.Revision(ref)
|
||||||
|
_, err := r.ResolveRevision(rev)
|
||||||
|
return rev, "sha", err == nil
|
||||||
|
}
|
||||||
|
|
||||||
// isShallow reports whether the local repository was cloned with a limited depth.
|
// isShallow reports whether the local repository was cloned with a limited depth.
|
||||||
func isShallow(r *git.Repository) bool {
|
func isShallow(r *git.Repository) bool {
|
||||||
shallows, err := r.Storer.Shallow()
|
shallows, err := r.Storer.Shallow()
|
||||||
return err == nil && len(shallows) > 0
|
return err == nil && len(shallows) > 0
|
||||||
}
|
}
|
||||||
|
|
||||||
// shallowFetchRefSpec returns the single refspec that updates only input.Ref, keeping a shallow clone from re-downloading every branch's history.
|
// shallowFetchRefSpec limits a shallow update to the requested ref, falling back to the broad refspec when it is not present locally.
|
||||||
// ok is false when the ref is not present locally as a tag or remote-tracking branch, in which case the broad default refspec is used.
|
|
||||||
func shallowFetchRefSpec(r *git.Repository, ref string) (config.RefSpec, bool) {
|
func shallowFetchRefSpec(r *git.Repository, ref string) (config.RefSpec, bool) {
|
||||||
tagRef := plumbing.NewTagReferenceName(ref)
|
tagRef := plumbing.NewTagReferenceName(ref)
|
||||||
if _, err := r.Reference(tagRef, false); err == nil {
|
if _, err := r.Reference(tagRef, false); err == nil {
|
||||||
@@ -548,5 +597,9 @@ func shallowFetchRefSpec(r *git.Repository, ref string) (config.RefSpec, bool) {
|
|||||||
branchRef := plumbing.NewBranchReferenceName(ref)
|
branchRef := plumbing.NewBranchReferenceName(ref)
|
||||||
return config.RefSpec(fmt.Sprintf("+%s:%s", branchRef, remoteRef)), true
|
return config.RefSpec(fmt.Sprintf("+%s:%s", branchRef, remoteRef)), true
|
||||||
}
|
}
|
||||||
|
if plumbing.IsHash(ref) {
|
||||||
|
// The broad refspec carries only advertised tips, never a pinned commit.
|
||||||
|
return pinnedRefSpec(ref), true
|
||||||
|
}
|
||||||
return "", false
|
return "", false
|
||||||
}
|
}
|
||||||
+110
-6
@@ -16,6 +16,7 @@ import (
|
|||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
|
"sync/atomic"
|
||||||
"syscall"
|
"syscall"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
@@ -24,6 +25,9 @@ import (
|
|||||||
|
|
||||||
gogit "github.com/go-git/go-git/v5"
|
gogit "github.com/go-git/go-git/v5"
|
||||||
gogitconfig "github.com/go-git/go-git/v5/config"
|
gogitconfig "github.com/go-git/go-git/v5/config"
|
||||||
|
"github.com/go-git/go-git/v5/plumbing/transport"
|
||||||
|
gogitclient "github.com/go-git/go-git/v5/plumbing/transport/client"
|
||||||
|
gogitfile "github.com/go-git/go-git/v5/plumbing/transport/file"
|
||||||
log "github.com/sirupsen/logrus"
|
log "github.com/sirupsen/logrus"
|
||||||
logrustest "github.com/sirupsen/logrus/hooks/test"
|
logrustest "github.com/sirupsen/logrus/hooks/test"
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
@@ -435,7 +439,7 @@ func TestGitCloneExecutorShallow(t *testing.T) {
|
|||||||
require.NoError(t, gitCmd("-C", workDir, "commit", "--allow-empty", "-m", m))
|
require.NoError(t, gitCmd("-C", workDir, "commit", "--allow-empty", "-m", m))
|
||||||
}
|
}
|
||||||
require.NoError(t, gitCmd("-C", workDir, "tag", "v1"))
|
require.NoError(t, gitCmd("-C", workDir, "tag", "v1"))
|
||||||
sha := gitRevParse(t, workDir, "HEAD~1") // c2, a SHA that go-git cannot shallow-clone
|
unadvertisedSHA := gitRevParse(t, workDir, "HEAD~1")
|
||||||
require.NoError(t, gitCmd("-C", workDir, "push", "-u", "origin", "main"))
|
require.NoError(t, gitCmd("-C", workDir, "push", "-u", "origin", "main"))
|
||||||
require.NoError(t, gitCmd("-C", workDir, "push", "origin", "v1"))
|
require.NoError(t, gitCmd("-C", workDir, "push", "origin", "v1"))
|
||||||
|
|
||||||
@@ -461,14 +465,43 @@ func TestGitCloneExecutorShallow(t *testing.T) {
|
|||||||
assert.Equal(t, "c3", gitHeadSubject(t, dir))
|
assert.Equal(t, "c3", gitHeadSubject(t, dir))
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("SHA falls back to a full clone", func(t *testing.T) {
|
unadvertisedRemote := func(t *testing.T, allowUnadvertised bool) string {
|
||||||
|
remote := filepath.Join(t.TempDir(), "remote.git")
|
||||||
|
require.NoError(t, gitCmd("clone", "--bare", remoteDir, remote))
|
||||||
|
require.NoError(t, gitCmd("-C", remote, "config", "uploadpack.allowAnySHA1InWant", strconv.FormatBool(allowUnadvertised)))
|
||||||
|
return remote
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Run("commit hash falls back to a full clone when the remote refuses unadvertised objects", func(t *testing.T) {
|
||||||
dir := t.TempDir()
|
dir := t.TempDir()
|
||||||
require.NoError(t, NewGitCloneExecutor(NewGitCloneExecutorInput{
|
require.NoError(t, NewGitCloneExecutor(NewGitCloneExecutorInput{
|
||||||
URL: remoteDir, Ref: sha, Dir: dir, Depth: 1,
|
URL: unadvertisedRemote(t, false), Ref: unadvertisedSHA, Dir: dir, Depth: 1,
|
||||||
})(t.Context()))
|
})(t.Context()))
|
||||||
// go-git cannot shallow-clone a raw SHA, so it falls back to a full clone; the absence of a shallow marker proves the fallback happened.
|
assert.NoFileExists(t, shallowMarker(dir))
|
||||||
assert.NoFileExists(t, shallowMarker(dir), "a SHA ref must not produce a shallow clone")
|
assert.Equal(t, unadvertisedSHA, gitRevParse(t, dir, "HEAD"))
|
||||||
assert.Equal(t, sha, gitRevParse(t, dir, "HEAD"))
|
})
|
||||||
|
|
||||||
|
t.Run("commit hash is fetched shallowly, moved to another hash, then reused without reaching the remote", func(t *testing.T) {
|
||||||
|
remote := unadvertisedRemote(t, true)
|
||||||
|
dir := t.TempDir()
|
||||||
|
cloneAt := func(ref string) error {
|
||||||
|
return NewGitCloneExecutor(NewGitCloneExecutorInput{
|
||||||
|
URL: remote, Ref: ref, Dir: dir, Depth: 1,
|
||||||
|
})(t.Context())
|
||||||
|
}
|
||||||
|
|
||||||
|
require.NoError(t, cloneAt(unadvertisedSHA))
|
||||||
|
assert.FileExists(t, shallowMarker(dir))
|
||||||
|
assert.Equal(t, 1, gitRevCount(t, dir))
|
||||||
|
assert.Equal(t, unadvertisedSHA, gitRevParse(t, dir, "HEAD"))
|
||||||
|
|
||||||
|
olderSHA := gitRevParse(t, workDir, "HEAD~2")
|
||||||
|
require.NoError(t, cloneAt(olderSHA))
|
||||||
|
assert.Equal(t, olderSHA, gitRevParse(t, dir, "HEAD"))
|
||||||
|
|
||||||
|
require.NoError(t, os.RemoveAll(remote))
|
||||||
|
require.NoError(t, cloneAt(olderSHA))
|
||||||
|
assert.Equal(t, olderSHA, gitRevParse(t, dir, "HEAD"))
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("moving branch updates while staying shallow", func(t *testing.T) {
|
t.Run("moving branch updates while staying shallow", func(t *testing.T) {
|
||||||
@@ -491,6 +524,77 @@ func TestGitCloneExecutorShallow(t *testing.T) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestGitCloneExecutorColdCloneSkipsRefresh(t *testing.T) {
|
||||||
|
remoteDir := t.TempDir()
|
||||||
|
require.NoError(t, gitCmd("init", "--bare", "--initial-branch=main", remoteDir))
|
||||||
|
workDir := t.TempDir()
|
||||||
|
require.NoError(t, gitCmd("clone", remoteDir, workDir))
|
||||||
|
require.NoError(t, gitCmd("-C", workDir, "checkout", "-b", "main"))
|
||||||
|
require.NoError(t, gitCmd("-C", workDir, "commit", "--allow-empty", "-m", "c1"))
|
||||||
|
require.NoError(t, gitCmd("-C", workDir, "tag", "v1"))
|
||||||
|
require.NoError(t, gitCmd("-C", workDir, "push", "-u", "origin", "main"))
|
||||||
|
require.NoError(t, gitCmd("-C", workDir, "push", "origin", "v1"))
|
||||||
|
|
||||||
|
for name, tt := range map[string]struct {
|
||||||
|
Ref string
|
||||||
|
Depth int
|
||||||
|
}{
|
||||||
|
"shallow branch": {"main", 1},
|
||||||
|
"full clone tag": {"v1", 0},
|
||||||
|
} {
|
||||||
|
t.Run(name, func(t *testing.T) {
|
||||||
|
counter := installCountingTransport(t)
|
||||||
|
require.NoError(t, NewGitCloneExecutor(NewGitCloneExecutorInput{
|
||||||
|
URL: remoteDir, Ref: tt.Ref, Dir: t.TempDir(), Depth: tt.Depth,
|
||||||
|
})(t.Context()))
|
||||||
|
assert.Equal(t, int64(1), counter.sessions.Load())
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGitCloneExecutorPinnedHashIgnoresShadowingRef(t *testing.T) {
|
||||||
|
remoteDir := t.TempDir()
|
||||||
|
require.NoError(t, gitCmd("init", "--bare", "--initial-branch=main", remoteDir))
|
||||||
|
workDir := t.TempDir()
|
||||||
|
require.NoError(t, gitCmd("clone", remoteDir, workDir))
|
||||||
|
require.NoError(t, gitCmd("-C", workDir, "checkout", "-b", "main"))
|
||||||
|
require.NoError(t, gitCmd("-C", workDir, "commit", "--allow-empty", "-m", "pinned"))
|
||||||
|
pinned := gitRevParse(t, workDir, "HEAD")
|
||||||
|
require.NoError(t, gitCmd("-C", workDir, "commit", "--allow-empty", "-m", "decoy"))
|
||||||
|
require.NoError(t, gitCmd("-C", workDir, "tag", pinned))
|
||||||
|
require.NoError(t, gitCmd("-C", workDir, "push", "-u", "origin", "main"))
|
||||||
|
require.NoError(t, gitCmd("-C", workDir, "push", "origin", pinned))
|
||||||
|
|
||||||
|
for name, depth := range map[string]int{"shallow": 1, "full clone": 0} {
|
||||||
|
t.Run(name, func(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
require.NoError(t, NewGitCloneExecutor(NewGitCloneExecutorInput{
|
||||||
|
URL: remoteDir, Ref: pinned, Dir: dir, Depth: depth,
|
||||||
|
})(t.Context()))
|
||||||
|
assert.Equal(t, pinned, gitRevParse(t, dir, "HEAD"))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type countingTransport struct {
|
||||||
|
transport.Transport
|
||||||
|
sessions atomic.Int64
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *countingTransport) NewUploadPackSession(ep *transport.Endpoint, auth transport.AuthMethod) (transport.UploadPackSession, error) {
|
||||||
|
c.sessions.Add(1)
|
||||||
|
return c.Transport.NewUploadPackSession(ep, auth)
|
||||||
|
}
|
||||||
|
|
||||||
|
func installCountingTransport(t *testing.T) *countingTransport {
|
||||||
|
t.Helper()
|
||||||
|
counter := &countingTransport{Transport: gogitfile.DefaultClient}
|
||||||
|
gogitclient.InstallProtocol("file", counter)
|
||||||
|
t.Cleanup(func() { gogitclient.InstallProtocol("file", gogitfile.DefaultClient) })
|
||||||
|
|
||||||
|
return counter
|
||||||
|
}
|
||||||
|
|
||||||
func gitRevParse(t *testing.T, dir, rev string) string {
|
func gitRevParse(t *testing.T, dir, rev string) string {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
out, err := exec.Command("git", "-C", dir, "rev-parse", rev).Output()
|
out, err := exec.Command("git", "-C", dir, "rev-parse", rev).Output()
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
|
"sync"
|
||||||
|
|
||||||
"gitea.com/gitea/runner/act/common"
|
"gitea.com/gitea/runner/act/common"
|
||||||
|
|
||||||
@@ -75,6 +76,19 @@ const (
|
|||||||
// fragment, missingContainerError composes it into the message every operation shares.
|
// fragment, missingContainerError composes it into the message every operation shares.
|
||||||
var ErrContainerNotFound = errors.New("does not exist")
|
var ErrContainerNotFound = errors.New("does not exist")
|
||||||
|
|
||||||
|
// DockerProxy is a job's docker socket, fronting the daemon's for the job's lifetime.
|
||||||
|
type DockerProxy struct {
|
||||||
|
Socket string
|
||||||
|
close func(context.Context) error
|
||||||
|
closeOnce sync.Once
|
||||||
|
closeErr error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *DockerProxy) Close(ctx context.Context) error {
|
||||||
|
p.closeOnce.Do(func() { p.closeErr = p.close(ctx) })
|
||||||
|
return p.closeErr
|
||||||
|
}
|
||||||
|
|
||||||
// Info is a snapshot of a container, as of one inspect.
|
// Info is a snapshot of a container, as of one inspect.
|
||||||
type Info struct {
|
type Info struct {
|
||||||
ID string
|
ID string
|
||||||
@@ -84,13 +98,14 @@ type Info struct {
|
|||||||
// HealthOutput is the last healthcheck probe's output.
|
// HealthOutput is the last healthcheck probe's output.
|
||||||
HealthOutput string
|
HealthOutput string
|
||||||
Ports map[string]string // container port ("5432") to the host port it is published on
|
Ports map[string]string // container port ("5432") to the host port it is published on
|
||||||
|
Mounts map[string]string // container path to its source on the daemon
|
||||||
}
|
}
|
||||||
|
|
||||||
// Container for managing docker run containers
|
// Container for managing docker run containers
|
||||||
type Container interface {
|
type Container interface {
|
||||||
Create(capAdd, capDrop []string) common.Executor
|
Create(capAdd, capDrop []string) common.Executor
|
||||||
Copy(destPath string, files ...*FileEntry) common.Executor
|
Copy(destPath string, files ...*FileEntry) common.Executor
|
||||||
CopyDir(destPath, srcPath string, useGitIgnore bool) common.Executor
|
CopyDir(destPath, srcPath string, useGitIgnore, skipGitDir bool) common.Executor
|
||||||
GetContainerArchive(ctx context.Context, srcPath string) (io.ReadCloser, error)
|
GetContainerArchive(ctx context.Context, srcPath string) (io.ReadCloser, error)
|
||||||
Inspect(ctx context.Context) (*Info, error)
|
Inspect(ctx context.Context) (*Info, error)
|
||||||
DumpLogs(ctx context.Context) error
|
DumpLogs(ctx context.Context) error
|
||||||
|
|||||||
@@ -0,0 +1,395 @@
|
|||||||
|
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
//go:build !(WITHOUT_DOCKER || !(linux || darwin || windows || netbsd))
|
||||||
|
|
||||||
|
package container
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"maps"
|
||||||
|
"mime"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httputil"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"regexp"
|
||||||
|
"runtime"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"gitea.com/gitea/runner/act/common"
|
||||||
|
|
||||||
|
cerrdefs "github.com/containerd/errdefs"
|
||||||
|
"github.com/moby/moby/api/types/container"
|
||||||
|
"github.com/moby/moby/api/types/mount"
|
||||||
|
"github.com/moby/moby/client"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
jobLabel = "com.gitea.runner.job"
|
||||||
|
maxCreateBody = 8 << 20
|
||||||
|
|
||||||
|
dockerProxyProbeTimeout = 5 * time.Second
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
createPath = regexp.MustCompile(`^(/v[0-9.]+)?/(containers|networks|volumes)/create$`)
|
||||||
|
rawStreamPath = regexp.MustCompile(`^(/v[0-9.]+)?/(containers/[^/]+/attach|exec/[^/]+/start)$`)
|
||||||
|
)
|
||||||
|
|
||||||
|
func NewDockerProxy(ctx context.Context, job string) *DockerProxy {
|
||||||
|
if host := os.Getenv("DOCKER_HOST"); runtime.GOOS != "linux" || host != "" && !strings.HasPrefix(host, "unix://") {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
probeCtx, cancel := context.WithTimeout(ctx, dockerProxyProbeTimeout)
|
||||||
|
defer cancel()
|
||||||
|
cli, err := GetDockerClient(probeCtx)
|
||||||
|
if err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
defer cli.Close()
|
||||||
|
daemonSocket, ok := strings.CutPrefix(cli.DaemonHost(), "unix://")
|
||||||
|
if !ok {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if info, err := os.Stat(daemonSocket); err != nil || info.Mode()&os.ModeSocket == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
dir, err := filepath.Abs(os.TempDir())
|
||||||
|
if err != nil {
|
||||||
|
common.Logger(ctx).Infof("docker proxy probe failed, jobs get the daemon socket directly: %v", err)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
seen, err := daemonSeesDir(probeCtx, cli, dir)
|
||||||
|
if err != nil {
|
||||||
|
common.Logger(ctx).Infof("docker proxy probe failed, jobs get the daemon socket directly: %v", err)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if !seen {
|
||||||
|
common.Logger(ctx).Infof("the docker daemon cannot reach the runner's temporary filesystem, jobs get the daemon socket directly")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
proxy, err := StartDockerProxy(daemonSocket, dir, job)
|
||||||
|
if err != nil {
|
||||||
|
common.Logger(ctx).Warnf("docker proxy not started, the job gets the daemon socket directly: %v", err)
|
||||||
|
}
|
||||||
|
return proxy
|
||||||
|
}
|
||||||
|
|
||||||
|
// daemonSeesDir reports whether the daemon opens the files the runner writes in dir,
|
||||||
|
// which is what a job's proxy socket mounted from there needs.
|
||||||
|
func daemonSeesDir(ctx context.Context, cli client.APIClient, dir string) (bool, error) {
|
||||||
|
marker, err := os.CreateTemp(dir, "gitea-runner-probe-")
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
defer func() {
|
||||||
|
if err := os.Remove(marker.Name()); err != nil {
|
||||||
|
common.Logger(ctx).Warnf("removing the docker proxy probe marker failed: %v", err)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
if err := marker.Close(); err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
images, err := cli.ImageList(ctx, client.ImageListOptions{})
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
if len(images.Items) == 0 {
|
||||||
|
return false, errors.New("no image available for the docker proxy probe")
|
||||||
|
}
|
||||||
|
created, err := cli.ContainerCreate(ctx, client.ContainerCreateOptions{
|
||||||
|
Config: &container.Config{Image: images.Items[0].ID, Cmd: []string{"true"}},
|
||||||
|
HostConfig: &container.HostConfig{Mounts: []mount.Mount{
|
||||||
|
{Type: mount.TypeBind, Source: marker.Name(), Target: "/gitea-runner-probe", ReadOnly: true},
|
||||||
|
}},
|
||||||
|
})
|
||||||
|
if cerrdefs.IsInvalidArgument(err) {
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), dockerProxyProbeTimeout)
|
||||||
|
defer cancel()
|
||||||
|
if _, err := cli.ContainerRemove(cleanupCtx, created.ID, client.ContainerRemoveOptions{Force: true, RemoveVolumes: true}); err != nil {
|
||||||
|
return false, fmt.Errorf("removing the docker proxy probe container failed: %w", err)
|
||||||
|
}
|
||||||
|
return true, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// StartDockerProxy serves a job's docker socket in dir, labelling what the job creates through it.
|
||||||
|
func StartDockerProxy(daemonSocket, dir, job string) (*DockerProxy, error) {
|
||||||
|
info, err := os.Stat(daemonSocket)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if info.Mode()&os.ModeSocket == 0 {
|
||||||
|
return nil, errors.New("docker daemon path is not a Unix socket")
|
||||||
|
}
|
||||||
|
if err := os.MkdirAll(dir, 0o700); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
instance, err := os.MkdirTemp(dir, "p-")
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
socket := filepath.Join(instance, "docker.sock")
|
||||||
|
listener, err := net.Listen("unix", socket)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.Join(err, os.RemoveAll(instance))
|
||||||
|
}
|
||||||
|
if err := copyDockerSocketPermissions(socket, info); err != nil {
|
||||||
|
return nil, errors.Join(err, listener.Close(), os.RemoveAll(instance))
|
||||||
|
}
|
||||||
|
dial := func(ctx context.Context, _, _ string) (net.Conn, error) {
|
||||||
|
return (&net.Dialer{}).DialContext(ctx, "unix", daemonSocket)
|
||||||
|
}
|
||||||
|
transport := &http.Transport{DialContext: dial}
|
||||||
|
forward := &httputil.ReverseProxy{
|
||||||
|
Rewrite: func(r *httputil.ProxyRequest) {
|
||||||
|
r.Out.URL.Scheme = "http"
|
||||||
|
r.Out.URL.Host = "docker"
|
||||||
|
},
|
||||||
|
Transport: transport,
|
||||||
|
}
|
||||||
|
streams, cancelStreams := context.WithCancel(context.Background())
|
||||||
|
creates, cancelCreates := context.WithCancel(context.Background())
|
||||||
|
var admission sync.Mutex
|
||||||
|
var handlers sync.WaitGroup
|
||||||
|
server := &http.Server{ReadHeaderTimeout: 30 * time.Second, ConnContext: func(ctx context.Context, conn net.Conn) context.Context {
|
||||||
|
return context.WithValue(ctx, dockerProxyConnKey{}, conn)
|
||||||
|
}, Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
admission.Lock()
|
||||||
|
if streams.Err() != nil {
|
||||||
|
admission.Unlock()
|
||||||
|
http.Error(w, "docker proxy is closing", http.StatusServiceUnavailable)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
handlers.Add(1)
|
||||||
|
admission.Unlock()
|
||||||
|
defer handlers.Done()
|
||||||
|
creating := r.Method == http.MethodPost && createPath.MatchString(r.URL.Path)
|
||||||
|
parent, lifetime := r.Context(), streams
|
||||||
|
if creating {
|
||||||
|
parent, lifetime = context.WithoutCancel(parent), creates
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithCancel(parent)
|
||||||
|
defer cancel()
|
||||||
|
stop := context.AfterFunc(lifetime, func() {
|
||||||
|
cancel()
|
||||||
|
if !creating {
|
||||||
|
if conn, ok := parent.Value(dockerProxyConnKey{}).(net.Conn); ok {
|
||||||
|
_ = conn.Close()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
defer stop()
|
||||||
|
r = r.WithContext(ctx)
|
||||||
|
if creating {
|
||||||
|
r.Body = http.MaxBytesReader(w, r.Body, maxCreateBody)
|
||||||
|
if err := addLabel(r, job); err != nil {
|
||||||
|
status := http.StatusBadRequest
|
||||||
|
if _, ok := errors.AsType[*http.MaxBytesError](err); ok {
|
||||||
|
status = http.StatusRequestEntityTooLarge
|
||||||
|
}
|
||||||
|
http.Error(w, err.Error(), status)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
} else if r.Method == http.MethodPost && rawStreamPath.MatchString(r.URL.Path) {
|
||||||
|
tunnel(w, r, dial, forward)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
forward.ServeHTTP(w, r)
|
||||||
|
})}
|
||||||
|
served := make(chan struct{})
|
||||||
|
go func() {
|
||||||
|
defer close(served)
|
||||||
|
_ = server.Serve(listener)
|
||||||
|
}()
|
||||||
|
return &DockerProxy{Socket: socket, close: func(ctx context.Context) error {
|
||||||
|
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
admission.Lock()
|
||||||
|
listenerErr := listener.Close()
|
||||||
|
cancelStreams()
|
||||||
|
admission.Unlock()
|
||||||
|
<-served
|
||||||
|
shutdownErr := server.Shutdown(ctx)
|
||||||
|
cancelCreates()
|
||||||
|
serverErr := server.Close()
|
||||||
|
handlers.Wait()
|
||||||
|
transport.CloseIdleConnections()
|
||||||
|
return errors.Join(ctx.Err(), listenerErr, shutdownErr, serverErr, os.RemoveAll(instance))
|
||||||
|
}}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func addLabel(r *http.Request, job string) error {
|
||||||
|
body, err := io.ReadAll(r.Body)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if len(bytes.TrimSpace(body)) == 0 {
|
||||||
|
body = []byte("{}")
|
||||||
|
}
|
||||||
|
var fields map[string]json.RawMessage
|
||||||
|
var config struct{ Labels map[string]string }
|
||||||
|
if err := json.Unmarshal(body, &fields); err != nil {
|
||||||
|
return fmt.Errorf("invalid create request: %w", err)
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(body, &config); err != nil {
|
||||||
|
return fmt.Errorf("invalid create labels: %w", err)
|
||||||
|
}
|
||||||
|
if fields == nil {
|
||||||
|
fields = make(map[string]json.RawMessage)
|
||||||
|
}
|
||||||
|
maps.DeleteFunc(fields, func(name string, _ json.RawMessage) bool {
|
||||||
|
return strings.EqualFold(name, "Labels")
|
||||||
|
})
|
||||||
|
if config.Labels == nil {
|
||||||
|
config.Labels = make(map[string]string)
|
||||||
|
}
|
||||||
|
config.Labels[jobLabel] = job
|
||||||
|
if fields["Labels"], err = json.Marshal(config.Labels); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if body, err = json.Marshal(fields); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
r.Body = io.NopCloser(bytes.NewReader(body))
|
||||||
|
r.ContentLength = int64(len(body))
|
||||||
|
r.TransferEncoding = nil
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type dockerProxyConnKey struct{}
|
||||||
|
|
||||||
|
type dockerProxyResponse struct {
|
||||||
|
response *http.Response
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r dockerProxyResponse) RoundTrip(_ *http.Request) (*http.Response, error) {
|
||||||
|
return r.response, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// tunnel splices attach and exec streams, which the daemon hijacks with or without an HTTP upgrade
|
||||||
|
func tunnel(w http.ResponseWriter, r *http.Request, dial func(context.Context, string, string) (net.Conn, error), forward *httputil.ReverseProxy) {
|
||||||
|
upstream, err := dial(r.Context(), "", "")
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusBadGateway)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer upstream.Close()
|
||||||
|
stop := context.AfterFunc(r.Context(), func() { _ = upstream.Close() })
|
||||||
|
defer stop()
|
||||||
|
if err := r.Write(upstream); err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusBadGateway)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
reader := bufio.NewReader(upstream)
|
||||||
|
var response *http.Response
|
||||||
|
for {
|
||||||
|
response, err = http.ReadResponse(reader, r)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusBadGateway)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if response.StatusCode >= 200 || response.StatusCode == http.StatusSwitchingProtocols {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
maps.Copy(w.Header(), response.Header)
|
||||||
|
w.WriteHeader(response.StatusCode)
|
||||||
|
clear(w.Header())
|
||||||
|
_ = response.Body.Close()
|
||||||
|
}
|
||||||
|
defer func() {
|
||||||
|
_ = upstream.Close()
|
||||||
|
_ = response.Body.Close()
|
||||||
|
}()
|
||||||
|
mediaType, _, _ := mime.ParseMediaType(response.Header.Get("Content-Type"))
|
||||||
|
if response.StatusCode != http.StatusSwitchingProtocols && (response.StatusCode != http.StatusOK || mediaType != "application/vnd.docker.raw-stream") {
|
||||||
|
ordinary := *forward
|
||||||
|
ordinary.Transport = dockerProxyResponse{response: response}
|
||||||
|
ordinary.ServeHTTP(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
downstream, buffered, err := http.NewResponseController(w).Hijack()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer downstream.Close()
|
||||||
|
if _, err := fmt.Fprintf(buffered, "%s %s\r\n", response.Proto, response.Status); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := response.Header.Write(buffered); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if _, err := buffered.WriteString("\r\n"); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := buffered.Flush(); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
done := make(chan struct{})
|
||||||
|
go func() {
|
||||||
|
defer close(done)
|
||||||
|
if _, err := io.Copy(upstream, io.MultiReader(io.LimitReader(buffered, int64(buffered.Reader.Buffered())), downstream)); err != nil { // Bypass net/http after the prefix so stdin EOF preserves output.
|
||||||
|
_ = upstream.Close()
|
||||||
|
} else if writer, ok := upstream.(interface{ CloseWrite() error }); ok {
|
||||||
|
_ = writer.CloseWrite()
|
||||||
|
} else {
|
||||||
|
_ = upstream.Close()
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
_, _ = io.Copy(downstream, reader)
|
||||||
|
_ = downstream.Close()
|
||||||
|
_ = upstream.Close()
|
||||||
|
<-done
|
||||||
|
}
|
||||||
|
|
||||||
|
func RemoveDockerJobResources(ctx context.Context, job string) error {
|
||||||
|
cli, err := GetDockerClient(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer cli.Close()
|
||||||
|
return removeLabelled(ctx, cli, job)
|
||||||
|
}
|
||||||
|
|
||||||
|
func removeLabelled(ctx context.Context, cli client.APIClient, job string) error {
|
||||||
|
logger := common.Logger(ctx)
|
||||||
|
filters := make(client.Filters).Add("label", jobLabel+"="+job)
|
||||||
|
containers, err := cli.ContainerList(ctx, client.ContainerListOptions{All: true, Filters: filters})
|
||||||
|
errs := []error{err}
|
||||||
|
for _, c := range containers.Items {
|
||||||
|
logger.Infof("removing container %s the job left behind", strings.TrimPrefix(strings.Join(c.Names, ","), "/"))
|
||||||
|
errs = append(errs, (&containerReference{cli: cli, id: c.ID}).remove()(ctx))
|
||||||
|
}
|
||||||
|
networks, err := cli.NetworkList(ctx, client.NetworkListOptions{Filters: filters})
|
||||||
|
errs = append(errs, err)
|
||||||
|
for _, n := range networks.Items {
|
||||||
|
if _, err := cli.NetworkRemove(ctx, n.ID, client.NetworkRemoveOptions{}); err != nil && !cerrdefs.IsNotFound(err) {
|
||||||
|
errs = append(errs, fmt.Errorf("failed to remove network %s: %w", n.Name, err))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
volumes, err := cli.VolumeList(ctx, client.VolumeListOptions{Filters: filters})
|
||||||
|
errs = append(errs, err)
|
||||||
|
for _, v := range volumes.Items {
|
||||||
|
if _, err := cli.VolumeRemove(ctx, v.Name, client.VolumeRemoveOptions{}); err != nil && !cerrdefs.IsNotFound(err) {
|
||||||
|
errs = append(errs, fmt.Errorf("failed to remove volume %s: %w", v.Name, err))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return errors.Join(errs...)
|
||||||
|
}
|
||||||
@@ -0,0 +1,469 @@
|
|||||||
|
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
//go:build !(WITHOUT_DOCKER || !(linux || darwin || windows || netbsd))
|
||||||
|
|
||||||
|
package container
|
||||||
|
|
||||||
|
import (
|
||||||
|
"archive/tar"
|
||||||
|
"bufio"
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"runtime"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
cerrdefs "github.com/containerd/errdefs"
|
||||||
|
"github.com/moby/moby/api/types/container"
|
||||||
|
"github.com/moby/moby/api/types/image"
|
||||||
|
"github.com/moby/moby/api/types/mount"
|
||||||
|
"github.com/moby/moby/api/types/volume"
|
||||||
|
mobyclient "github.com/moby/moby/client"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/mock"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (m *mockDockerClient) VolumeList(ctx context.Context, opts mobyclient.VolumeListOptions) (mobyclient.VolumeListResult, error) {
|
||||||
|
args := m.Called(ctx, opts)
|
||||||
|
return args.Get(0).(mobyclient.VolumeListResult), args.Error(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *mockDockerClient) VolumeRemove(ctx context.Context, id string, opts mobyclient.VolumeRemoveOptions) (mobyclient.VolumeRemoveResult, error) {
|
||||||
|
args := m.Called(ctx, id, opts)
|
||||||
|
return args.Get(0).(mobyclient.VolumeRemoveResult), args.Error(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
// unix socket paths are limited to about a hundred bytes, which the default macOS TMPDIR exceeds
|
||||||
|
func shortTempDir(t testing.TB) string {
|
||||||
|
t.Helper()
|
||||||
|
t.Setenv("TMPDIR", "/tmp")
|
||||||
|
return t.TempDir()
|
||||||
|
}
|
||||||
|
|
||||||
|
func daemonSocketPath(t testing.TB, cli mobyclient.APIClient) string {
|
||||||
|
t.Helper()
|
||||||
|
host := cli.DaemonHost()
|
||||||
|
if !strings.HasPrefix(host, "unix://") {
|
||||||
|
t.Skipf("skipping: daemon at %s is not a unix socket", host)
|
||||||
|
}
|
||||||
|
return strings.TrimPrefix(host, "unix://")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDockerProxy(t *testing.T) {
|
||||||
|
if runtime.GOOS == "windows" {
|
||||||
|
t.Skip("Unix socket ownership is unavailable on Windows")
|
||||||
|
}
|
||||||
|
bodies := make(chan []byte, 8)
|
||||||
|
createStarted, releaseCreate := make(chan struct{}), make(chan struct{})
|
||||||
|
streamsDone := make(chan struct{}, 2)
|
||||||
|
daemonSocket := filepath.Join(shortTempDir(t), "d.sock")
|
||||||
|
listener, err := net.Listen("unix", daemonSocket)
|
||||||
|
require.NoError(t, err)
|
||||||
|
daemon := &http.Server{ReadHeaderTimeout: time.Second, Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
switch {
|
||||||
|
case strings.HasSuffix(r.URL.Path, "/create"):
|
||||||
|
body, _ := io.ReadAll(r.Body)
|
||||||
|
if r.URL.RawQuery == "wait" {
|
||||||
|
close(createStarted)
|
||||||
|
<-releaseCreate
|
||||||
|
}
|
||||||
|
bodies <- body
|
||||||
|
w.WriteHeader(http.StatusCreated)
|
||||||
|
case r.URL.Path == "/exec/detached/start" || r.URL.Path == "/exec/error/start":
|
||||||
|
if r.URL.Path == "/exec/error/start" {
|
||||||
|
w.Header().Set("Content-Type", "application/vnd.docker.raw-stream")
|
||||||
|
w.WriteHeader(http.StatusBadRequest)
|
||||||
|
}
|
||||||
|
_, _ = w.Write([]byte("ordinary"))
|
||||||
|
case rawStreamPath.MatchString(r.URL.Path) || r.URL.Path == "/session":
|
||||||
|
_, _ = io.Copy(io.Discard, r.Body)
|
||||||
|
conn, buffered, err := w.(http.Hijacker).Hijack()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer conn.Close()
|
||||||
|
if r.Header.Get("Upgrade") != "" {
|
||||||
|
_, _ = conn.Write([]byte("HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nUpgrade: tcp\r\n\r\nready\n"))
|
||||||
|
} else {
|
||||||
|
_, _ = conn.Write([]byte("HTTP/1.1 200 OK\r\nContent-Type: application/vnd.docker.raw-stream\r\n\r\nready\n"))
|
||||||
|
}
|
||||||
|
input, _ := io.ReadAll(buffered)
|
||||||
|
_, _ = conn.Write(append([]byte("final:"), input...))
|
||||||
|
streamsDone <- struct{}{}
|
||||||
|
default:
|
||||||
|
w.Header().Set("Api-Version", "1.47")
|
||||||
|
_, _ = w.Write([]byte("OK " + r.Method + " " + r.URL.Path))
|
||||||
|
}
|
||||||
|
})}
|
||||||
|
go func() { _ = daemon.Serve(listener) }()
|
||||||
|
t.Cleanup(func() { _ = daemon.Close() })
|
||||||
|
proxy, err := StartDockerProxy(daemonSocket, shortTempDir(t), "job-1")
|
||||||
|
require.NoError(t, err)
|
||||||
|
t.Cleanup(func() { _ = proxy.Close(context.Background()) })
|
||||||
|
client := &http.Client{Timeout: 5 * time.Second, Transport: &http.Transport{DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
|
||||||
|
return (&net.Dialer{}).DialContext(ctx, "unix", proxy.Socket)
|
||||||
|
}}}
|
||||||
|
t.Cleanup(client.CloseIdleConnections)
|
||||||
|
dialProxy := func(t *testing.T) *net.UnixConn {
|
||||||
|
t.Helper()
|
||||||
|
conn, err := net.DialUnix("unix", nil, &net.UnixAddr{Name: proxy.Socket, Net: "unix"})
|
||||||
|
require.NoError(t, err)
|
||||||
|
t.Cleanup(func() { _ = conn.Close() })
|
||||||
|
require.NoError(t, conn.SetDeadline(time.Now().Add(5*time.Second)))
|
||||||
|
return conn
|
||||||
|
}
|
||||||
|
startStream := func(t *testing.T, path, upgrade string) (*net.UnixConn, *bufio.Reader) {
|
||||||
|
t.Helper()
|
||||||
|
conn := dialProxy(t)
|
||||||
|
_, err := fmt.Fprintf(conn, "POST %s HTTP/1.1\r\nHost: docker\r\n%sContent-Length: 2\r\n\r\n{}input", path, upgrade)
|
||||||
|
require.NoError(t, err)
|
||||||
|
reader := bufio.NewReader(conn)
|
||||||
|
resp, err := http.ReadResponse(reader, nil)
|
||||||
|
require.NoError(t, err)
|
||||||
|
t.Cleanup(func() {
|
||||||
|
_ = conn.Close()
|
||||||
|
_ = resp.Body.Close()
|
||||||
|
})
|
||||||
|
prefix, err := reader.ReadString('\n')
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.Equal(t, "ready\n", prefix)
|
||||||
|
return conn, reader
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Run("labels creates", func(t *testing.T) {
|
||||||
|
for _, testCase := range []struct{ path, body, want string }{
|
||||||
|
{
|
||||||
|
"/v1.47/containers/create", `{"Image":"alpine","Unknown":{"enabled":true},"Labels":{"own":"1","com.gitea.runner.job":"other"}}`,
|
||||||
|
`{"Image":"alpine","Unknown":{"enabled":true},"Labels":{"own":"1","com.gitea.runner.job":"job-1"}}`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"/networks/create", `{"Name":"n"}`,
|
||||||
|
`{"Name":"n","Labels":{"com.gitea.runner.job":"job-1"}}`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"/volumes/create", `{"Name":"v","labels":null}`,
|
||||||
|
`{"Name":"v","Labels":{"com.gitea.runner.job":"job-1"}}`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"/volumes/create", "",
|
||||||
|
`{"Labels":{"com.gitea.runner.job":"job-1"}}`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"/volumes/create", "null",
|
||||||
|
`{"Labels":{"com.gitea.runner.job":"job-1"}}`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"/volumes/create", `{"Labels":{"discard":"1"},"labels":null,"LABELS":{"own":"1"},"LABELS":{"extra":"2"}}`,
|
||||||
|
`{"Labels":{"own":"1","extra":"2","com.gitea.runner.job":"job-1"}}`,
|
||||||
|
},
|
||||||
|
} {
|
||||||
|
resp, err := client.Post("http://docker"+testCase.path, "application/json", strings.NewReader(testCase.body))
|
||||||
|
require.NoError(t, err)
|
||||||
|
resp.Body.Close()
|
||||||
|
require.Equal(t, http.StatusCreated, resp.StatusCode)
|
||||||
|
assert.JSONEq(t, testCase.want, string(<-bodies), testCase.body)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("passes other requests through", func(t *testing.T) {
|
||||||
|
resp, err := client.Get("http://docker/v1.47/_ping")
|
||||||
|
require.NoError(t, err)
|
||||||
|
defer resp.Body.Close()
|
||||||
|
body, _ := io.ReadAll(resp.Body)
|
||||||
|
assert.Equal(t, "1.47", resp.Header.Get("Api-Version"))
|
||||||
|
assert.Equal(t, "OK GET /v1.47/_ping", string(body))
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("tunnels raw streams through stdin EOF", func(t *testing.T) {
|
||||||
|
for _, stream := range []struct{ path, upgrade string }{
|
||||||
|
{path: "/v1.47/exec/abc/start"},
|
||||||
|
{path: "/containers/abc/attach", upgrade: "Connection: Upgrade\r\nUpgrade: tcp\r\n"},
|
||||||
|
} {
|
||||||
|
conn, reader := startStream(t, stream.path, stream.upgrade)
|
||||||
|
require.NoError(t, conn.CloseWrite())
|
||||||
|
output, err := io.ReadAll(reader)
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.Equal(t, "final:input", string(output))
|
||||||
|
<-streamsDone
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("detached and error responses retain keepalive label injection", func(t *testing.T) {
|
||||||
|
conn := dialProxy(t)
|
||||||
|
reader := bufio.NewReader(conn)
|
||||||
|
for endpoint, status := range map[string]int{"detached": http.StatusOK, "error": http.StatusBadRequest} {
|
||||||
|
_, err := fmt.Fprintf(conn, "POST /exec/%s/start HTTP/1.1\r\nHost: docker\r\nContent-Length: 2\r\n\r\n{}", endpoint)
|
||||||
|
require.NoError(t, err)
|
||||||
|
resp, err := http.ReadResponse(reader, nil)
|
||||||
|
require.NoError(t, err)
|
||||||
|
body, err := io.ReadAll(resp.Body)
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.NoError(t, resp.Body.Close())
|
||||||
|
assert.Equal(t, status, resp.StatusCode)
|
||||||
|
assert.Equal(t, "ordinary", string(body))
|
||||||
|
_, err = io.WriteString(conn, "POST /volumes/create HTTP/1.1\r\nHost: docker\r\nContent-Length: 0\r\n\r\n")
|
||||||
|
require.NoError(t, err)
|
||||||
|
resp, err = http.ReadResponse(reader, nil)
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.NoError(t, resp.Body.Close())
|
||||||
|
require.Equal(t, http.StatusCreated, resp.StatusCode)
|
||||||
|
assert.JSONEq(t, `{"Labels":{"com.gitea.runner.job":"job-1"}}`, string(<-bodies))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("close joins streams and admitted create", func(t *testing.T) {
|
||||||
|
t.Cleanup(func() { close(releaseCreate) })
|
||||||
|
_, raw := startStream(t, "/exec/live/start", "")
|
||||||
|
_, upgraded := startStream(t, "/session", "Connection: Upgrade\r\nUpgrade: tcp\r\n")
|
||||||
|
creator := dialProxy(t)
|
||||||
|
_, err := io.WriteString(creator, "POST /volumes/create?wait HTTP/1.1\r\nHost: docker\r\nContent-Length: 2\r\n\r\n{}")
|
||||||
|
require.NoError(t, err)
|
||||||
|
<-createStarted
|
||||||
|
require.NoError(t, creator.CloseWrite())
|
||||||
|
closed := make(chan error, 1)
|
||||||
|
ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
go func() { closed <- proxy.Close(ctx) }()
|
||||||
|
for _, reader := range []*bufio.Reader{raw, upgraded} {
|
||||||
|
_, err := reader.ReadByte()
|
||||||
|
require.ErrorIs(t, err, io.EOF)
|
||||||
|
<-streamsDone
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case err := <-closed:
|
||||||
|
t.Fatalf("Close returned before admitted create settled: %v", err)
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
releaseCreate <- struct{}{}
|
||||||
|
resp, err := http.ReadResponse(bufio.NewReader(creator), nil)
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.NoError(t, resp.Body.Close())
|
||||||
|
require.Equal(t, http.StatusCreated, resp.StatusCode)
|
||||||
|
assert.JSONEq(t, `{"Labels":{"com.gitea.runner.job":"job-1"}}`, string(<-bodies))
|
||||||
|
require.NoError(t, <-closed)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRemoveLabelledRemovesContainersNetworksAndVolumes(t *testing.T) {
|
||||||
|
containerFailure := errors.New("container removal failed")
|
||||||
|
listFailure := errors.New("listing failed")
|
||||||
|
volumeFailure := errors.New("volume removal failed")
|
||||||
|
ctx := context.Background()
|
||||||
|
filters := make(mobyclient.Filters).Add("label", jobLabel+"=job-1")
|
||||||
|
cli := &mockDockerClient{}
|
||||||
|
cli.On("ContainerList", ctx, mobyclient.ContainerListOptions{All: true, Filters: filters}).
|
||||||
|
Return(mobyclient.ContainerListResult{Items: []container.Summary{{ID: "c1", Names: []string{"/app"}}}}, nil).Once()
|
||||||
|
cli.On("ContainerKill", ctx, "c1", mock.Anything).Return(mobyclient.ContainerKillResult{}, nil).Once()
|
||||||
|
cli.On("ContainerRemove", ctx, "c1", mobyclient.ContainerRemoveOptions{RemoveVolumes: true, Force: true}).
|
||||||
|
Return(mobyclient.ContainerRemoveResult{}, containerFailure).Once()
|
||||||
|
cli.On("NetworkList", ctx, mobyclient.NetworkListOptions{Filters: filters}).Return(mobyclient.NetworkListResult{}, listFailure).Once()
|
||||||
|
cli.On("VolumeList", ctx, mobyclient.VolumeListOptions{Filters: filters}).
|
||||||
|
Return(mobyclient.VolumeListResult{Items: []volume.Volume{{Name: "app_data"}}}, nil).Once()
|
||||||
|
cli.On("VolumeRemove", ctx, "app_data", mobyclient.VolumeRemoveOptions{}).Return(mobyclient.VolumeRemoveResult{}, volumeFailure).Once()
|
||||||
|
|
||||||
|
err := removeLabelled(ctx, cli, "job-1")
|
||||||
|
require.ErrorIs(t, err, containerFailure)
|
||||||
|
require.ErrorIs(t, err, listFailure)
|
||||||
|
require.ErrorIs(t, err, volumeFailure)
|
||||||
|
require.ErrorContains(t, err, "failed to remove container c1")
|
||||||
|
require.ErrorContains(t, err, "failed to remove volume app_data")
|
||||||
|
cli.AssertExpectations(t)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDockerProxyWithDaemon(t *testing.T) {
|
||||||
|
requireDocker(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
require.NoError(t, NewDockerPullExecutor(NewDockerPullExecutorInput{Image: "alpine"})(ctx))
|
||||||
|
direct, err := GetDockerClient(ctx)
|
||||||
|
require.NoError(t, err)
|
||||||
|
defer direct.Close()
|
||||||
|
dir := shortTempDir(t)
|
||||||
|
seen, err := daemonSeesDir(ctx, direct, dir)
|
||||||
|
require.NoError(t, err)
|
||||||
|
t.Logf("daemon sees the runner's filesystem: %v", seen)
|
||||||
|
|
||||||
|
job := "proxy-test-" + strconv.FormatInt(time.Now().UnixNano(), 36)
|
||||||
|
proxy, err := StartDockerProxy(daemonSocketPath(t, direct), dir, job)
|
||||||
|
require.NoError(t, err)
|
||||||
|
t.Cleanup(func() { _ = proxy.Close(context.Background()) })
|
||||||
|
viaProxy, err := mobyclient.New(mobyclient.WithHost("unix://" + proxy.Socket))
|
||||||
|
require.NoError(t, err)
|
||||||
|
defer viaProxy.Close()
|
||||||
|
|
||||||
|
created, err := viaProxy.ContainerCreate(ctx, mobyclient.ContainerCreateOptions{
|
||||||
|
Config: &container.Config{Image: "alpine", Cmd: []string{"sleep", "300"}, Labels: map[string]string{"own": "1"}},
|
||||||
|
})
|
||||||
|
require.NoError(t, err)
|
||||||
|
t.Cleanup(func() { _, _ = direct.ContainerRemove(ctx, created.ID, mobyclient.ContainerRemoveOptions{Force: true}) })
|
||||||
|
_, err = viaProxy.ContainerStart(ctx, created.ID, mobyclient.ContainerStartOptions{})
|
||||||
|
require.NoError(t, err)
|
||||||
|
net, err := viaProxy.NetworkCreate(ctx, job, mobyclient.NetworkCreateOptions{})
|
||||||
|
require.NoError(t, err)
|
||||||
|
t.Cleanup(func() { _, _ = direct.NetworkRemove(ctx, net.ID, mobyclient.NetworkRemoveOptions{}) })
|
||||||
|
_, err = viaProxy.VolumeCreate(ctx, mobyclient.VolumeCreateOptions{Name: job})
|
||||||
|
require.NoError(t, err)
|
||||||
|
t.Cleanup(func() { _, _ = direct.VolumeRemove(ctx, job, mobyclient.VolumeRemoveOptions{Force: true}) })
|
||||||
|
|
||||||
|
inspected, err := direct.ContainerInspect(ctx, created.ID, mobyclient.ContainerInspectOptions{})
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.Equal(t, map[string]string{"own": "1", jobLabel: job}, inspected.Container.Config.Labels)
|
||||||
|
vol, err := direct.VolumeInspect(ctx, job, mobyclient.VolumeInspectOptions{})
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.Equal(t, job, vol.Volume.Labels[jobLabel])
|
||||||
|
|
||||||
|
exec, err := viaProxy.ExecCreate(ctx, created.ID, mobyclient.ExecCreateOptions{Cmd: []string{"cat"}, AttachStdin: true, AttachStdout: true, TTY: true})
|
||||||
|
require.NoError(t, err)
|
||||||
|
attached, err := viaProxy.ExecAttach(ctx, exec.ID, mobyclient.ExecAttachOptions{TTY: true})
|
||||||
|
require.NoError(t, err)
|
||||||
|
_, err = attached.Conn.Write([]byte("hello\n"))
|
||||||
|
require.NoError(t, err)
|
||||||
|
echoed, err := attached.Reader.ReadString('\n')
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.Equal(t, "hello\r\n", echoed)
|
||||||
|
attached.Close()
|
||||||
|
|
||||||
|
require.NoError(t, proxy.Close(ctx))
|
||||||
|
require.NoError(t, RemoveDockerJobResources(ctx, job))
|
||||||
|
_, err = direct.ContainerInspect(ctx, created.ID, mobyclient.ContainerInspectOptions{})
|
||||||
|
assert.True(t, cerrdefs.IsNotFound(err))
|
||||||
|
_, err = direct.NetworkInspect(ctx, net.ID, mobyclient.NetworkInspectOptions{})
|
||||||
|
assert.True(t, cerrdefs.IsNotFound(err))
|
||||||
|
_, err = direct.VolumeInspect(ctx, job, mobyclient.VolumeInspectOptions{})
|
||||||
|
assert.True(t, cerrdefs.IsNotFound(err))
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkDockerProxy(b *testing.B) {
|
||||||
|
ctx := context.Background()
|
||||||
|
direct, err := GetDockerClient(ctx)
|
||||||
|
require.NoError(b, err)
|
||||||
|
defer direct.Close()
|
||||||
|
if _, err := direct.Ping(ctx, mobyclient.PingOptions{}); err != nil {
|
||||||
|
b.Skipf("docker daemon unreachable: %v", err)
|
||||||
|
}
|
||||||
|
proxy, err := StartDockerProxy(daemonSocketPath(b, direct), shortTempDir(b), "bench")
|
||||||
|
require.NoError(b, err)
|
||||||
|
defer func() { _ = proxy.Close(ctx) }()
|
||||||
|
viaProxy, err := mobyclient.New(mobyclient.WithHost("unix://" + proxy.Socket))
|
||||||
|
require.NoError(b, err)
|
||||||
|
defer viaProxy.Close()
|
||||||
|
|
||||||
|
require.NoError(b, NewDockerPullExecutor(NewDockerPullExecutorInput{Image: "alpine"})(ctx))
|
||||||
|
created, err := direct.ContainerCreate(ctx, mobyclient.ContainerCreateOptions{Config: &container.Config{Image: "alpine", Cmd: []string{"sleep", "600"}}})
|
||||||
|
require.NoError(b, err)
|
||||||
|
defer func() { _, _ = direct.ContainerRemove(ctx, created.ID, mobyclient.ContainerRemoveOptions{Force: true}) }()
|
||||||
|
_, err = direct.ContainerStart(ctx, created.ID, mobyclient.ContainerStartOptions{})
|
||||||
|
require.NoError(b, err)
|
||||||
|
|
||||||
|
var archive bytes.Buffer
|
||||||
|
writer := tar.NewWriter(&archive)
|
||||||
|
payload := make([]byte, 64<<20)
|
||||||
|
require.NoError(b, writer.WriteHeader(&tar.Header{Name: "blob", Mode: 0o600, Size: int64(len(payload))}))
|
||||||
|
_, _ = writer.Write(payload)
|
||||||
|
require.NoError(b, writer.Close())
|
||||||
|
|
||||||
|
for name, cli := range map[string]mobyclient.APIClient{"direct": direct, "proxy": viaProxy} {
|
||||||
|
b.Run("ping/"+name, func(b *testing.B) {
|
||||||
|
for b.Loop() {
|
||||||
|
if _, err := cli.Ping(ctx, mobyclient.PingOptions{}); err != nil {
|
||||||
|
b.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
b.Run("copy64MiB/"+name, func(b *testing.B) {
|
||||||
|
b.SetBytes(int64(archive.Len()))
|
||||||
|
for b.Loop() {
|
||||||
|
_, err := cli.CopyToContainer(ctx, created.ID, mobyclient.CopyToContainerOptions{DestinationPath: "/tmp", Content: bytes.NewReader(archive.Bytes())})
|
||||||
|
if err != nil {
|
||||||
|
b.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type probeClient struct {
|
||||||
|
mobyclient.APIClient
|
||||||
|
create func(mobyclient.ContainerCreateOptions) (mobyclient.ContainerCreateResult, error)
|
||||||
|
remove func(context.Context, string, mobyclient.ContainerRemoveOptions) (mobyclient.ContainerRemoveResult, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *probeClient) ImageList(context.Context, mobyclient.ImageListOptions) (mobyclient.ImageListResult, error) {
|
||||||
|
return mobyclient.ImageListResult{Items: []image.Summary{{ID: "probe-image"}}}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *probeClient) ContainerCreate(_ context.Context, opts mobyclient.ContainerCreateOptions) (mobyclient.ContainerCreateResult, error) {
|
||||||
|
return c.create(opts)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *probeClient) ContainerRemove(ctx context.Context, id string, opts mobyclient.ContainerRemoveOptions) (mobyclient.ContainerRemoveResult, error) {
|
||||||
|
return c.remove(ctx, id, opts)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDaemonSeesDir(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
markers := make(map[string]bool)
|
||||||
|
for _, testCase := range []struct {
|
||||||
|
name string
|
||||||
|
private bool
|
||||||
|
removeErr error
|
||||||
|
}{
|
||||||
|
{name: "cleanup after cancellation"},
|
||||||
|
{name: "private filesystem with stale marker", private: true},
|
||||||
|
{name: "cleanup error after cancellation", removeErr: errors.New("cleanup failed")},
|
||||||
|
} {
|
||||||
|
t.Run(testCase.name, func(t *testing.T) {
|
||||||
|
ctx, cancel := context.WithCancel(t.Context())
|
||||||
|
defer cancel()
|
||||||
|
daemonDir := dir
|
||||||
|
if testCase.private {
|
||||||
|
daemonDir = t.TempDir()
|
||||||
|
require.NoError(t, os.WriteFile(filepath.Join(daemonDir, "probe"), []byte("stale"), 0o600))
|
||||||
|
}
|
||||||
|
removed := false
|
||||||
|
cli := &probeClient{
|
||||||
|
create: func(opts mobyclient.ContainerCreateOptions) (mobyclient.ContainerCreateResult, error) {
|
||||||
|
require.Len(t, opts.HostConfig.Mounts, 1)
|
||||||
|
marker := opts.HostConfig.Mounts[0].Source
|
||||||
|
assert.Equal(t, mount.Mount{Type: mount.TypeBind, Source: marker, Target: "/gitea-runner-probe", ReadOnly: true}, opts.HostConfig.Mounts[0])
|
||||||
|
assert.False(t, markers[marker])
|
||||||
|
markers[marker] = true
|
||||||
|
info, err := os.Stat(marker)
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.True(t, info.Mode().IsRegular())
|
||||||
|
cancel()
|
||||||
|
if _, err := os.Stat(filepath.Join(daemonDir, filepath.Base(marker))); errors.Is(err, os.ErrNotExist) {
|
||||||
|
return mobyclient.ContainerCreateResult{}, cerrdefs.ErrInvalidArgument
|
||||||
|
}
|
||||||
|
return mobyclient.ContainerCreateResult{ID: "probe"}, nil
|
||||||
|
},
|
||||||
|
remove: func(ctx context.Context, id string, opts mobyclient.ContainerRemoveOptions) (mobyclient.ContainerRemoveResult, error) {
|
||||||
|
removed = true
|
||||||
|
assert.Equal(t, "probe", id)
|
||||||
|
assert.Equal(t, mobyclient.ContainerRemoveOptions{Force: true, RemoveVolumes: true}, opts)
|
||||||
|
require.NoError(t, ctx.Err())
|
||||||
|
_, bounded := ctx.Deadline()
|
||||||
|
assert.True(t, bounded)
|
||||||
|
return mobyclient.ContainerRemoveResult{}, testCase.removeErr
|
||||||
|
},
|
||||||
|
}
|
||||||
|
seen, err := daemonSeesDir(ctx, cli, dir)
|
||||||
|
require.ErrorIs(t, err, testCase.removeErr)
|
||||||
|
assert.Equal(t, !testCase.private && testCase.removeErr == nil, seen)
|
||||||
|
assert.Equal(t, !testCase.private, removed)
|
||||||
|
entries, err := os.ReadDir(dir)
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.Empty(t, entries)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
//go:build !WITHOUT_DOCKER && (linux || darwin || netbsd)
|
||||||
|
|
||||||
|
package container
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"syscall"
|
||||||
|
)
|
||||||
|
|
||||||
|
func copyDockerSocketPermissions(socket string, info os.FileInfo) error {
|
||||||
|
stat, ok := info.Sys().(*syscall.Stat_t)
|
||||||
|
if !ok {
|
||||||
|
return errors.New("docker socket ownership is unavailable")
|
||||||
|
}
|
||||||
|
if err := os.Chown(socket, int(stat.Uid), int(stat.Gid)); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := os.Chown(filepath.Dir(socket), int(stat.Uid), -1); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return os.Chmod(socket, info.Mode().Perm())
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
//go:build !WITHOUT_DOCKER
|
||||||
|
|
||||||
|
package container
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"os"
|
||||||
|
)
|
||||||
|
|
||||||
|
func copyDockerSocketPermissions(_ string, _ os.FileInfo) error {
|
||||||
|
return errors.New("docker socket ownership cannot be preserved on Windows")
|
||||||
|
}
|
||||||
+28
-31
@@ -138,12 +138,12 @@ func (cr *containerReference) Copy(destPath string, files ...*FileEntry) common.
|
|||||||
).IfNot(common.Dryrun)
|
).IfNot(common.Dryrun)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (cr *containerReference) CopyDir(destPath, srcPath string, useGitIgnore bool) common.Executor {
|
func (cr *containerReference) CopyDir(destPath, srcPath string, useGitIgnore, skipGitDir bool) common.Executor {
|
||||||
return common.NewPipelineExecutor(
|
return common.NewPipelineExecutor(
|
||||||
common.NewInfoExecutor("docker cp src=%s dst=%s", srcPath, destPath),
|
common.NewInfoExecutor("docker cp src=%s dst=%s", srcPath, destPath),
|
||||||
cr.connect(),
|
cr.connect(),
|
||||||
cr.find(),
|
cr.find(),
|
||||||
cr.copyDir(destPath, srcPath, useGitIgnore),
|
cr.copyDir(destPath, srcPath, useGitIgnore, skipGitDir),
|
||||||
func(ctx context.Context) error {
|
func(ctx context.Context) error {
|
||||||
// If this fails, then folders have wrong permissions on non root container
|
// If this fails, then folders have wrong permissions on non root container
|
||||||
if cr.UID != 0 || cr.GID != 0 {
|
if cr.UID != 0 || cr.GID != 0 {
|
||||||
@@ -252,6 +252,10 @@ func containerInfoFromInspect(inspect container.InspectResponse) *Info {
|
|||||||
ID: inspect.ID,
|
ID: inspect.ID,
|
||||||
Health: HealthNone,
|
Health: HealthNone,
|
||||||
Ports: map[string]string{}, // an empty map, never null, in the expression context
|
Ports: map[string]string{}, // an empty map, never null, in the expression context
|
||||||
|
Mounts: make(map[string]string, len(inspect.Mounts)),
|
||||||
|
}
|
||||||
|
for _, mountPoint := range inspect.Mounts {
|
||||||
|
info.Mounts[mountPoint.Destination] = mountPoint.Source
|
||||||
}
|
}
|
||||||
|
|
||||||
if state := inspect.State; state != nil {
|
if state := inspect.State; state != nil {
|
||||||
@@ -484,14 +488,11 @@ func (cr *containerReference) remove() common.Executor {
|
|||||||
RemoveVolumes: true,
|
RemoveVolumes: true,
|
||||||
Force: true,
|
Force: true,
|
||||||
})
|
})
|
||||||
switch {
|
if cerrdefs.IsConflict(err) {
|
||||||
case cerrdefs.IsConflict(err):
|
err = cr.waitForRemoval(ctx, idOrName)
|
||||||
// the daemon's own AutoRemove teardown is running, and it releases the volume
|
}
|
||||||
// references and the network endpoint only once it finishes
|
if err != nil && !cerrdefs.IsNotFound(err) {
|
||||||
cr.waitForRemoval(ctx, idOrName)
|
return fmt.Errorf("failed to remove container %s: %w", idOrName, err)
|
||||||
case err != nil && !cerrdefs.IsNotFound(err):
|
|
||||||
logger.Error(fmt.Errorf("failed to remove container %s: %w", idOrName, err))
|
|
||||||
return nil // keep the id, the container is still there for a later Remove()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.Debugf("Removed container: %v", idOrName)
|
logger.Debugf("Removed container: %v", idOrName)
|
||||||
@@ -500,7 +501,7 @@ func (cr *containerReference) remove() common.Executor {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (cr *containerReference) waitForRemoval(ctx context.Context, idOrName string) {
|
func (cr *containerReference) waitForRemoval(ctx context.Context, idOrName string) error {
|
||||||
// per container, against the one minute the post-job executor allows for the whole
|
// per container, against the one minute the post-job executor allows for the whole
|
||||||
// cleanup, so a job with several services can spend most of that budget here
|
// cleanup, so a job with several services can spend most of that budget here
|
||||||
ctx, cancel := context.WithTimeout(ctx, 15*time.Second)
|
ctx, cancel := context.WithTimeout(ctx, 15*time.Second)
|
||||||
@@ -510,18 +511,13 @@ func (cr *containerReference) waitForRemoval(ctx context.Context, idOrName strin
|
|||||||
Condition: container.WaitConditionRemoved,
|
Condition: container.WaitConditionRemoved,
|
||||||
})
|
})
|
||||||
select {
|
select {
|
||||||
case <-waitResult.Result:
|
case result := <-waitResult.Result:
|
||||||
case <-waitResult.Error:
|
if result.Error != nil {
|
||||||
case <-ctx.Done():
|
return errors.New(result.Error.Message)
|
||||||
// the client delivers the result over an unbuffered channel, so leave a receiver
|
}
|
||||||
// behind or its goroutine parks on the send for the lifetime of the process
|
return nil
|
||||||
go func() {
|
case err := <-waitResult.Error:
|
||||||
select {
|
return err
|
||||||
case <-waitResult.Result:
|
|
||||||
case <-waitResult.Error:
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
common.Logger(ctx).Warnf("Timed out waiting for the daemon to remove container %s, its volumes and network may be left behind", idOrName)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -940,7 +936,7 @@ func (cr *containerReference) waitForCommand(ctx context.Context, resp client.Hi
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (cr *containerReference) copyDir(dstPath, srcPath string, useGitIgnore bool) common.Executor {
|
func (cr *containerReference) copyDir(dstPath, srcPath string, useGitIgnore, skipGitDir bool) common.Executor {
|
||||||
return func(ctx context.Context) error {
|
return func(ctx context.Context) error {
|
||||||
if cr.id == "" {
|
if cr.id == "" {
|
||||||
return cr.missingContainerError("copy directory to %s", dstPath)
|
return cr.missingContainerError("copy directory to %s", dstPath)
|
||||||
@@ -981,9 +977,10 @@ func (cr *containerReference) copyDir(dstPath, srcPath string, useGitIgnore bool
|
|||||||
}
|
}
|
||||||
|
|
||||||
fc := &filecollector.FileCollector{
|
fc := &filecollector.FileCollector{
|
||||||
Ignorer: ignorer,
|
Ignorer: ignorer,
|
||||||
SrcPath: srcPath,
|
SrcPath: srcPath,
|
||||||
SrcPrefix: srcPrefix,
|
SrcPrefix: srcPrefix,
|
||||||
|
SkipGitDir: skipGitDir,
|
||||||
Handler: &filecollector.TarCollector{
|
Handler: &filecollector.TarCollector{
|
||||||
TarWriter: tw,
|
TarWriter: tw,
|
||||||
UID: cr.UID,
|
UID: cr.UID,
|
||||||
@@ -1272,15 +1269,15 @@ func overlayVolumes(dst, src *container.HostConfig) {
|
|||||||
|
|
||||||
type validVolumeMatcher struct {
|
type validVolumeMatcher struct {
|
||||||
allowAll bool
|
allowAll bool
|
||||||
named []glob.Glob
|
named []*glob.Pattern
|
||||||
host []glob.Glob
|
host []*glob.Pattern
|
||||||
}
|
}
|
||||||
|
|
||||||
func newValidVolumeMatcher(ctx context.Context, validVolumes []string) validVolumeMatcher {
|
func newValidVolumeMatcher(ctx context.Context, validVolumes []string) validVolumeMatcher {
|
||||||
logger := common.Logger(ctx)
|
logger := common.Logger(ctx)
|
||||||
ret := validVolumeMatcher{
|
ret := validVolumeMatcher{
|
||||||
named: make([]glob.Glob, 0, len(validVolumes)),
|
named: make([]*glob.Pattern, 0, len(validVolumes)),
|
||||||
host: make([]glob.Glob, 0, len(validVolumes)),
|
host: make([]*glob.Pattern, 0, len(validVolumes)),
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, v := range validVolumes {
|
for _, v := range validVolumes {
|
||||||
|
|||||||
@@ -345,18 +345,22 @@ func TestDockerWaitFailure(t *testing.T) {
|
|||||||
// A remove that raced the daemon's AutoRemove teardown is not a failure and must not
|
// A remove that raced the daemon's AutoRemove teardown is not a failure and must not
|
||||||
// be logged as one.
|
// be logged as one.
|
||||||
func TestRemoveIgnoresAutoRemoveRace(t *testing.T) {
|
func TestRemoveIgnoresAutoRemoveRace(t *testing.T) {
|
||||||
|
removeFailure := errors.New("driver failed to remove root filesystem")
|
||||||
removeOpts := mobyclient.ContainerRemoveOptions{RemoveVolumes: true, Force: true}
|
removeOpts := mobyclient.ContainerRemoveOptions{RemoveVolumes: true, Force: true}
|
||||||
killOpts := mobyclient.ContainerKillOptions{Signal: "SIGKILL"}
|
killOpts := mobyclient.ContainerKillOptions{Signal: "SIGKILL"}
|
||||||
for _, tc := range []struct {
|
for _, tc := range []struct {
|
||||||
name string
|
name string
|
||||||
err error
|
err error
|
||||||
wantWait bool
|
wantWait bool
|
||||||
wantFailure bool
|
waitErr error
|
||||||
|
wantErr error
|
||||||
}{
|
}{
|
||||||
{name: "removal in progress", err: cerrdefs.ErrConflict.WithMessage("removal of container abc is already in progress"), wantWait: true},
|
{name: "removal in progress", err: cerrdefs.ErrConflict.WithMessage("removal of container abc is already in progress"), wantWait: true},
|
||||||
|
{name: "wait canceled", err: cerrdefs.ErrConflict, wantWait: true, waitErr: context.Canceled, wantErr: context.Canceled},
|
||||||
|
{name: "removed during wait", err: cerrdefs.ErrConflict, wantWait: true, waitErr: cerrdefs.ErrNotFound},
|
||||||
{name: "already removed", err: cerrdefs.ErrNotFound.WithMessage("No such container: abc")},
|
{name: "already removed", err: cerrdefs.ErrNotFound.WithMessage("No such container: abc")},
|
||||||
{name: "removed cleanly", err: nil},
|
{name: "removed cleanly", err: nil},
|
||||||
{name: "real failure", err: errors.New("driver failed to remove root filesystem"), wantFailure: true},
|
{name: "real failure", err: removeFailure, wantErr: removeFailure},
|
||||||
} {
|
} {
|
||||||
t.Run(tc.name, func(t *testing.T) {
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
logger, hook := test.NewNullLogger()
|
logger, hook := test.NewNullLogger()
|
||||||
@@ -366,21 +370,24 @@ func TestRemoveIgnoresAutoRemoveRace(t *testing.T) {
|
|||||||
client.On("ContainerRemove", ctx, "abc", removeOpts).Return(mobyclient.ContainerRemoveResult{}, tc.err)
|
client.On("ContainerRemove", ctx, "abc", removeOpts).Return(mobyclient.ContainerRemoveResult{}, tc.err)
|
||||||
if tc.wantWait {
|
if tc.wantWait {
|
||||||
removed := make(chan container.WaitResponse, 1)
|
removed := make(chan container.WaitResponse, 1)
|
||||||
removed <- container.WaitResponse{}
|
waitErrors := make(chan error, 1)
|
||||||
|
if tc.waitErr == nil {
|
||||||
|
removed <- container.WaitResponse{}
|
||||||
|
} else {
|
||||||
|
waitErrors <- tc.waitErr
|
||||||
|
}
|
||||||
client.On("ContainerWait", mock.Anything, "abc", mobyclient.ContainerWaitOptions{Condition: container.WaitConditionRemoved}).
|
client.On("ContainerWait", mock.Anything, "abc", mobyclient.ContainerWaitOptions{Condition: container.WaitConditionRemoved}).
|
||||||
Return(mobyclient.ContainerWaitResult{Result: removed})
|
Return(mobyclient.ContainerWaitResult{Result: removed, Error: waitErrors})
|
||||||
}
|
}
|
||||||
cr := &containerReference{id: "abc", cli: client}
|
cr := &containerReference{id: "abc", cli: client}
|
||||||
|
|
||||||
require.NoError(t, cr.remove()(ctx))
|
require.ErrorIs(t, cr.remove()(ctx), tc.wantErr)
|
||||||
// a failure keeps the id, so a later Remove() can retry it
|
if tc.wantErr != nil {
|
||||||
if tc.wantFailure {
|
|
||||||
assert.Equal(t, "abc", cr.id)
|
assert.Equal(t, "abc", cr.id)
|
||||||
assert.Len(t, hook.AllEntries(), 1)
|
|
||||||
} else {
|
} else {
|
||||||
assert.Empty(t, cr.id)
|
assert.Empty(t, cr.id)
|
||||||
assert.Empty(t, hook.AllEntries())
|
|
||||||
}
|
}
|
||||||
|
assert.Empty(t, hook.AllEntries())
|
||||||
client.AssertExpectations(t)
|
client.AssertExpectations(t)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -471,7 +478,7 @@ func TestRejectsMissingContainer(t *testing.T) {
|
|||||||
assert.Contains(t, err.Error(), `container "job-1" does not exist`, op)
|
assert.Contains(t, err.Error(), `container "job-1" does not exist`, op)
|
||||||
}
|
}
|
||||||
check("copyContent", cr.copyContent("/var/run/act", &FileEntry{Name: "x", Mode: 0o644})(ctx))
|
check("copyContent", cr.copyContent("/var/run/act", &FileEntry{Name: "x", Mode: 0o644})(ctx))
|
||||||
check("copyDir", cr.copyDir("/var/run/act", "/src", false)(ctx))
|
check("copyDir", cr.copyDir("/var/run/act", "/src", false, false)(ctx))
|
||||||
check("exec", cr.exec([]string{"echo"}, nil, "", "")(ctx))
|
check("exec", cr.exec([]string{"echo"}, nil, "", "")(ctx))
|
||||||
_, err := cr.GetContainerArchive(ctx, "/var/run/act/x")
|
_, err := cr.GetContainerArchive(ctx, "/var/run/act/x")
|
||||||
check("GetContainerArchive", err)
|
check("GetContainerArchive", err)
|
||||||
@@ -801,6 +808,20 @@ func TestContainerInfoFromInspect(t *testing.T) {
|
|||||||
assert.Equal(t, "abc123", info.ID)
|
assert.Equal(t, "abc123", info.ID)
|
||||||
assert.Equal(t, HealthNone, info.Health)
|
assert.Equal(t, HealthNone, info.Health)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
t.Run("reports the mount sources by container path", func(t *testing.T) {
|
||||||
|
info := containerInfoFromInspect(container.InspectResponse{
|
||||||
|
Mounts: []container.MountPoint{
|
||||||
|
{Type: mount.TypeVolume, Name: "job", Source: "/var/lib/docker/volumes/job/_data", Destination: "/workspace/owner/repo"},
|
||||||
|
{Type: mount.TypeBind, Source: "/var/run/docker.sock", Destination: "/var/run/docker.sock"},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
assert.Equal(t, map[string]string{
|
||||||
|
"/workspace/owner/repo": "/var/lib/docker/volumes/job/_data",
|
||||||
|
"/var/run/docker.sock": "/var/run/docker.sock",
|
||||||
|
}, info.Mounts)
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestMergeContainerConfigsVolumesReplaceRunnerMounts(t *testing.T) {
|
func TestMergeContainerConfigsVolumesReplaceRunnerMounts(t *testing.T) {
|
||||||
|
|||||||
@@ -29,6 +29,18 @@ func RemoveImage(ctx context.Context, imageName string, force, pruneChildren boo
|
|||||||
return false, errors.New("Unsupported Operation")
|
return false, errors.New("Unsupported Operation")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func RemoveDockerJobResources(_ context.Context, _ string) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewDockerProxy(_ context.Context, _ string) *DockerProxy {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func StartDockerProxy(daemonSocket, dir, job string) (*DockerProxy, error) {
|
||||||
|
return nil, errors.New("Unsupported Operation")
|
||||||
|
}
|
||||||
|
|
||||||
// NewDockerBuildExecutor function to create a run executor for the container
|
// NewDockerBuildExecutor function to create a run executor for the container
|
||||||
func NewDockerBuildExecutor(input NewDockerBuildExecutorInput) common.Executor {
|
func NewDockerBuildExecutor(input NewDockerBuildExecutorInput) common.Executor {
|
||||||
return func(ctx context.Context) error {
|
return func(ctx context.Context) error {
|
||||||
|
|||||||
@@ -92,7 +92,7 @@ func (e *HostEnvironment) Copy(destPath string, files ...*FileEntry) common.Exec
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (e *HostEnvironment) CopyDir(destPath, srcPath string, useGitIgnore bool) common.Executor {
|
func (e *HostEnvironment) CopyDir(destPath, srcPath string, useGitIgnore, skipGitDir bool) common.Executor {
|
||||||
return func(ctx context.Context) error {
|
return func(ctx context.Context) error {
|
||||||
logger := common.Logger(ctx)
|
logger := common.Logger(ctx)
|
||||||
srcPrefix := filepath.Dir(srcPath)
|
srcPrefix := filepath.Dir(srcPath)
|
||||||
@@ -110,9 +110,10 @@ func (e *HostEnvironment) CopyDir(destPath, srcPath string, useGitIgnore bool) c
|
|||||||
ignorer = gitignore.NewMatcher(ps)
|
ignorer = gitignore.NewMatcher(ps)
|
||||||
}
|
}
|
||||||
fc := &filecollector.FileCollector{
|
fc := &filecollector.FileCollector{
|
||||||
Ignorer: ignorer,
|
Ignorer: ignorer,
|
||||||
SrcPath: srcPath,
|
SrcPath: srcPath,
|
||||||
SrcPrefix: srcPrefix,
|
SrcPrefix: srcPrefix,
|
||||||
|
SkipGitDir: skipGitDir,
|
||||||
Handler: &filecollector.CopyCollector{
|
Handler: &filecollector.CopyCollector{
|
||||||
DstDir: destPath,
|
DstDir: destPath,
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -47,10 +47,32 @@ func TestCopyDir(t *testing.T) {
|
|||||||
_ = os.MkdirAll(e.TmpDir, 0o700)
|
_ = os.MkdirAll(e.TmpDir, 0o700)
|
||||||
_ = os.MkdirAll(e.ToolCache, 0o700)
|
_ = os.MkdirAll(e.ToolCache, 0o700)
|
||||||
_ = os.MkdirAll(e.ActPath, 0o700)
|
_ = os.MkdirAll(e.ActPath, 0o700)
|
||||||
err := e.CopyDir(e.Workdir, e.Path, true)(ctx)
|
err := e.CopyDir(e.Workdir, e.Path, true, false)(ctx)
|
||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestCopyDirSkipGitDir(t *testing.T) {
|
||||||
|
for name, skipGitDir := range map[string]bool{"kept for a workspace copy": false, "skipped for an action copy": true} {
|
||||||
|
t.Run(name, func(t *testing.T) {
|
||||||
|
src := filepath.Join(t.TempDir(), "action")
|
||||||
|
require.NoError(t, os.MkdirAll(filepath.Join(src, ".git", "objects"), 0o700))
|
||||||
|
require.NoError(t, os.WriteFile(filepath.Join(src, ".git", "objects", "pack"), []byte("x"), 0o600))
|
||||||
|
require.NoError(t, os.WriteFile(filepath.Join(src, "action.yml"), []byte("name: x\n"), 0o600))
|
||||||
|
|
||||||
|
dest := filepath.Join(t.TempDir(), "dest")
|
||||||
|
e := &HostEnvironment{StdOut: os.Stdout}
|
||||||
|
require.NoError(t, e.CopyDir(dest, src+string(filepath.Separator), false, skipGitDir)(context.Background()))
|
||||||
|
|
||||||
|
assert.FileExists(t, filepath.Join(dest, "action.yml"))
|
||||||
|
if skipGitDir {
|
||||||
|
assert.NoDirExists(t, filepath.Join(dest, ".git"))
|
||||||
|
} else {
|
||||||
|
assert.FileExists(t, filepath.Join(dest, ".git", "objects", "pack"))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestGetContainerArchive(t *testing.T) {
|
func TestGetContainerArchive(t *testing.T) {
|
||||||
dir := t.TempDir()
|
dir := t.TempDir()
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
|
|||||||
@@ -94,10 +94,11 @@ func (cc *CopyCollector) WriteFile(fpath string, fi fs.FileInfo, linkName string
|
|||||||
}
|
}
|
||||||
|
|
||||||
type FileCollector struct {
|
type FileCollector struct {
|
||||||
Ignorer gitignore.Matcher
|
Ignorer gitignore.Matcher
|
||||||
SrcPath string
|
SrcPath string
|
||||||
SrcPrefix string
|
SrcPrefix string
|
||||||
Handler Handler
|
SkipGitDir bool
|
||||||
|
Handler Handler
|
||||||
}
|
}
|
||||||
|
|
||||||
func openGitIndex(path string) (*index.Index, error) {
|
func openGitIndex(path string) (*index.Index, error) {
|
||||||
@@ -124,6 +125,12 @@ func (fc *FileCollector) CollectFiles(ctx context.Context, submodulePath []strin
|
|||||||
if fi.IsDir() && len(split) > 0 && split[len(split)-1] == "." {
|
if fi.IsDir() && len(split) > 0 && split[len(split)-1] == "." {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
if fc.SkipGitDir && split[len(split)-1] == ".git" {
|
||||||
|
if fi.IsDir() {
|
||||||
|
return filepath.SkipDir
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
var entry *index.Entry
|
var entry *index.Entry
|
||||||
if i != nil {
|
if i != nil {
|
||||||
entry, err = i.Entry(strings.Join(split[len(submodulePath):], "/"))
|
entry, err = i.Entry(strings.Join(split[len(submodulePath):], "/"))
|
||||||
|
|||||||
+60
-31
@@ -32,7 +32,7 @@ type actionStep interface {
|
|||||||
step
|
step
|
||||||
|
|
||||||
getActionModel() *model.Action
|
getActionModel() *model.Action
|
||||||
getCompositeRunContext(context.Context) *RunContext
|
getCompositeRunContext(context.Context) (*RunContext, error)
|
||||||
getCompositeSteps() *compositeSteps
|
getCompositeSteps() *compositeSteps
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -154,7 +154,7 @@ func maybeCopyToActionDir(ctx context.Context, step actionStep, actionDir, actio
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
return rc.JobContainer.CopyDir(containerActionDirCopy, actionDir+"/", rc.Config.UseGitIgnore)(ctx)
|
return rc.JobContainer.CopyDir(containerActionDirCopy, actionDir+"/", rc.Config.UseGitIgnore, true)(ctx)
|
||||||
}
|
}
|
||||||
|
|
||||||
func runActionImpl(step actionStep, actionDir string, remoteAction *remoteAction) common.Executor {
|
func runActionImpl(step actionStep, actionDir string, remoteAction *remoteAction) common.Executor {
|
||||||
@@ -172,7 +172,9 @@ func runActionImpl(step actionStep, actionDir string, remoteAction *remoteAction
|
|||||||
|
|
||||||
rc.withGithubEnv(ctx, step.getGithubContext(ctx), *step.getEnv())
|
rc.withGithubEnv(ctx, step.getGithubContext(ctx), *step.getEnv())
|
||||||
populateEnvsFromSavedState(step.getEnv(), step, rc)
|
populateEnvsFromSavedState(step.getEnv(), step, rc)
|
||||||
populateEnvsFromInput(ctx, step.getEnv(), action, rc)
|
if err := populateEnvsFromInput(ctx, step.getEnv(), action, rc); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
actionLocation := path.Join(actionDir, actionPath)
|
actionLocation := path.Join(actionDir, actionPath)
|
||||||
actionName, containerActionDir := getContainerActionPaths(stepModel, actionLocation, rc)
|
actionName, containerActionDir := getContainerActionPaths(stepModel, actionLocation, rc)
|
||||||
@@ -352,23 +354,35 @@ func execAsDocker(ctx context.Context, step actionStep, actionName, actionDir, b
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
eval := rc.NewActionInputsExpressionEvaluator(ctx, step)
|
eval := rc.NewActionInputsExpressionEvaluator(ctx, step)
|
||||||
cmd, err := shellquote.Split(eval.Interpolate(ctx, step.getStepModel().With["args"]))
|
args, err := eval.Interpolate(ctx, step.getStepModel().With["args"])
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("unable to interpolate with.args: %w", err)
|
||||||
|
}
|
||||||
|
cmd, err := shellquote.Split(args)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
ee, err := evalDockerEnv(ctx, step, action)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
ee := evalDockerEnv(ctx, step, action)
|
|
||||||
if action.Runs.Args != nil {
|
if action.Runs.Args != nil {
|
||||||
// a fresh slice, the manifest is evaluated again for every stage
|
// a fresh slice, the manifest is evaluated again for every stage
|
||||||
cmd = make([]string, len(action.Runs.Args))
|
cmd = make([]string, len(action.Runs.Args))
|
||||||
for i, v := range action.Runs.Args {
|
for i, v := range action.Runs.Args {
|
||||||
cmd[i] = ee.Interpolate(ctx, v)
|
if cmd[i], err = ee.Interpolate(ctx, v); err != nil {
|
||||||
|
return fmt.Errorf("unable to interpolate runs.args: %w", err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
entrypoint, err := dockerEntrypoint(ctx, step, eval, stage)
|
entrypoint, err := dockerEntrypoint(ctx, step, eval, stage)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
stepContainer := newStepContainer(ctx, step, image, cmd, entrypoint, rc.Config.ContainerOptions)
|
stepContainer, err := newStepContainer(ctx, step, image, cmd, entrypoint, rc.Config.ContainerOptions)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
return common.NewPipelineExecutor(
|
return common.NewPipelineExecutor(
|
||||||
prepImage,
|
prepImage,
|
||||||
stepContainer.Pull(forcePull),
|
stepContainer.Pull(forcePull),
|
||||||
@@ -392,7 +406,11 @@ func dockerEntrypoint(ctx context.Context, step actionStep, eval *expressionEval
|
|||||||
default:
|
default:
|
||||||
entrypoint = runs.Entrypoint
|
entrypoint = runs.Entrypoint
|
||||||
if entrypoint == "" {
|
if entrypoint == "" {
|
||||||
if fields := strings.Fields(eval.Interpolate(ctx, step.getStepModel().With["entrypoint"])); len(fields) > 0 {
|
withEntrypoint, err := eval.Interpolate(ctx, step.getStepModel().With["entrypoint"])
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("unable to interpolate with.entrypoint: %w", err)
|
||||||
|
}
|
||||||
|
if fields := strings.Fields(withEntrypoint); len(fields) > 0 {
|
||||||
return fields, nil
|
return fields, nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -405,19 +423,22 @@ func dockerEntrypoint(ctx context.Context, step actionStep, eval *expressionEval
|
|||||||
}
|
}
|
||||||
|
|
||||||
// evalDockerEnv returns an evaluator bound to the environment it installed.
|
// evalDockerEnv returns an evaluator bound to the environment it installed.
|
||||||
func evalDockerEnv(ctx context.Context, step step, action *model.Action) *expressionEvaluator {
|
func evalDockerEnv(ctx context.Context, step step, action *model.Action) (*expressionEvaluator, error) {
|
||||||
rc := step.getRunContext()
|
rc := step.getRunContext()
|
||||||
stepModel := step.getStepModel()
|
stepModel := step.getStepModel()
|
||||||
|
|
||||||
|
var err error
|
||||||
inputs := make(map[string]string)
|
inputs := make(map[string]string)
|
||||||
eval := rc.NewExpressionEvaluator(ctx)
|
eval := rc.NewExpressionEvaluator(ctx)
|
||||||
// Set Defaults
|
// Set Defaults
|
||||||
for k, input := range action.Inputs {
|
for k, input := range action.Inputs {
|
||||||
inputs[k] = eval.Interpolate(ctx, input.Default)
|
if inputs[k], err = eval.Interpolate(ctx, input.Default); err != nil {
|
||||||
|
return nil, fmt.Errorf("unable to interpolate the default of input %s: %w", k, err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if stepModel.With != nil {
|
for k, v := range stepModel.With {
|
||||||
for k, v := range stepModel.With {
|
if inputs[k], err = eval.Interpolate(ctx, v); err != nil {
|
||||||
inputs[k] = eval.Interpolate(ctx, v)
|
return nil, fmt.Errorf("unable to interpolate with.%s: %w", k, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
mergeIntoMap(step, step.getEnv(), inputs)
|
mergeIntoMap(step, step.getEnv(), inputs)
|
||||||
@@ -428,12 +449,14 @@ func evalDockerEnv(ctx context.Context, step step, action *model.Action) *expres
|
|||||||
|
|
||||||
ee := rc.NewActionInputsExpressionEvaluator(ctx, step)
|
ee := rc.NewActionInputsExpressionEvaluator(ctx, step)
|
||||||
for k, v := range *step.getEnv() {
|
for k, v := range *step.getEnv() {
|
||||||
(*step.getEnv())[k] = ee.Interpolate(ctx, v)
|
if (*step.getEnv())[k], err = ee.Interpolate(ctx, v); err != nil {
|
||||||
|
return nil, fmt.Errorf("unable to interpolate env %s: %w", k, err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return ee
|
return ee, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func newStepContainer(ctx context.Context, step step, image string, cmd, entrypoint []string, runnerOptions string) container.Container {
|
func newStepContainer(ctx context.Context, step step, image string, cmd, entrypoint []string, runnerOptions string) (container.Container, error) {
|
||||||
rc := step.getRunContext()
|
rc := step.getRunContext()
|
||||||
logWriter := rc.commandLogWriter(ctx)
|
logWriter := rc.commandLogWriter(ctx)
|
||||||
envList := make([]string, 0)
|
envList := make([]string, 0)
|
||||||
@@ -443,9 +466,12 @@ func newStepContainer(ctx context.Context, step step, image string, cmd, entrypo
|
|||||||
|
|
||||||
envList = append(envList, rc.runnerEnv(ctx)...)
|
envList = append(envList, rc.runnerEnv(ctx)...)
|
||||||
|
|
||||||
binds, mounts := rc.GetBindsAndMounts()
|
binds, mounts, err := rc.GetBindsAndMounts()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
networkMode := "container:" + rc.jobContainerName()
|
networkMode := "container:" + rc.jobContainerName()
|
||||||
if rc.IsHostEnv(ctx) {
|
if rc.IsHostEnv() {
|
||||||
networkMode = "default"
|
networkMode = "default"
|
||||||
}
|
}
|
||||||
return ContainerNewContainer(&container.NewContainerInput{
|
return ContainerNewContainer(&container.NewContainerInput{
|
||||||
@@ -467,7 +493,7 @@ func newStepContainer(ctx context.Context, step step, image string, cmd, entrypo
|
|||||||
AutoRemove: true,
|
AutoRemove: true,
|
||||||
ValidVolumes: rc.validVolumes(),
|
ValidVolumes: rc.validVolumes(),
|
||||||
AllocatePTY: rc.Config.AllocatePTY,
|
AllocatePTY: rc.Config.AllocatePTY,
|
||||||
})
|
}), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func populateEnvsFromSavedState(env *map[string]string, step actionStep, rc *RunContext) {
|
func populateEnvsFromSavedState(env *map[string]string, step actionStep, rc *RunContext) {
|
||||||
@@ -480,15 +506,19 @@ func populateEnvsFromSavedState(env *map[string]string, step actionStep, rc *Run
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func populateEnvsFromInput(ctx context.Context, env *map[string]string, action *model.Action, rc *RunContext) {
|
func populateEnvsFromInput(ctx context.Context, env *map[string]string, action *model.Action, rc *RunContext) error {
|
||||||
eval := rc.NewExpressionEvaluator(ctx)
|
eval := rc.NewExpressionEvaluator(ctx)
|
||||||
for inputID, input := range action.Inputs {
|
for inputID, input := range action.Inputs {
|
||||||
envKey := regexp.MustCompile("[^A-Z0-9-]").ReplaceAllString(strings.ToUpper(inputID), "_")
|
envKey := regexp.MustCompile("[^A-Z0-9-]").ReplaceAllString(strings.ToUpper(inputID), "_")
|
||||||
envKey = "INPUT_" + envKey
|
envKey = "INPUT_" + envKey
|
||||||
if _, ok := (*env)[envKey]; !ok {
|
if _, ok := (*env)[envKey]; !ok {
|
||||||
(*env)[envKey] = eval.Interpolate(ctx, input.Default)
|
var err error
|
||||||
|
if (*env)[envKey], err = eval.Interpolate(ctx, input.Default); err != nil {
|
||||||
|
return fmt.Errorf("unable to interpolate the default of input %s: %w", inputID, err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func getContainerActionPaths(step *model.Step, actionDir string, rc *RunContext) (string, string) {
|
func getContainerActionPaths(step *model.Step, actionDir string, rc *RunContext) (string, string) {
|
||||||
@@ -588,11 +618,14 @@ func runPreStep(step actionStep) common.Executor {
|
|||||||
actionDir, actionPath, _, containerActionDir := actionStagePaths(step)
|
actionDir, actionPath, _, containerActionDir := actionStagePaths(step)
|
||||||
|
|
||||||
x := action.Runs.Using
|
x := action.Runs.Using
|
||||||
|
if !x.IsComposite() {
|
||||||
|
// defaults in pre steps were missing, however provided inputs are available
|
||||||
|
if err := populateEnvsFromInput(ctx, step.getEnv(), action, rc); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
switch {
|
switch {
|
||||||
case x.IsNode():
|
case x.IsNode():
|
||||||
// defaults in pre steps were missing, however provided inputs are available
|
|
||||||
populateEnvsFromInput(ctx, step.getEnv(), action, rc)
|
|
||||||
|
|
||||||
if err := maybeCopyToActionDir(ctx, step, actionDir, actionPath, containerActionDir); err != nil {
|
if err := maybeCopyToActionDir(ctx, step, actionDir, actionPath, containerActionDir); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -605,14 +638,13 @@ func runPreStep(step actionStep) common.Executor {
|
|||||||
return rc.JobContainer.Exec(containerArgs, *step.getEnv(), "", "")(ctx)
|
return rc.JobContainer.Exec(containerArgs, *step.getEnv(), "", "")(ctx)
|
||||||
|
|
||||||
case x.IsDocker():
|
case x.IsDocker():
|
||||||
// defaults in pre steps were missing, however provided inputs are available
|
|
||||||
populateEnvsFromInput(ctx, step.getEnv(), action, rc)
|
|
||||||
|
|
||||||
return execDockerActionStage(ctx, step, stepStagePre)
|
return execDockerActionStage(ctx, step, stepStagePre)
|
||||||
|
|
||||||
case x.IsComposite():
|
case x.IsComposite():
|
||||||
if step.getCompositeSteps() == nil {
|
if step.getCompositeSteps() == nil {
|
||||||
step.getCompositeRunContext(ctx)
|
if _, err := step.getCompositeRunContext(ctx); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if steps := step.getCompositeSteps(); steps != nil && steps.pre != nil {
|
if steps := step.getCompositeSteps(); steps != nil && steps.pre != nil {
|
||||||
@@ -621,9 +653,6 @@ func runPreStep(step actionStep) common.Executor {
|
|||||||
return errors.New("missing steps in composite action")
|
return errors.New("missing steps in composite action")
|
||||||
|
|
||||||
case x == model.ActionRunsUsingGo:
|
case x == model.ActionRunsUsingGo:
|
||||||
// defaults in pre steps were missing, however provided inputs are available
|
|
||||||
populateEnvsFromInput(ctx, step.getEnv(), action, rc)
|
|
||||||
|
|
||||||
if err := maybeCopyToActionDir(ctx, step, actionDir, actionPath, containerActionDir); err != nil {
|
if err := maybeCopyToActionDir(ctx, step, actionDir, actionPath, containerActionDir); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ package runner
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
|
"fmt"
|
||||||
"regexp"
|
"regexp"
|
||||||
"slices"
|
"slices"
|
||||||
"strconv"
|
"strconv"
|
||||||
@@ -17,7 +18,7 @@ import (
|
|||||||
"gitea.dev/actionslib/pkg/model"
|
"gitea.dev/actionslib/pkg/model"
|
||||||
)
|
)
|
||||||
|
|
||||||
func evaluateCompositeInputAndEnv(ctx context.Context, parent *RunContext, step actionStep) map[string]string {
|
func evaluateCompositeInputAndEnv(ctx context.Context, parent *RunContext, step actionStep) (map[string]string, error) {
|
||||||
env := make(map[string]string)
|
env := make(map[string]string)
|
||||||
stepEnv := *step.getEnv()
|
stepEnv := *step.getEnv()
|
||||||
for k, v := range stepEnv {
|
for k, v := range stepEnv {
|
||||||
@@ -47,14 +48,17 @@ func evaluateCompositeInputAndEnv(ctx context.Context, parent *RunContext, step
|
|||||||
env[envKey] = value
|
env[envKey] = value
|
||||||
} else {
|
} else {
|
||||||
// defaults could contain expressions
|
// defaults could contain expressions
|
||||||
env[envKey] = ee.Interpolate(ctx, input.Default)
|
var err error
|
||||||
|
if env[envKey], err = ee.Interpolate(ctx, input.Default); err != nil {
|
||||||
|
return nil, fmt.Errorf("unable to interpolate the default of input %s: %w", inputID, err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
gh := step.getGithubContext(ctx)
|
gh := step.getGithubContext(ctx)
|
||||||
env["GITHUB_ACTION_REPOSITORY"] = gh.ActionRepository
|
env["GITHUB_ACTION_REPOSITORY"] = gh.ActionRepository
|
||||||
env["GITHUB_ACTION_REF"] = gh.ActionRef
|
env["GITHUB_ACTION_REF"] = gh.ActionRef
|
||||||
|
|
||||||
return env
|
return env, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (rc *RunContext) setCompositeActionEnv(env map[string]string) {
|
func (rc *RunContext) setCompositeActionEnv(env map[string]string) {
|
||||||
@@ -66,8 +70,11 @@ func (rc *RunContext) setCompositeActionEnv(env map[string]string) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func newCompositeRunContext(ctx context.Context, parent *RunContext, step actionStep, actionPath string) *RunContext {
|
func newCompositeRunContext(ctx context.Context, parent *RunContext, step actionStep, actionPath string) (*RunContext, error) {
|
||||||
env := evaluateCompositeInputAndEnv(ctx, parent, step)
|
env, err := evaluateCompositeInputAndEnv(ctx, parent, step)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
// run with the global config but without secrets
|
// run with the global config but without secrets
|
||||||
configCopy := *parent.Config
|
configCopy := *parent.Config
|
||||||
@@ -87,20 +94,21 @@ func newCompositeRunContext(ctx context.Context, parent *RunContext, step action
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
Config: &configCopy,
|
Config: &configCopy,
|
||||||
StepResults: map[string]*model.StepResult{},
|
StepResults: map[string]*model.StepResult{},
|
||||||
JobContainer: parent.JobContainer,
|
JobContainer: parent.JobContainer,
|
||||||
ActionPath: actionPath,
|
ActionPath: actionPath,
|
||||||
GlobalEnv: parent.GlobalEnv,
|
GlobalEnv: parent.GlobalEnv,
|
||||||
Masks: parent.Masks,
|
Masks: parent.Masks,
|
||||||
ExtraPath: parent.ExtraPath,
|
ExtraPath: parent.ExtraPath,
|
||||||
Parent: parent,
|
Parent: parent,
|
||||||
EventJSON: parent.EventJSON,
|
EventJSON: parent.EventJSON,
|
||||||
|
platformImage: parent.platformImage,
|
||||||
}
|
}
|
||||||
compositerc.setCompositeActionEnv(env)
|
compositerc.setCompositeActionEnv(env)
|
||||||
compositerc.ExprEval = compositerc.NewExpressionEvaluator(ctx)
|
compositerc.ExprEval = compositerc.NewExpressionEvaluator(ctx)
|
||||||
|
|
||||||
return compositerc
|
return compositerc, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// appendUniqueMasks appends the masks from src to dst, skipping any mask that
|
// appendUniqueMasks appends the masks from src to dst, skipping any mask that
|
||||||
@@ -121,7 +129,10 @@ func execAsComposite(step actionStep) common.Executor {
|
|||||||
action := step.getActionModel()
|
action := step.getActionModel()
|
||||||
|
|
||||||
return func(ctx context.Context) error {
|
return func(ctx context.Context) error {
|
||||||
compositeRC := step.getCompositeRunContext(ctx)
|
compositeRC, err := step.getCompositeRunContext(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
steps := step.getCompositeSteps()
|
steps := step.getCompositeSteps()
|
||||||
|
|
||||||
@@ -131,14 +142,17 @@ func execAsComposite(step actionStep) common.Executor {
|
|||||||
|
|
||||||
ctx = WithCompositeLogger(ctx, &compositeRC.Masks)
|
ctx = WithCompositeLogger(ctx, &compositeRC.Masks)
|
||||||
|
|
||||||
err := steps.main(ctx)
|
err = steps.main(ctx)
|
||||||
|
|
||||||
// Map outputs from composite RunContext to job RunContext
|
// Map outputs from composite RunContext to job RunContext
|
||||||
eval := compositeRC.NewExpressionEvaluator(ctx)
|
eval := compositeRC.NewExpressionEvaluator(ctx)
|
||||||
for outputName, output := range action.Outputs {
|
for outputName, output := range action.Outputs {
|
||||||
rc.setOutput(ctx, map[string]string{
|
value, outputErr := eval.Interpolate(ctx, output.Value)
|
||||||
"name": outputName,
|
if outputErr != nil {
|
||||||
}, eval.Interpolate(ctx, output.Value))
|
err = errors.Join(err, fmt.Errorf("unable to interpolate output %s: %w", outputName, outputErr))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
rc.setOutput(ctx, map[string]string{"name": outputName}, value)
|
||||||
}
|
}
|
||||||
|
|
||||||
// compositeRC.Masks is seeded with rc.Masks (see newCompositeRunContext)
|
// compositeRC.Masks is seeded with rc.Masks (see newCompositeRunContext)
|
||||||
|
|||||||
@@ -19,25 +19,30 @@ func TestCompositeActionParity(t *testing.T) {
|
|||||||
ctx := t.Context()
|
ctx := t.Context()
|
||||||
strategy := &model.Strategy{MaxParallel: 3}
|
strategy := &model.Strategy{MaxParallel: 3}
|
||||||
parent := &RunContext{
|
parent := &RunContext{
|
||||||
Config: &Config{},
|
Config: &Config{},
|
||||||
Matrix: map[string]any{"os": "linux"},
|
Matrix: map[string]any{"os": "linux"},
|
||||||
Run: &model.Run{JobID: "job", Workflow: &model.Workflow{Name: "workflow", Jobs: map[string]*model.Job{"job": {Strategy: strategy}}}},
|
Run: &model.Run{JobID: "job", Workflow: &model.Workflow{Name: "workflow", Jobs: map[string]*model.Job{"job": {Strategy: strategy}}}},
|
||||||
JobContainer: &jobContainerMock{},
|
JobContainer: &jobContainerMock{},
|
||||||
|
platformImage: "-self-hosted",
|
||||||
}
|
}
|
||||||
composite := newCompositeRunContext(ctx, parent, &stepActionRemote{
|
composite, err := newCompositeRunContext(ctx, parent, &stepActionRemote{
|
||||||
Step: &model.Step{With: map[string]string{"SHARED": "outer"}},
|
Step: &model.Step{With: map[string]string{"SHARED": "outer"}},
|
||||||
RunContext: parent,
|
RunContext: parent,
|
||||||
action: &model.Action{Inputs: map[string]model.Input{"shared": {Default: "outer-default"}}},
|
action: &model.Action{Inputs: map[string]model.Input{"shared": {Default: "outer-default"}}},
|
||||||
env: map[string]string{"INPUT_SHARED": "outer"},
|
env: map[string]string{"INPUT_SHARED": "outer"},
|
||||||
}, "/action")
|
}, "/action")
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
assert.Same(t, strategy, composite.Run.Job().Strategy)
|
assert.Same(t, strategy, composite.Run.Job().Strategy)
|
||||||
assert.Equal(t, "linux|3|outer", composite.NewExpressionEvaluator(ctx).Interpolate(ctx,
|
assert.True(t, composite.IsHostEnv())
|
||||||
"${{ matrix.os }}|${{ strategy.max-parallel }}|${{ inputs.shared }}"))
|
interpolated, err := composite.NewExpressionEvaluator(ctx).Interpolate(ctx,
|
||||||
|
"${{ matrix.os }}|${{ strategy.max-parallel }}|${{ inputs.shared }}")
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.Equal(t, "linux|3|outer", interpolated)
|
||||||
assert.NotContains(t, composite.Env, "INPUT_SHARED")
|
assert.NotContains(t, composite.Env, "INPUT_SHARED")
|
||||||
|
|
||||||
nestedEnv := composite.GetEnv()
|
nestedEnv := composite.GetEnv()
|
||||||
populateEnvsFromInput(ctx, &nestedEnv, &model.Action{Inputs: map[string]model.Input{"shared": {Default: "inner-default"}}}, composite)
|
require.NoError(t, populateEnvsFromInput(ctx, &nestedEnv, &model.Action{Inputs: map[string]model.Input{"shared": {Default: "inner-default"}}}, composite))
|
||||||
assert.Equal(t, "inner-default", nestedEnv["INPUT_SHARED"])
|
assert.Equal(t, "inner-default", nestedEnv["INPUT_SHARED"])
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
@@ -227,7 +227,7 @@ func TestActionRunner(t *testing.T) {
|
|||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
|
|
||||||
cm := &containerMock{}
|
cm := &containerMock{}
|
||||||
cm.On("CopyDir", "/var/run/act/actions/dir/", "dir/", false).Return(func(ctx context.Context) error { return nil })
|
cm.On("CopyDir", "/var/run/act/actions/dir/", "dir/", false, true).Return(func(ctx context.Context) error { return nil })
|
||||||
|
|
||||||
envMatcher := mock.MatchedBy(func(env map[string]string) bool {
|
envMatcher := mock.MatchedBy(func(env map[string]string) bool {
|
||||||
for k, v := range tt.expectedEnv {
|
for k, v := range tt.expectedEnv {
|
||||||
@@ -316,7 +316,7 @@ func TestNewStepContainerDoesNotUseDockerSecrets(t *testing.T) {
|
|||||||
step.On("getStepModel").Return(&model.Step{ID: "action"})
|
step.On("getStepModel").Return(&model.Step{ID: "action"})
|
||||||
step.On("getEnv").Return(&env)
|
step.On("getEnv").Return(&env)
|
||||||
|
|
||||||
_ = newStepContainer(ctx, step, "registry.example.com/action:tag", nil, nil, "")
|
_, _ = newStepContainer(ctx, step, "registry.example.com/action:tag", nil, nil, "")
|
||||||
|
|
||||||
// DOCKER_USERNAME/DOCKER_PASSWORD should not be injected as pull credentials for docker action containers.
|
// DOCKER_USERNAME/DOCKER_PASSWORD should not be injected as pull credentials for docker action containers.
|
||||||
assert.Empty(t, captured.Username)
|
assert.Empty(t, captured.Username)
|
||||||
@@ -337,7 +337,7 @@ func TestMaybeCopyToActionDirHoldsCloneLock(t *testing.T) {
|
|||||||
copyEntered := make(chan struct{})
|
copyEntered := make(chan struct{})
|
||||||
|
|
||||||
cm := &containerMock{}
|
cm := &containerMock{}
|
||||||
cm.On("CopyDir", "/var/run/act/actions/", actionDir+"/", false).Return(func(ctx context.Context) error {
|
cm.On("CopyDir", "/var/run/act/actions/", actionDir+"/", false, true).Return(func(ctx context.Context) error {
|
||||||
close(copyEntered)
|
close(copyEntered)
|
||||||
<-releaseCopy
|
<-releaseCopy
|
||||||
return nil
|
return nil
|
||||||
|
|||||||
@@ -57,8 +57,8 @@ func (cm *containerMock) Copy(destPath string, files ...*container.FileEntry) co
|
|||||||
return args.Get(0).(func(context.Context) error)
|
return args.Get(0).(func(context.Context) error)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (cm *containerMock) CopyDir(destPath, srcPath string, useGitIgnore bool) common.Executor {
|
func (cm *containerMock) CopyDir(destPath, srcPath string, useGitIgnore, skipGitDir bool) common.Executor {
|
||||||
args := cm.Called(destPath, srcPath, useGitIgnore)
|
args := cm.Called(destPath, srcPath, useGitIgnore, skipGitDir)
|
||||||
return args.Get(0).(func(context.Context) error)
|
return args.Get(0).(func(context.Context) error)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,102 @@
|
|||||||
|
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
//go:build !(WITHOUT_DOCKER || !(linux || darwin || windows || netbsd))
|
||||||
|
|
||||||
|
package runner
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/rand"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"gitea.com/gitea/runner/act/common"
|
||||||
|
"gitea.com/gitea/runner/act/container"
|
||||||
|
|
||||||
|
"gitea.dev/actionslib/pkg/model"
|
||||||
|
cerrdefs "github.com/containerd/errdefs"
|
||||||
|
"github.com/moby/moby/client"
|
||||||
|
"github.com/sirupsen/logrus/hooks/test"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestDockerProxyMountedJob(t *testing.T) {
|
||||||
|
mode := os.Getenv("ACT_TEST_DOCKER_PROXY")
|
||||||
|
if mode == "" {
|
||||||
|
t.Skip("set ACT_TEST_DOCKER_PROXY=proxy or direct to verify mounted Docker access")
|
||||||
|
}
|
||||||
|
require.Contains(t, []string{"proxy", "direct"}, mode)
|
||||||
|
ctx, cancel := context.WithTimeout(t.Context(), 2*time.Minute)
|
||||||
|
defer cancel()
|
||||||
|
dockerClient, err := container.GetDockerClient(ctx)
|
||||||
|
require.NoError(t, err)
|
||||||
|
t.Cleanup(func() { assert.NoError(t, dockerClient.Close()) })
|
||||||
|
require.True(t, strings.HasPrefix(dockerClient.DaemonHost(), "unix://"), "mounted Docker coverage requires a Unix daemon socket")
|
||||||
|
|
||||||
|
fixtureDir, err := filepath.Abs("testdata/docker-proxy")
|
||||||
|
require.NoError(t, err)
|
||||||
|
resourceName := "gitea-proxy-test-" + strings.ToLower(rand.Text())
|
||||||
|
runner, err := New(&Config{
|
||||||
|
Workdir: fixtureDir,
|
||||||
|
ActionCacheDir: t.TempDir(),
|
||||||
|
EventName: "push",
|
||||||
|
PlatformPicker: mapPlatformPicker(platforms),
|
||||||
|
ContainerNamePrefix: resourceName,
|
||||||
|
ContainerDaemonSocket: dockerClient.DaemonHost(),
|
||||||
|
ContainerMaxLifetime: 2 * time.Minute,
|
||||||
|
Env: map[string]string{"PROXY_TEST_RESOURCE": resourceName, "PROXY_TEST_MODE": mode},
|
||||||
|
})
|
||||||
|
require.NoError(t, err)
|
||||||
|
planner, err := model.NewWorkflowPlanner(filepath.Join(fixtureDir, "push.yml"), true)
|
||||||
|
require.NoError(t, err)
|
||||||
|
plan, err := planner.PlanEvent("push")
|
||||||
|
require.NoError(t, err)
|
||||||
|
runContext, err := runner.newRunContext(ctx, plan.Stages[0].Runs[0], nil)
|
||||||
|
require.NoError(t, err)
|
||||||
|
jobName := runContext.jobContainerName()
|
||||||
|
jobNetwork, _ := runContext.networkNameForGitea()
|
||||||
|
t.Cleanup(func() {
|
||||||
|
cleanCtx, cleanCancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
|
||||||
|
defer cleanCancel()
|
||||||
|
if _, err := dockerClient.ContainerRemove(cleanCtx, jobName, client.ContainerRemoveOptions{Force: true, RemoveVolumes: true}); !cerrdefs.IsNotFound(err) {
|
||||||
|
assert.NoError(t, err)
|
||||||
|
}
|
||||||
|
for _, name := range []string{resourceName, jobNetwork} {
|
||||||
|
if _, err := dockerClient.NetworkRemove(cleanCtx, name, client.NetworkRemoveOptions{}); !cerrdefs.IsNotFound(err) {
|
||||||
|
assert.NoError(t, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, name := range []string{resourceName, jobName, jobName + "-env"} {
|
||||||
|
if _, err := dockerClient.VolumeRemove(cleanCtx, name, client.VolumeRemoveOptions{}); !cerrdefs.IsNotFound(err) {
|
||||||
|
assert.NoError(t, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
hook := &test.Hook{}
|
||||||
|
require.NoError(t, runner.NewPlanExecutor(plan)(common.WithLoggerHook(ctx, hook)))
|
||||||
|
var messages []string
|
||||||
|
for _, entry := range hook.AllEntries() {
|
||||||
|
messages = append(messages, strings.TrimSpace(entry.Message))
|
||||||
|
}
|
||||||
|
require.Contains(t, messages, "docker proxy post verified")
|
||||||
|
_, err = dockerClient.ContainerInspect(ctx, jobName, client.ContainerInspectOptions{})
|
||||||
|
assert.True(t, cerrdefs.IsNotFound(err), "job container survived cleanup: %v", err)
|
||||||
|
_, err = dockerClient.NetworkInspect(ctx, resourceName, client.NetworkInspectOptions{})
|
||||||
|
if mode == "proxy" {
|
||||||
|
assert.True(t, cerrdefs.IsNotFound(err), "labelled network survived cleanup: %v", err)
|
||||||
|
} else {
|
||||||
|
require.NoError(t, err)
|
||||||
|
}
|
||||||
|
_, err = dockerClient.VolumeInspect(ctx, resourceName, client.VolumeInspectOptions{})
|
||||||
|
if mode == "proxy" {
|
||||||
|
assert.True(t, cerrdefs.IsNotFound(err), "labelled volume survived cleanup: %v", err)
|
||||||
|
} else {
|
||||||
|
require.NoError(t, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
+51
-54
@@ -13,6 +13,7 @@ import (
|
|||||||
"reflect"
|
"reflect"
|
||||||
"regexp"
|
"regexp"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"gitea.com/gitea/runner/act/common"
|
"gitea.com/gitea/runner/act/common"
|
||||||
@@ -71,7 +72,7 @@ func (rc *RunContext) NewExpressionEvaluatorWithEnv(ctx context.Context, env map
|
|||||||
}
|
}
|
||||||
|
|
||||||
ghc := rc.getGithubContext(ctx)
|
ghc := rc.getGithubContext(ctx)
|
||||||
inputs := getEvaluatorInputs(ctx, rc, rc.actionInputs, ghc)
|
inputs := getEvaluatorInputs(rc, rc.actionInputs, ghc)
|
||||||
|
|
||||||
ee := &exprparser.EvaluationEnvironment{
|
ee := &exprparser.EvaluationEnvironment{
|
||||||
Github: ghc,
|
Github: ghc,
|
||||||
@@ -81,7 +82,7 @@ func (rc *RunContext) NewExpressionEvaluatorWithEnv(ctx context.Context, env map
|
|||||||
// todo: should be unavailable
|
// todo: should be unavailable
|
||||||
// but required to interpolate/evaluate the step outputs on the job
|
// but required to interpolate/evaluate the step outputs on the job
|
||||||
Steps: rc.getStepsContext(),
|
Steps: rc.getStepsContext(),
|
||||||
Secrets: getWorkflowSecrets(ctx, rc),
|
Secrets: getWorkflowSecrets(rc),
|
||||||
Vars: getWorkflowVars(ctx, rc),
|
Vars: getWorkflowVars(ctx, rc),
|
||||||
Strategy: strategy,
|
Strategy: strategy,
|
||||||
Matrix: rc.Matrix,
|
Matrix: rc.Matrix,
|
||||||
@@ -137,14 +138,14 @@ func (rc *RunContext) newStepExpressionEvaluator(ctx context.Context, step step,
|
|||||||
Env: *step.getEnv(),
|
Env: *step.getEnv(),
|
||||||
Job: rc.getJobContext(),
|
Job: rc.getJobContext(),
|
||||||
Steps: rc.getStepsContext(),
|
Steps: rc.getStepsContext(),
|
||||||
Secrets: getWorkflowSecrets(ctx, rc),
|
Secrets: getWorkflowSecrets(rc),
|
||||||
Vars: getWorkflowVars(ctx, rc),
|
Vars: getWorkflowVars(ctx, rc),
|
||||||
Strategy: strategy,
|
Strategy: strategy,
|
||||||
Matrix: rc.Matrix,
|
Matrix: rc.Matrix,
|
||||||
Needs: using,
|
Needs: using,
|
||||||
// todo: should be unavailable
|
// todo: should be unavailable
|
||||||
// but required to interpolate/evaluate the inputs in actions/composite
|
// but required to interpolate/evaluate the inputs in actions/composite
|
||||||
Inputs: getEvaluatorInputs(ctx, rc, stepInputs, rc.getGithubContext(ctx)),
|
Inputs: getEvaluatorInputs(rc, stepInputs, rc.getGithubContext(ctx)),
|
||||||
HashFiles: getHashFilesFunction(ctx, rc),
|
HashFiles: getHashFilesFunction(ctx, rc),
|
||||||
}
|
}
|
||||||
ee.Runner = rc.getRunnerContext(ctx)
|
ee.Runner = rc.getRunnerContext(ctx)
|
||||||
@@ -246,17 +247,18 @@ func (ee expressionEvaluator) EvaluateYamlNode(ctx context.Context, node *yaml.N
|
|||||||
return ee.shared(ctx).EvaluateYamlNode(node)
|
return ee.shared(ctx).EvaluateYamlNode(node)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ee expressionEvaluator) Interpolate(ctx context.Context, in string) string {
|
func (ee expressionEvaluator) Interpolate(ctx context.Context, in string) (string, error) {
|
||||||
out, err := ee.interpolate(ctx, in)
|
return ee.shared(ctx).Interpolate(in)
|
||||||
if err != nil {
|
|
||||||
common.Logger(ctx).Errorf("Unable to interpolate expression '%s': %s", in, err)
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
return out
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ee expressionEvaluator) interpolate(ctx context.Context, in string) (string, error) {
|
// InterpolateName keeps the source text of a job or step name that cannot be evaluated, as GitHub does.
|
||||||
return ee.shared(ctx).Interpolate(in)
|
func (ee expressionEvaluator) InterpolateName(ctx context.Context, in string) string {
|
||||||
|
out, err := ee.Interpolate(ctx, in)
|
||||||
|
if err != nil {
|
||||||
|
common.Logger(ctx).Warnf("Unable to evaluate the display name '%s': %s", in, err)
|
||||||
|
return in
|
||||||
|
}
|
||||||
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
// EvalBool evaluates an expression against given evaluator. An `if:` is an expression even without
|
// EvalBool evaluates an expression against given evaluator. An `if:` is an expression even without
|
||||||
@@ -277,10 +279,10 @@ func inputsFromEnv(env map[string]string) map[string]any {
|
|||||||
return inputs
|
return inputs
|
||||||
}
|
}
|
||||||
|
|
||||||
func getEvaluatorInputs(ctx context.Context, rc *RunContext, stepInputs map[string]any, ghc *model.GithubContext) map[string]any {
|
func getEvaluatorInputs(rc *RunContext, stepInputs map[string]any, ghc *model.GithubContext) map[string]any {
|
||||||
inputs := map[string]any{}
|
inputs := map[string]any{}
|
||||||
|
|
||||||
setupWorkflowInputs(ctx, &inputs, rc)
|
maps.Copy(inputs, rc.workflowCallInputs)
|
||||||
maps.Copy(inputs, stepInputs)
|
maps.Copy(inputs, stepInputs)
|
||||||
|
|
||||||
if ghc.EventName == "workflow_dispatch" {
|
if ghc.EventName == "workflow_dispatch" {
|
||||||
@@ -324,54 +326,49 @@ func coerceInputValue(value any, inputType string) any {
|
|||||||
return value == "true"
|
return value == "true"
|
||||||
}
|
}
|
||||||
|
|
||||||
func setupWorkflowInputs(ctx context.Context, inputs *map[string]any, rc *RunContext) {
|
// resolveWorkflowCall evaluates the caller's with: and secrets: once, as the server does before dispatching a called workflow.
|
||||||
if rc.caller != nil {
|
func (rc *RunContext) resolveWorkflowCall(ctx context.Context) error {
|
||||||
config := rc.Run.Workflow.WorkflowCallConfig()
|
if rc.caller == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
callerJob := rc.caller.runContext.Run.Job()
|
||||||
|
callerEval := rc.caller.runContext.ExprEval
|
||||||
|
calleeEval := sync.OnceValue(func() *expressionEvaluator { return rc.NewExpressionEvaluator(ctx) })
|
||||||
|
config := rc.Run.Workflow.WorkflowCallConfig()
|
||||||
|
|
||||||
for name, input := range config.Inputs {
|
rc.workflowCallInputs = make(map[string]any, len(config.Inputs))
|
||||||
value := rc.caller.runContext.Run.Job().With[name]
|
for name, input := range config.Inputs {
|
||||||
if value != nil {
|
value, eval, label := callerJob.With[name], callerEval, "input"
|
||||||
if str, ok := value.(string); ok {
|
if value == nil {
|
||||||
// evaluate using the calling RunContext (outside)
|
value, eval, label = input.Default, calleeEval(), "the default of input"
|
||||||
value = rc.caller.runContext.ExprEval.Interpolate(ctx, str)
|
}
|
||||||
}
|
if str, ok := value.(string); ok {
|
||||||
|
var err error
|
||||||
|
if value, err = eval.Interpolate(ctx, str); err != nil {
|
||||||
|
return fmt.Errorf("unable to interpolate %s %s: %w", label, name, err)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
rc.workflowCallInputs[name] = coerceInputValue(value, input.Type)
|
||||||
|
}
|
||||||
|
|
||||||
if value == nil && config != nil && config.Inputs != nil {
|
secrets := callerJob.Secrets()
|
||||||
value = input.Default
|
if secrets == nil && callerJob.InheritSecrets() {
|
||||||
if rc.ExprEval != nil {
|
secrets = rc.caller.runContext.Config.Secrets
|
||||||
if str, ok := value.(string); ok {
|
}
|
||||||
// evaluate using the called RunContext (inside)
|
rc.workflowCallSecrets = make(map[string]string, len(secrets))
|
||||||
value = rc.ExprEval.Interpolate(ctx, str)
|
for k, v := range secrets {
|
||||||
}
|
var err error
|
||||||
}
|
if rc.workflowCallSecrets[k], err = callerEval.Interpolate(ctx, v); err != nil {
|
||||||
}
|
return fmt.Errorf("unable to interpolate secret %s: %w", k, err)
|
||||||
|
|
||||||
(*inputs)[name] = coerceInputValue(value, input.Type)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func getWorkflowSecrets(ctx context.Context, rc *RunContext) map[string]string {
|
func getWorkflowSecrets(rc *RunContext) map[string]string {
|
||||||
if rc.caller != nil {
|
if rc.caller != nil {
|
||||||
job := rc.caller.runContext.Run.Job()
|
return rc.workflowCallSecrets
|
||||||
secrets := job.Secrets()
|
|
||||||
|
|
||||||
if secrets == nil && job.InheritSecrets() {
|
|
||||||
secrets = rc.caller.runContext.Config.Secrets
|
|
||||||
}
|
|
||||||
|
|
||||||
// Interpolate into a new map. secrets may be the shared Config.Secrets (or the job's
|
|
||||||
// map), which other parallel jobs read concurrently (e.g. log masking), so mutating it
|
|
||||||
// in place is a data race.
|
|
||||||
interpolated := make(map[string]string, len(secrets))
|
|
||||||
for k, v := range secrets {
|
|
||||||
interpolated[k] = rc.caller.runContext.ExprEval.Interpolate(ctx, v)
|
|
||||||
}
|
|
||||||
|
|
||||||
return interpolated
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return rc.Config.Secrets
|
return rc.Config.Secrets
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -266,19 +266,21 @@ func TestInterpolate(t *testing.T) {
|
|||||||
{"${{ null }}", ""},
|
{"${{ null }}", ""},
|
||||||
{"${{ fromJSON('[1,2]') }}", "Array"},
|
{"${{ fromJSON('[1,2]') }}", "Array"},
|
||||||
{"${{ fromJSON('{\"a\":1}') }}", "Object"},
|
{"${{ fromJSON('{\"a\":1}') }}", "Object"},
|
||||||
// a malformed part must not restructure its neighbours, and it interpolates to nothing
|
|
||||||
{"${{ 1) && (2 }}", ""},
|
|
||||||
{"run ${{ 1) && (2 }} now", ""},
|
|
||||||
{"${{ 1", "${{ 1"},
|
{"${{ 1", "${{ 1"},
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, table := range tables {
|
for _, table := range tables {
|
||||||
t.Run("interpolate", func(t *testing.T) {
|
t.Run("interpolate", func(t *testing.T) {
|
||||||
assertObject := assert.New(t)
|
out, err := ee.Interpolate(context.Background(), table.in)
|
||||||
out := ee.Interpolate(context.Background(), table.in)
|
require.NoError(t, err, table.in)
|
||||||
assertObject.Equal(table.out, out, table.in)
|
assert.Equal(t, table.out, out, table.in)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
for _, in := range []string{"${{ 1) && (2 }}", "run ${{ 1) && (2 }} now"} {
|
||||||
|
_, err := ee.Interpolate(context.Background(), in)
|
||||||
|
assert.Error(t, err, in)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestGetEvaluatorInputsBoolean(t *testing.T) {
|
func TestGetEvaluatorInputsBoolean(t *testing.T) {
|
||||||
@@ -352,7 +354,7 @@ on:
|
|||||||
}
|
}
|
||||||
ghc := &model.GithubContext{EventName: eventName, Event: table.event}
|
ghc := &model.GithubContext{EventName: eventName, Event: table.event}
|
||||||
|
|
||||||
inputs := getEvaluatorInputs(context.Background(), rc, nil, ghc)
|
inputs := getEvaluatorInputs(rc, nil, ghc)
|
||||||
assert.Equal(t, table.flag, inputs["flag"])
|
assert.Equal(t, table.flag, inputs["flag"])
|
||||||
assert.Equal(t, "gitea", inputs["name"])
|
assert.Equal(t, "gitea", inputs["name"])
|
||||||
})
|
})
|
||||||
@@ -372,7 +374,8 @@ jobs:
|
|||||||
|
|
||||||
runner := &runnerImpl{config: &Config{Secrets: map[string]string{"A": "s3cr3t-a", "B": "s3cr3t-b"}}}
|
runner := &runnerImpl{config: &Config{Secrets: map[string]string{"A": "s3cr3t-a", "B": "s3cr3t-b"}}}
|
||||||
containerName := func(jobID string) string {
|
containerName := func(jobID string) string {
|
||||||
rc := runner.newRunContext(t.Context(), &model.Run{JobID: jobID, Workflow: workflow}, nil)
|
rc, err := runner.newRunContext(t.Context(), &model.Run{JobID: jobID, Workflow: workflow}, nil)
|
||||||
|
require.NoError(t, err)
|
||||||
assert.NotContains(t, rc.Name, "s3cr3t")
|
assert.NotContains(t, rc.Name, "s3cr3t")
|
||||||
return rc.jobContainerName()
|
return rc.jobContainerName()
|
||||||
}
|
}
|
||||||
|
|||||||
+59
-30
@@ -18,6 +18,7 @@ import (
|
|||||||
"slices"
|
"slices"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
"unicode"
|
"unicode"
|
||||||
|
|
||||||
@@ -154,11 +155,9 @@ func newJobExecutor(info jobInfo, sf stepFactory, rc *RunContext) common.Executo
|
|||||||
if rc.Run == nil {
|
if rc.Run == nil {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
rc.ExprEval = rc.NewExpressionEvaluator(ctx)
|
if err := evaluateJobEnvAndDefaults(ctx, rc); err != nil {
|
||||||
// evaluate environment variables since they can contain
|
reportStepError(ctx, rc, err)
|
||||||
// GitHub's special environment variables.
|
return err
|
||||||
for k, v := range rc.GetEnv() {
|
|
||||||
rc.Env[k] = rc.ExprEval.Interpolate(ctx, v)
|
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
@@ -240,6 +239,8 @@ func newJobExecutor(info jobInfo, sf stepFactory, rc *RunContext) common.Executo
|
|||||||
// swallowed: a bad output fails this job, it must not abandon the rest of the plan
|
// swallowed: a bad output fails this job, it must not abandon the rest of the plan
|
||||||
if err := info.interpolateOutputs()(ctx); err != nil {
|
if err := info.interpolateOutputs()(ctx); err != nil {
|
||||||
reportStepError(ctx, rc, err)
|
reportStepError(ctx, rc, err)
|
||||||
|
} else if err := setJobOutputs(ctx, rc); err != nil {
|
||||||
|
reportStepError(ctx, rc, err)
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
@@ -258,23 +259,23 @@ func newJobExecutor(info jobInfo, sf stepFactory, rc *RunContext) common.Executo
|
|||||||
logger.Errorf("##[error]%s", EscapeCommandData("Error while stop job container: "+err.Error()))
|
logger.Errorf("##[error]%s", EscapeCommandData("Error while stop job container: "+err.Error()))
|
||||||
}
|
}
|
||||||
setJobResult(ctx, info, rc, jobError == nil)
|
setJobResult(ctx, info, rc, jobError == nil)
|
||||||
setJobOutputs(ctx, rc)
|
|
||||||
|
|
||||||
return err
|
return err
|
||||||
})
|
})
|
||||||
|
|
||||||
stepsExecutor := newStepsExecutor(rc, preSteps, steps)
|
return common.Executor(func(ctx context.Context) error {
|
||||||
|
if err := info.startContainer()(ctx); err != nil {
|
||||||
return common.NewPipelineExecutor(info.startContainer(), stepsExecutor.
|
return err
|
||||||
Finally(func(ctx context.Context) error {
|
}
|
||||||
|
return newStepsExecutor(rc, preSteps, steps).Finally(func(ctx context.Context) error {
|
||||||
// Record an interrupt (backstop for interrupts that land outside the main
|
// Record an interrupt (backstop for interrupts that land outside the main
|
||||||
// step loop) so the post steps observe the cancelled/failed job status.
|
// step loop) so the post steps observe the cancelled/failed job status.
|
||||||
rc.markInterrupted(ctx.Err())
|
rc.markInterrupted(ctx.Err())
|
||||||
postCtx, cancel := postStepsContext(ctx)
|
postCtx, cancel := postStepsContext(ctx)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
return postExecutor(postCtx)
|
return postExecutor(postCtx)
|
||||||
}).
|
})(ctx)
|
||||||
Finally(info.closeContainer()))
|
}).Finally(info.closeContainer())
|
||||||
}
|
}
|
||||||
|
|
||||||
// postStepsContext derives the context used to run the job's post/cleanup steps from the
|
// postStepsContext derives the context used to run the job's post/cleanup steps from the
|
||||||
@@ -413,30 +414,58 @@ func setJobResult(ctx context.Context, info jobInfo, rc *RunContext, success boo
|
|||||||
logger.WithField("jobResult", jobResult).Infof("Job %s", jobResultMessage)
|
logger.WithField("jobResult", jobResult).Infof("Job %s", jobResultMessage)
|
||||||
}
|
}
|
||||||
|
|
||||||
func setJobOutputs(ctx context.Context, rc *RunContext) {
|
// evaluateJobEnvAndDefaults resolves the job's env and defaults.run once, as GitHub does at job setup.
|
||||||
if rc.caller != nil {
|
func evaluateJobEnvAndDefaults(ctx context.Context, rc *RunContext) error {
|
||||||
// map outputs for reusable workflows
|
rc.ExprEval = rc.NewExpressionEvaluator(ctx)
|
||||||
callerOutputs := make(map[string]string)
|
var err error
|
||||||
|
for k, v := range rc.GetEnv() {
|
||||||
ee := rc.NewExpressionEvaluator(ctx)
|
if rc.Env[k], err = rc.ExprEval.Interpolate(ctx, v); err != nil {
|
||||||
|
return fmt.Errorf("unable to interpolate env %s: %w", k, err)
|
||||||
for k, v := range rc.Run.Workflow.WorkflowCallConfig().Outputs {
|
|
||||||
callerOutputs[k] = ee.Interpolate(ctx, ee.Interpolate(ctx, v.Value))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Matrix combinations of a reusable-workflow caller share the caller's *model.Job;
|
|
||||||
// serialize the write so parallel combos don't race on its Outputs field.
|
|
||||||
callerJob := rc.caller.runContext.Run.Job()
|
|
||||||
defer lockJob(callerJob)()
|
|
||||||
callerJob.Outputs = callerOutputs
|
|
||||||
}
|
}
|
||||||
|
defaults := rc.Run.Job().Defaults.Run
|
||||||
|
if rc.jobRunDefaults.Shell, err = rc.ExprEval.Interpolate(ctx, defaults.Shell); err != nil {
|
||||||
|
return fmt.Errorf("unable to interpolate defaults.run.shell: %w", err)
|
||||||
|
}
|
||||||
|
if rc.jobRunDefaults.WorkingDirectory, err = rc.ExprEval.Interpolate(ctx, defaults.WorkingDirectory); err != nil {
|
||||||
|
return fmt.Errorf("unable to interpolate defaults.run.working-directory: %w", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func setJobOutputs(ctx context.Context, rc *RunContext) error {
|
||||||
|
if rc.caller == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
outputs := rc.Run.Workflow.WorkflowCallConfig().Outputs
|
||||||
|
callerOutputs := make(map[string]string, len(outputs))
|
||||||
|
ee := sync.OnceValue(func() *expressionEvaluator { return rc.NewExpressionEvaluator(ctx) })
|
||||||
|
for k, v := range outputs {
|
||||||
|
value := v.Value
|
||||||
|
for range 2 { // two passes, the value resolves through a job output
|
||||||
|
var err error
|
||||||
|
if value, err = ee().Interpolate(ctx, value); err != nil {
|
||||||
|
return fmt.Errorf("unable to interpolate workflow output %s: %w", k, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
callerOutputs[k] = value
|
||||||
|
}
|
||||||
|
|
||||||
|
// Matrix combinations of a reusable-workflow caller share the caller's *model.Job;
|
||||||
|
// serialize the write so parallel combos don't race on its Outputs field.
|
||||||
|
callerJob := rc.caller.runContext.Run.Job()
|
||||||
|
defer lockJob(callerJob)()
|
||||||
|
callerJob.Outputs = callerOutputs
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// applyJobTimeout applies the job-level timeout-minutes to ctx, mirroring the
|
// applyJobTimeout applies the job-level timeout-minutes to ctx, mirroring the
|
||||||
// step-level evaluateStepTimeout in step.go.
|
// step-level evaluateStepTimeout in step.go.
|
||||||
func applyJobTimeout(ctx context.Context, rc *RunContext, job *model.Job) (context.Context, context.CancelFunc) {
|
func applyJobTimeout(ctx context.Context, rc *RunContext, job *model.Job) (context.Context, context.CancelFunc) {
|
||||||
timeout := rc.ExprEval.Interpolate(ctx, job.TimeoutMinutes)
|
timeout, err := rc.ExprEval.Interpolate(ctx, job.TimeoutMinutes)
|
||||||
if timeout != "" {
|
if err != nil {
|
||||||
|
common.Logger(ctx).Errorf("An error occurred when attempting to determine the job timeout: %s", err)
|
||||||
|
} else if timeout != "" {
|
||||||
if timeoutMinutes, err := strconv.ParseInt(timeout, 10, 64); err == nil {
|
if timeoutMinutes, err := strconv.ParseInt(timeout, 10, 64); err == nil {
|
||||||
return context.WithTimeout(ctx, time.Duration(timeoutMinutes)*time.Minute)
|
return context.WithTimeout(ctx, time.Duration(timeoutMinutes)*time.Minute)
|
||||||
}
|
}
|
||||||
@@ -635,7 +664,7 @@ func archiveEntryMatchesPath(entryName, requestedPath string) bool {
|
|||||||
|
|
||||||
func useStepLogger(rc *RunContext, stepModel *model.Step, stage stepStage, executor common.Executor) common.Executor {
|
func useStepLogger(rc *RunContext, stepModel *model.Step, stage stepStage, executor common.Executor) common.Executor {
|
||||||
return func(ctx context.Context) error {
|
return func(ctx context.Context) error {
|
||||||
ctx = withStepLogger(ctx, stepModel.Number, stepModel.ID, rc.ExprEval.Interpolate(ctx, stepModel.String()), stage.String())
|
ctx = withStepLogger(ctx, stepModel.Number, stepModel.ID, rc.ExprEval.InterpolateName(ctx, stepModel.String()), stage.String())
|
||||||
|
|
||||||
logWriter := rc.commandLogWriter(ctx)
|
logWriter := rc.commandLogWriter(ctx)
|
||||||
|
|
||||||
|
|||||||
@@ -300,6 +300,8 @@ func TestNewJobExecutor(t *testing.T) {
|
|||||||
result string
|
result string
|
||||||
hasError bool
|
hasError bool
|
||||||
output string
|
output string
|
||||||
|
startError error
|
||||||
|
cancelOnStart bool
|
||||||
}{
|
}{
|
||||||
{
|
{
|
||||||
name: "zeroSteps",
|
name: "zeroSteps",
|
||||||
@@ -435,6 +437,21 @@ func TestNewJobExecutor(t *testing.T) {
|
|||||||
result: "failure",
|
result: "failure",
|
||||||
output: "${{ 'test' != test }}",
|
output: "${{ 'test' != test }}",
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: "start failure",
|
||||||
|
steps: []*model.Step{{ID: "1"}},
|
||||||
|
executedSteps: []string{"startContainer", "closeContainer"},
|
||||||
|
startError: errors.New("start failed"),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "cancelled at startup boundary",
|
||||||
|
steps: []*model.Step{{ID: "1"}},
|
||||||
|
preSteps: []bool{false},
|
||||||
|
postSteps: []bool{true},
|
||||||
|
executedSteps: []string{"startContainer", "step1", "post1", "interpolateOutputs", "stopContainer", "closeContainer"},
|
||||||
|
result: "cancelled",
|
||||||
|
cancelOnStart: true,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
contains := func(needle string, haystack []string) bool {
|
contains := func(needle string, haystack []string) bool {
|
||||||
@@ -445,7 +462,8 @@ func TestNewJobExecutor(t *testing.T) {
|
|||||||
t.Run(tt.name, func(t *testing.T) {
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
fmt.Printf("::group::%s\n", tt.name) //nolint:forbidigo // pre-existing issue from nektos/act
|
fmt.Printf("::group::%s\n", tt.name) //nolint:forbidigo // pre-existing issue from nektos/act
|
||||||
|
|
||||||
ctx := common.WithJobErrorContainer(context.Background())
|
ctx, cancel := context.WithCancel(common.WithJobErrorContainer(context.Background()))
|
||||||
|
defer cancel()
|
||||||
jim := &jobInfoMock{}
|
jim := &jobInfoMock{}
|
||||||
sfm := &stepFactoryMock{}
|
sfm := &stepFactoryMock{}
|
||||||
rc := &RunContext{
|
rc := &RunContext{
|
||||||
@@ -470,9 +488,12 @@ func TestNewJobExecutor(t *testing.T) {
|
|||||||
jim.On("steps").Return(tt.steps)
|
jim.On("steps").Return(tt.steps)
|
||||||
|
|
||||||
if len(tt.steps) > 0 {
|
if len(tt.steps) > 0 {
|
||||||
jim.On("startContainer").Return(func(ctx context.Context) error {
|
jim.On("startContainer").Return(func(_ context.Context) error {
|
||||||
executorOrder = append(executorOrder, "startContainer")
|
executorOrder = append(executorOrder, "startContainer")
|
||||||
return nil
|
if tt.cancelOnStart {
|
||||||
|
cancel()
|
||||||
|
}
|
||||||
|
return tt.startError
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -506,7 +527,7 @@ func TestNewJobExecutor(t *testing.T) {
|
|||||||
defer sm.AssertExpectations(t)
|
defer sm.AssertExpectations(t)
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(tt.steps) > 0 {
|
if len(tt.steps) > 0 && tt.startError == nil {
|
||||||
jim.On("matrix").Return(map[string]any{})
|
jim.On("matrix").Return(map[string]any{})
|
||||||
|
|
||||||
jim.On("interpolateOutputs").Return(func(ctx context.Context) error {
|
jim.On("interpolateOutputs").Return(func(ctx context.Context) error {
|
||||||
@@ -520,12 +541,17 @@ func TestNewJobExecutor(t *testing.T) {
|
|||||||
if contains("stopContainer", tt.executedSteps) {
|
if contains("stopContainer", tt.executedSteps) {
|
||||||
jim.On("stopContainer").Return(func(ctx context.Context) error {
|
jim.On("stopContainer").Return(func(ctx context.Context) error {
|
||||||
executorOrder = append(executorOrder, "stopContainer")
|
executorOrder = append(executorOrder, "stopContainer")
|
||||||
|
require.NoError(t, ctx.Err())
|
||||||
|
_, bounded := ctx.Deadline()
|
||||||
|
require.True(t, bounded)
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
jim.On("result", tt.result)
|
jim.On("result", tt.result)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(tt.steps) > 0 {
|
||||||
jim.On("closeContainer").Return(func(ctx context.Context) error {
|
jim.On("closeContainer").Return(func(ctx context.Context) error {
|
||||||
executorOrder = append(executorOrder, "closeContainer")
|
executorOrder = append(executorOrder, "closeContainer")
|
||||||
return nil
|
return nil
|
||||||
@@ -534,7 +560,14 @@ func TestNewJobExecutor(t *testing.T) {
|
|||||||
|
|
||||||
executor := newJobExecutor(jim, sfm, rc)
|
executor := newJobExecutor(jim, sfm, rc)
|
||||||
err := executor(ctx)
|
err := executor(ctx)
|
||||||
assert.NoError(t, err) //nolint:testifylint // pre-existing issue from nektos/act
|
switch {
|
||||||
|
case tt.startError != nil:
|
||||||
|
require.ErrorIs(t, err, tt.startError)
|
||||||
|
case tt.cancelOnStart:
|
||||||
|
require.ErrorIs(t, err, context.Canceled)
|
||||||
|
default:
|
||||||
|
require.NoError(t, err)
|
||||||
|
}
|
||||||
assert.Empty(t, rc.Run.Job().Outputs["bad"])
|
assert.Empty(t, rc.Run.Job().Outputs["bad"])
|
||||||
assert.Equal(t, tt.executedSteps, executorOrder)
|
assert.Equal(t, tt.executedSteps, executorOrder)
|
||||||
|
|
||||||
|
|||||||
@@ -244,7 +244,7 @@ func TestPatchActionsAtTheContainerCopy(t *testing.T) {
|
|||||||
require.NoError(t, os.WriteFile(script, []byte(gateTSC), 0o600))
|
require.NoError(t, os.WriteFile(script, []byte(gateTSC), 0o600))
|
||||||
|
|
||||||
var copied string
|
var copied string
|
||||||
cm.On("CopyDir", mock.Anything, mock.Anything, mock.Anything).Return(func(context.Context) error {
|
cm.On("CopyDir", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(func(context.Context) error {
|
||||||
body, err := os.ReadFile(script)
|
body, err := os.ReadFile(script)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
copied = string(body)
|
copied = string(body)
|
||||||
|
|||||||
@@ -95,9 +95,12 @@ func newRemoteReusableWorkflowExecutor(rc *RunContext) common.Executor {
|
|||||||
// remoteReusableWorkflow.URL = rc.getGithubContext(ctx).ServerURL
|
// remoteReusableWorkflow.URL = rc.getGithubContext(ctx).ServerURL
|
||||||
func cloneRemoteReusableWorkflow(rc *RunContext, cloneURL, ref, targetDirectory, token string) common.Executor {
|
func cloneRemoteReusableWorkflow(rc *RunContext, cloneURL, ref, targetDirectory, token string) common.Executor {
|
||||||
return func(ctx context.Context) error {
|
return func(ctx context.Context) error {
|
||||||
cloneURL = rc.NewExpressionEvaluator(ctx).Interpolate(ctx, cloneURL)
|
interpolatedURL, err := rc.NewExpressionEvaluator(ctx).Interpolate(ctx, cloneURL)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("unable to interpolate the workflow clone URL: %w", err)
|
||||||
|
}
|
||||||
return git.NewGitCloneExecutor(git.NewGitCloneExecutorInput{
|
return git.NewGitCloneExecutor(git.NewGitCloneExecutorInput{
|
||||||
URL: cloneURL,
|
URL: interpolatedURL,
|
||||||
Ref: ref,
|
Ref: ref,
|
||||||
Dir: targetDirectory,
|
Dir: targetDirectory,
|
||||||
Token: token,
|
Token: token,
|
||||||
|
|||||||
+180
-102
@@ -67,7 +67,11 @@ type RunContext struct {
|
|||||||
actionInputs map[string]any // inputs of the composite action this runs, nil for a job
|
actionInputs map[string]any // inputs of the composite action this runs, nil for a job
|
||||||
Masks []string
|
Masks []string
|
||||||
cleanUpJobContainer common.Executor
|
cleanUpJobContainer common.Executor
|
||||||
caller *caller // job calling this RunContext (reusable workflows)
|
caller *caller // job calling this RunContext (reusable workflows)
|
||||||
|
workflowCallInputs map[string]any // the caller's with:, resolved once by resolveWorkflowCall
|
||||||
|
workflowCallSecrets map[string]string // the caller's secrets:, resolved once by resolveWorkflowCall
|
||||||
|
jobRunDefaults model.RunDefaults // defaults.run, resolved once at job setup as GitHub does
|
||||||
|
platformImage string // container.image or the runs-on pick, resolved once by isEnabled
|
||||||
// summaryFileInitialized tracks which per-step summary files (workflow/step-summary-N.md)
|
// 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
|
// have already been created on the JobContainer. The runner sets up file-command files
|
||||||
// via JobContainer.Copy at the start of every phase, which truncates them — fine for
|
// via JobContainer.Copy at the start of every phase, which truncates them — fine for
|
||||||
@@ -92,6 +96,7 @@ type RunContext struct {
|
|||||||
jobContainerID string
|
jobContainerID string
|
||||||
hasBash *bool // memoized implicit-shell probe, only set on the top-level RunContext
|
hasBash *bool // memoized implicit-shell probe, only set on the top-level RunContext
|
||||||
jobNetworkName string
|
jobNetworkName string
|
||||||
|
dockerProxy *container.DockerProxy
|
||||||
// stepEnv is a copy of the running step's environment, so that workflow commands parsed out
|
// stepEnv is a copy of the running step's environment, so that workflow commands parsed out
|
||||||
// of the container's output can be judged against it. Written by runStepExecutor and read on
|
// of the container's output can be judged against it. Written by runStepExecutor and read on
|
||||||
// the log-writer goroutine, hence unsecureCommandMu, which also guards unsecureCommandErr.
|
// the log-writer goroutine, hence unsecureCommandMu, which also guards unsecureCommandErr.
|
||||||
@@ -246,11 +251,31 @@ func (rc *RunContext) validVolumes() []string {
|
|||||||
if rc.Config.SharedToolCache {
|
if rc.Config.SharedToolCache {
|
||||||
volumes = append(volumes, sharedToolCacheVolume)
|
volumes = append(volumes, sharedToolCacheVolume)
|
||||||
}
|
}
|
||||||
|
if rc.Config.BindWorkdir {
|
||||||
|
volumes = append(volumes, rc.Config.Workdir)
|
||||||
|
}
|
||||||
|
if rc.dockerProxy != nil {
|
||||||
|
volumes = append(volumes, rc.dockerProxy.Socket)
|
||||||
|
}
|
||||||
// TODO: add a new configuration to control whether the docker daemon can be mounted
|
// TODO: add a new configuration to control whether the docker daemon can be mounted
|
||||||
return append(volumes, name, name+"-env",
|
return append(volumes, name, name+"-env",
|
||||||
getDockerDaemonSocketMountPath(rc.containerDaemonSocket()))
|
getDockerDaemonSocketMountPath(rc.containerDaemonSocket()))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (rc *RunContext) jobDockerSocket() string {
|
||||||
|
if rc.dockerProxy != nil {
|
||||||
|
return rc.dockerProxy.Socket
|
||||||
|
}
|
||||||
|
return getDockerDaemonSocketMountPath(rc.containerDaemonSocket())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rc *RunContext) startDockerProxy(ctx context.Context) {
|
||||||
|
if !filepath.IsAbs(strings.TrimPrefix(rc.containerDaemonSocket(), "unix://")) || common.Dryrun(ctx) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
rc.dockerProxy = container.NewDockerProxy(ctx, rc.jobContainerName())
|
||||||
|
}
|
||||||
|
|
||||||
// toolCache returns the tool cache path the job sees, relocatable through RUNNER_TOOL_CACHE.
|
// toolCache returns the tool cache path the job sees, relocatable through RUNNER_TOOL_CACHE.
|
||||||
func (rc *RunContext) toolCache(fallback string) string {
|
func (rc *RunContext) toolCache(fallback string) string {
|
||||||
if path := rc.GetEnv()["RUNNER_TOOL_CACHE"]; path != "" {
|
if path := rc.GetEnv()["RUNNER_TOOL_CACHE"]; path != "" {
|
||||||
@@ -299,7 +324,7 @@ func splitVolumes(specs []string) ([]string, map[string]string, map[string]bool)
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Returns the binds and mounts for the container, resolving paths as appopriate
|
// Returns the binds and mounts for the container, resolving paths as appopriate
|
||||||
func (rc *RunContext) GetBindsAndMounts() ([]string, map[string]string) {
|
func (rc *RunContext) GetBindsAndMounts() ([]string, map[string]string, error) {
|
||||||
name := rc.jobContainerName()
|
name := rc.jobContainerName()
|
||||||
ext := container.LinuxContainerEnvironmentExtensions{}
|
ext := container.LinuxContainerEnvironmentExtensions{}
|
||||||
|
|
||||||
@@ -308,7 +333,10 @@ func (rc *RunContext) GetBindsAndMounts() ([]string, map[string]string) {
|
|||||||
if container := job.Container(); container != nil {
|
if container := job.Container(); container != nil {
|
||||||
for _, v := range container.Volumes {
|
for _, v := range container.Volumes {
|
||||||
if rc.ExprEval != nil {
|
if rc.ExprEval != nil {
|
||||||
v = rc.ExprEval.Interpolate(context.Background(), v)
|
var err error
|
||||||
|
if v, err = rc.ExprEval.Interpolate(context.Background(), v); err != nil {
|
||||||
|
return nil, nil, fmt.Errorf("unable to interpolate container.volumes: %w", err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
volumes = append(volumes, v)
|
volumes = append(volumes, v)
|
||||||
}
|
}
|
||||||
@@ -317,8 +345,8 @@ func (rc *RunContext) GetBindsAndMounts() ([]string, map[string]string) {
|
|||||||
// the runner's own mounts below yield to the targets the job claims
|
// the runner's own mounts below yield to the targets the job claims
|
||||||
binds, mounts, claimed := splitVolumes(volumes)
|
binds, mounts, claimed := splitVolumes(volumes)
|
||||||
|
|
||||||
if daemonSocket := rc.containerDaemonSocket(); daemonSocket != "-" && !claimed["/var/run/docker.sock"] {
|
if rc.containerDaemonSocket() != "-" && !claimed["/var/run/docker.sock"] {
|
||||||
binds = append(binds, getDockerDaemonSocketMountPath(daemonSocket)+":/var/run/docker.sock")
|
binds = append(binds, rc.jobDockerSocket()+":/var/run/docker.sock")
|
||||||
}
|
}
|
||||||
if rc.Config.SharedToolCache {
|
if rc.Config.SharedToolCache {
|
||||||
if toolCache := rc.toolCache(container.DefaultToolCache); !claimed[toolCache] {
|
if toolCache := rc.toolCache(container.DefaultToolCache); !claimed[toolCache] {
|
||||||
@@ -342,7 +370,7 @@ func (rc *RunContext) GetBindsAndMounts() ([]string, map[string]string) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return binds, mounts
|
return binds, mounts, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (rc *RunContext) startHostEnvironment() common.Executor {
|
func (rc *RunContext) startHostEnvironment() common.Executor {
|
||||||
@@ -433,7 +461,7 @@ var newContainer = container.NewContainer
|
|||||||
func (rc *RunContext) startJobContainer() common.Executor {
|
func (rc *RunContext) startJobContainer() common.Executor {
|
||||||
return func(ctx context.Context) error {
|
return func(ctx context.Context) error {
|
||||||
logger := common.Logger(ctx)
|
logger := common.Logger(ctx)
|
||||||
image := rc.platformImage(ctx)
|
image := rc.platformImage
|
||||||
logWriter := rc.commandLogWriter(ctx)
|
logWriter := rc.commandLogWriter(ctx)
|
||||||
|
|
||||||
username, password, err := rc.handleCredentials(ctx)
|
username, password, err := rc.handleCredentials(ctx)
|
||||||
@@ -451,19 +479,20 @@ func (rc *RunContext) startJobContainer() common.Executor {
|
|||||||
envList = append(envList, rc.runnerEnv(ctx)...)
|
envList = append(envList, rc.runnerEnv(ctx)...)
|
||||||
envList = append(envList, fmt.Sprintf("%s=%s", "LANG", "C.UTF-8")) // Use same locale as GitHub Actions
|
envList = append(envList, fmt.Sprintf("%s=%s", "LANG", "C.UTF-8")) // Use same locale as GitHub Actions
|
||||||
|
|
||||||
ext := container.LinuxContainerEnvironmentExtensions{}
|
|
||||||
binds, mounts := rc.GetBindsAndMounts()
|
|
||||||
|
|
||||||
// specify the network to which the container will connect when `docker create` stage. (like execute command line: docker create --network <networkName> <image>)
|
// specify the network to which the container will connect when `docker create` stage. (like execute command line: docker create --network <networkName> <image>)
|
||||||
// if using service containers, will create a new network for the containers.
|
// if using service containers, will create a new network for the containers.
|
||||||
// and it will be removed after at last.
|
// and it will be removed after at last.
|
||||||
networkName, createAndDeleteNetwork := rc.networkNameForGitea()
|
networkName, createAndDeleteNetwork := rc.networkNameForGitea()
|
||||||
|
rc.cleanUpJobContainer = rc.cleanupJobResources(networkName, createAndDeleteNetwork)
|
||||||
|
|
||||||
// add service containers
|
// add service containers
|
||||||
for serviceID, spec := range rc.Run.Job().Services {
|
for serviceID, spec := range rc.Run.Job().Services {
|
||||||
// GitHub compatibility: skip services whose image evaluates to an
|
// GitHub compatibility: skip services whose image evaluates to an
|
||||||
// empty string, enabling conditional services via expressions
|
// empty string, enabling conditional services via expressions
|
||||||
serviceImage := rc.ExprEval.Interpolate(ctx, spec.Image)
|
serviceImage, err := rc.ExprEval.Interpolate(ctx, spec.Image)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("unable to interpolate service %s image: %w", serviceID, err)
|
||||||
|
}
|
||||||
if serviceImage == "" {
|
if serviceImage == "" {
|
||||||
logger.Infof("The service '%s' will not be started because the container definition has an empty image.", serviceID)
|
logger.Infof("The service '%s' will not be started because the container definition has an empty image.", serviceID)
|
||||||
continue
|
continue
|
||||||
@@ -473,16 +502,20 @@ func (rc *RunContext) startJobContainer() common.Executor {
|
|||||||
// a service reaches the internet the way the job does; its own env still wins
|
// a service reaches the internet the way the job does; its own env still wins
|
||||||
maps0.Copy(interpolatedEnvs, rc.Config.ProxyEnv)
|
maps0.Copy(interpolatedEnvs, rc.Config.ProxyEnv)
|
||||||
for k, v := range spec.Env {
|
for k, v := range spec.Env {
|
||||||
interpolatedEnvs[k] = rc.ExprEval.Interpolate(ctx, v)
|
if interpolatedEnvs[k], err = rc.ExprEval.Interpolate(ctx, v); err != nil {
|
||||||
|
return fmt.Errorf("unable to interpolate service %s env %s: %w", serviceID, k, err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
envs := make([]string, 0, len(interpolatedEnvs))
|
envs := make([]string, 0, len(interpolatedEnvs))
|
||||||
for k, v := range interpolatedEnvs {
|
for k, v := range interpolatedEnvs {
|
||||||
envs = append(envs, fmt.Sprintf("%s=%s", k, v))
|
envs = append(envs, fmt.Sprintf("%s=%s", k, v))
|
||||||
}
|
}
|
||||||
// interpolate cmd
|
// interpolate cmd
|
||||||
interpolatedCmd := make([]string, 0, len(spec.Cmd))
|
interpolatedCmd := make([]string, len(spec.Cmd))
|
||||||
for _, v := range spec.Cmd {
|
for i, v := range spec.Cmd {
|
||||||
interpolatedCmd = append(interpolatedCmd, rc.ExprEval.Interpolate(ctx, v))
|
if interpolatedCmd[i], err = rc.ExprEval.Interpolate(ctx, v); err != nil {
|
||||||
|
return fmt.Errorf("unable to interpolate service %s command: %w", serviceID, err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
// keep these local: reusing username/password would overwrite the
|
// keep these local: reusing username/password would overwrite the
|
||||||
// credentials the job container is pulled with further down
|
// credentials the job container is pulled with further down
|
||||||
@@ -491,20 +524,28 @@ func (rc *RunContext) startJobContainer() common.Executor {
|
|||||||
return fmt.Errorf("failed to handle service %s credentials: %w", serviceID, err)
|
return fmt.Errorf("failed to handle service %s credentials: %w", serviceID, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
interpolatedVolumes := make([]string, 0, len(spec.Volumes))
|
interpolatedVolumes := make([]string, len(spec.Volumes))
|
||||||
for _, volume := range spec.Volumes {
|
for i, volume := range spec.Volumes {
|
||||||
interpolatedVolumes = append(interpolatedVolumes, rc.ExprEval.Interpolate(ctx, volume))
|
if interpolatedVolumes[i], err = rc.ExprEval.Interpolate(ctx, volume); err != nil {
|
||||||
|
return fmt.Errorf("unable to interpolate service %s volumes: %w", serviceID, err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
serviceBinds, serviceMounts, _ := splitVolumes(interpolatedVolumes)
|
serviceBinds, serviceMounts, _ := splitVolumes(interpolatedVolumes)
|
||||||
|
|
||||||
interpolatedPorts := make([]string, 0, len(spec.Ports))
|
interpolatedPorts := make([]string, len(spec.Ports))
|
||||||
for _, port := range spec.Ports {
|
for i, port := range spec.Ports {
|
||||||
interpolatedPorts = append(interpolatedPorts, rc.ExprEval.Interpolate(ctx, port))
|
if interpolatedPorts[i], err = rc.ExprEval.Interpolate(ctx, port); err != nil {
|
||||||
|
return fmt.Errorf("unable to interpolate service %s ports: %w", serviceID, err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
exposedPorts, portBindings, err := nat.ParsePortSpecs(interpolatedPorts)
|
exposedPorts, portBindings, err := nat.ParsePortSpecs(interpolatedPorts)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("failed to parse service %s ports: %w", serviceID, err)
|
return fmt.Errorf("failed to parse service %s ports: %w", serviceID, err)
|
||||||
}
|
}
|
||||||
|
serviceOptions, err := rc.ExprEval.Interpolate(ctx, spec.Options)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("unable to interpolate service %s options: %w", serviceID, err)
|
||||||
|
}
|
||||||
|
|
||||||
serviceContainerName := createContainerName(rc.jobContainerName(), serviceID)
|
serviceContainerName := createContainerName(rc.jobContainerName(), serviceID)
|
||||||
c := newContainer(&container.NewContainerInput{
|
c := newContainer(&container.NewContainerInput{
|
||||||
@@ -522,7 +563,7 @@ func (rc *RunContext) startJobContainer() common.Executor {
|
|||||||
UsernsMode: rc.Config.UsernsMode,
|
UsernsMode: rc.Config.UsernsMode,
|
||||||
Platform: rc.Config.ContainerArchitecture,
|
Platform: rc.Config.ContainerArchitecture,
|
||||||
AutoRemove: false, // so a dead service's log survives, cleanupJobResources removes it
|
AutoRemove: false, // so a dead service's log survives, cleanupJobResources removes it
|
||||||
WorkflowOptions: rc.ExprEval.Interpolate(ctx, spec.Options),
|
WorkflowOptions: serviceOptions,
|
||||||
NetworkMode: networkName,
|
NetworkMode: networkName,
|
||||||
NetworkAliases: []string{serviceID},
|
NetworkAliases: []string{serviceID},
|
||||||
ExposedPorts: exposedPorts,
|
ExposedPorts: exposedPorts,
|
||||||
@@ -533,12 +574,15 @@ func (rc *RunContext) startJobContainer() common.Executor {
|
|||||||
rc.serviceContainers = append(rc.serviceContainers, &serviceContainer{name: serviceID, image: serviceImage, container: c})
|
rc.serviceContainers = append(rc.serviceContainers, &serviceContainer{name: serviceID, image: serviceImage, container: c})
|
||||||
}
|
}
|
||||||
|
|
||||||
rc.cleanUpJobContainer = rc.cleanupJobResources(networkName, createAndDeleteNetwork)
|
|
||||||
|
|
||||||
// For Gitea, `jobContainerNetwork` should be the same as `networkName`
|
// For Gitea, `jobContainerNetwork` should be the same as `networkName`
|
||||||
jobContainerNetwork := networkName
|
jobContainerNetwork := networkName
|
||||||
|
|
||||||
rc.JobContainer = newContainer(&container.NewContainerInput{
|
workflowOptions, err := rc.workflowOptions(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
ext := container.LinuxContainerEnvironmentExtensions{}
|
||||||
|
containerInput := &container.NewContainerInput{
|
||||||
Cmd: nil,
|
Cmd: nil,
|
||||||
Entrypoint: []string{"/bin/sleep", fmt.Sprint(rc.Config.ContainerMaxLifetime.Round(time.Second).Seconds())},
|
Entrypoint: []string{"/bin/sleep", fmt.Sprint(rc.Config.ContainerMaxLifetime.Round(time.Second).Seconds())},
|
||||||
WorkingDir: ext.ToContainerPath(rc.Config.Workdir),
|
WorkingDir: ext.ToContainerPath(rc.Config.Workdir),
|
||||||
@@ -547,32 +591,39 @@ func (rc *RunContext) startJobContainer() common.Executor {
|
|||||||
Password: password,
|
Password: password,
|
||||||
Name: name,
|
Name: name,
|
||||||
Env: envList,
|
Env: envList,
|
||||||
Mounts: mounts,
|
|
||||||
NetworkMode: jobContainerNetwork,
|
NetworkMode: jobContainerNetwork,
|
||||||
NetworkAliases: []string{rc.Name},
|
NetworkAliases: []string{rc.Name},
|
||||||
Binds: binds,
|
|
||||||
Stdout: logWriter,
|
Stdout: logWriter,
|
||||||
Stderr: logWriter,
|
Stderr: logWriter,
|
||||||
Privileged: rc.Config.Privileged,
|
Privileged: rc.Config.Privileged,
|
||||||
UsernsMode: rc.Config.UsernsMode,
|
UsernsMode: rc.Config.UsernsMode,
|
||||||
Platform: rc.Config.ContainerArchitecture,
|
Platform: rc.Config.ContainerArchitecture,
|
||||||
RunnerOptions: rc.Config.ContainerOptions,
|
RunnerOptions: rc.Config.ContainerOptions,
|
||||||
WorkflowOptions: rc.workflowOptions(ctx),
|
WorkflowOptions: workflowOptions,
|
||||||
AutoRemove: true,
|
AutoRemove: true,
|
||||||
ValidVolumes: rc.validVolumes(),
|
|
||||||
AllocatePTY: rc.Config.AllocatePTY,
|
AllocatePTY: rc.Config.AllocatePTY,
|
||||||
})
|
}
|
||||||
|
rc.JobContainer = newContainer(containerInput)
|
||||||
if rc.JobContainer == nil {
|
if rc.JobContainer == nil {
|
||||||
return errors.New("failed to create job container")
|
return errors.New("failed to create job container")
|
||||||
}
|
}
|
||||||
|
defer printStartJobContainerGroup(ctx, image, name, networkName)()
|
||||||
|
if err := common.NewPipelineExecutor(
|
||||||
|
rc.stopJobContainer(),
|
||||||
|
rc.pullServicesImages(rc.Config.ForcePull),
|
||||||
|
rc.JobContainer.Pull(rc.Config.ForcePull),
|
||||||
|
).Finally(rc.closeContainer())(ctx); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
rc.startDockerProxy(ctx)
|
||||||
|
if containerInput.Binds, containerInput.Mounts, err = rc.GetBindsAndMounts(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
containerInput.ValidVolumes = rc.validVolumes()
|
||||||
|
|
||||||
rc.jobNetworkName = networkName
|
rc.jobNetworkName = networkName
|
||||||
|
|
||||||
defer printStartJobContainerGroup(ctx, image, name, networkName)()
|
|
||||||
return common.NewPipelineExecutor(
|
return common.NewPipelineExecutor(
|
||||||
rc.pullServicesImages(rc.Config.ForcePull),
|
|
||||||
rc.JobContainer.Pull(rc.Config.ForcePull),
|
|
||||||
rc.stopJobContainer(),
|
|
||||||
container.NewDockerNetworkCreateExecutor(networkName, rc.Config.ContainerNetworkCreateOptions).
|
container.NewDockerNetworkCreateExecutor(networkName, rc.Config.ContainerNetworkCreateOptions).
|
||||||
IfBool(createAndDeleteNetwork),
|
IfBool(createAndDeleteNetwork),
|
||||||
rc.startServiceContainers(),
|
rc.startServiceContainers(),
|
||||||
@@ -602,41 +653,46 @@ func (rc *RunContext) commandLogWriter(ctx context.Context) io.Writer {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// cleanupJobResources removes everything the job created, continuing past failures.
|
|
||||||
// Only job container and volume errors are returned, the rest are logged.
|
|
||||||
func (rc *RunContext) cleanupJobResources(networkName string, createAndDeleteNetwork bool) common.Executor {
|
func (rc *RunContext) cleanupJobResources(networkName string, createAndDeleteNetwork bool) common.Executor {
|
||||||
return func(ctx context.Context) error {
|
return func(ctx context.Context) error {
|
||||||
logger := common.Logger(ctx)
|
logger := common.Logger(ctx)
|
||||||
removeJobContainer := rc.JobContainer != nil
|
errs := []error{rc.closeDockerProxy(ctx)}
|
||||||
|
if rc.JobContainer != nil {
|
||||||
var errs []error
|
|
||||||
if removeJobContainer {
|
|
||||||
errs = append(errs, rc.JobContainer.Remove()(ctx))
|
errs = append(errs, rc.JobContainer.Remove()(ctx))
|
||||||
}
|
}
|
||||||
if len(rc.serviceContainers) > 0 {
|
if len(rc.serviceContainers) > 0 {
|
||||||
logger.Infof("Cleaning up services for job %s", rc.JobName)
|
logger.Infof("Cleaning up services for job %s", rc.JobName)
|
||||||
if err := rc.stopServiceContainers()(ctx); err != nil {
|
errs = append(errs, rc.stopServiceContainers()(ctx))
|
||||||
logger.Errorf("Error while cleaning services: %v", err)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if removeJobContainer {
|
if !common.Dryrun(ctx) {
|
||||||
// after the containers using them, services can hold these via `--volumes-from`
|
errs = append(errs, container.RemoveDockerJobResources(ctx, rc.jobContainerName()))
|
||||||
|
}
|
||||||
|
if rc.JobContainer != nil {
|
||||||
name := rc.jobContainerName()
|
name := rc.jobContainerName()
|
||||||
errs = append(errs,
|
errs = append(errs,
|
||||||
container.NewDockerVolumeRemoveExecutor(name, false)(ctx),
|
container.NewDockerVolumeRemoveExecutor(name, false)(ctx),
|
||||||
container.NewDockerVolumeRemoveExecutor(name+"-env", false)(ctx))
|
container.NewDockerVolumeRemoveExecutor(name+"-env", false)(ctx))
|
||||||
}
|
}
|
||||||
if createAndDeleteNetwork {
|
if createAndDeleteNetwork {
|
||||||
// last, once every container has detached
|
|
||||||
logger.Infof("Cleaning up network for job %s, and network name is: %s", rc.JobName, networkName)
|
logger.Infof("Cleaning up network for job %s, and network name is: %s", rc.JobName, networkName)
|
||||||
if err := container.NewDockerNetworkRemoveExecutor(networkName)(ctx); err != nil {
|
errs = append(errs, container.NewDockerNetworkRemoveExecutor(networkName)(ctx))
|
||||||
logger.Errorf("Error while cleaning network: %v", err)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return errors.Join(errs...)
|
return errors.Join(errs...)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (rc *RunContext) closeDockerProxy(ctx context.Context) error {
|
||||||
|
if rc.dockerProxy == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
err := rc.dockerProxy.Close(ctx)
|
||||||
|
rc.dockerProxy = nil
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("close docker proxy: %w", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
func (rc *RunContext) ApplyExtraPath(ctx context.Context, env *map[string]string) {
|
func (rc *RunContext) ApplyExtraPath(ctx context.Context, env *map[string]string) {
|
||||||
if len(rc.ExtraPath) > 0 {
|
if len(rc.ExtraPath) > 0 {
|
||||||
path := rc.JobContainer.GetPathVariableName()
|
path := rc.JobContainer.GetPathVariableName()
|
||||||
@@ -696,7 +752,6 @@ func (rc *RunContext) UpdateExtraPath(ctx context.Context, githubEnvPath string)
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// stopJobContainer removes the job container (if it exists) and its volume (if it exists)
|
|
||||||
func (rc *RunContext) stopJobContainer() common.Executor {
|
func (rc *RunContext) stopJobContainer() common.Executor {
|
||||||
return func(ctx context.Context) error {
|
return func(ctx context.Context) error {
|
||||||
if rc.cleanUpJobContainer != nil {
|
if rc.cleanUpJobContainer != nil {
|
||||||
@@ -733,10 +788,17 @@ func (rc *RunContext) startServiceContainers() common.Executor {
|
|||||||
func (rc *RunContext) stopServiceContainers() common.Executor {
|
func (rc *RunContext) stopServiceContainers() common.Executor {
|
||||||
return func(ctx context.Context) error {
|
return func(ctx context.Context) error {
|
||||||
execs := []common.Executor{}
|
execs := []common.Executor{}
|
||||||
for _, svc := range rc.serviceContainers {
|
errs := make([]error, len(rc.serviceContainers))
|
||||||
execs = append(execs, svc.container.Remove().Finally(svc.container.Close()))
|
for index, svc := range rc.serviceContainers {
|
||||||
|
execs = append(execs, func(ctx context.Context) error {
|
||||||
|
if err := errors.Join(svc.container.Remove()(ctx), svc.container.Close()(ctx)); err != nil {
|
||||||
|
errs[index] = fmt.Errorf("clean service %s: %w", svc.name, err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
}
|
}
|
||||||
return common.NewParallelExecutor(len(execs), execs...)(ctx)
|
errs = append(errs, common.NewParallelExecutor(len(execs), execs...)(ctx))
|
||||||
|
return errors.Join(errs...)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -882,6 +944,9 @@ func (rc *RunContext) captureJobContainerInfo() common.Executor {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
rc.jobContainerID = info.ID
|
rc.jobContainerID = info.ID
|
||||||
|
if source := info.Mounts[rc.githubWorkspace()]; source != "" {
|
||||||
|
rc.Env["GITEA_DOCKER_WORKSPACE"] = source
|
||||||
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -928,7 +993,7 @@ func (rc *RunContext) interpolateOutputs() common.Executor {
|
|||||||
outputs := make(map[string]string, len(rc.outputTemplate))
|
outputs := make(map[string]string, len(rc.outputTemplate))
|
||||||
var err error
|
var err error
|
||||||
for k, v := range rc.outputTemplate {
|
for k, v := range rc.outputTemplate {
|
||||||
if outputs[k], err = ee.interpolate(ctx, v); err != nil {
|
if outputs[k], err = ee.Interpolate(ctx, v); err != nil {
|
||||||
err = fmt.Errorf("failed to evaluate job output %q: %w", k, err)
|
err = fmt.Errorf("failed to evaluate job output %q: %w", k, err)
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
@@ -948,7 +1013,7 @@ func (rc *RunContext) interpolateOutputs() common.Executor {
|
|||||||
func (rc *RunContext) startContainer() common.Executor {
|
func (rc *RunContext) startContainer() common.Executor {
|
||||||
return func(ctx context.Context) error {
|
return func(ctx context.Context) error {
|
||||||
var err error
|
var err error
|
||||||
if rc.IsHostEnv(ctx) {
|
if rc.IsHostEnv() {
|
||||||
err = rc.startHostEnvironment()(ctx)
|
err = rc.startHostEnvironment()(ctx)
|
||||||
} else {
|
} else {
|
||||||
err = rc.startJobContainer()(ctx)
|
err = rc.startJobContainer()(ctx)
|
||||||
@@ -963,25 +1028,19 @@ func (rc *RunContext) startContainer() common.Executor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (rc *RunContext) cleanupFailedStart(ctx context.Context) {
|
func (rc *RunContext) cleanupFailedStart(ctx context.Context) {
|
||||||
if rc.cleanUpJobContainer == nil {
|
cleanCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), time.Minute)
|
||||||
return
|
defer cancel()
|
||||||
|
cleanup := rc.cleanUpJobContainer
|
||||||
|
if cleanup == nil {
|
||||||
|
cleanup = rc.closeDockerProxy
|
||||||
}
|
}
|
||||||
cleanCtx := ctx
|
if err := cleanup(cleanCtx); err != nil {
|
||||||
if ctx.Err() != nil {
|
|
||||||
// the start likely failed because ctx was cancelled, detach so teardown still runs
|
|
||||||
var cancel context.CancelFunc
|
|
||||||
cleanCtx, cancel = context.WithTimeout(common.WithLogger(context.Background(), common.Logger(ctx)), time.Minute)
|
|
||||||
defer cancel()
|
|
||||||
}
|
|
||||||
if err := rc.cleanUpJobContainer(cleanCtx); err != nil {
|
|
||||||
common.Logger(ctx).Errorf("Error while cleaning up after failed container start for job %s: %v", rc.JobName, err)
|
common.Logger(ctx).Errorf("Error while cleaning up after failed container start for job %s: %v", rc.JobName, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (rc *RunContext) IsHostEnv(ctx context.Context) bool {
|
func (rc *RunContext) IsHostEnv() bool {
|
||||||
platform := rc.runsOnImage(ctx)
|
return strings.EqualFold(rc.platformImage, "-self-hosted")
|
||||||
image := rc.containerImage(ctx)
|
|
||||||
return image == "" && strings.EqualFold(platform, "-self-hosted")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (rc *RunContext) stopContainer() common.Executor {
|
func (rc *RunContext) stopContainer() common.Executor {
|
||||||
@@ -1066,32 +1125,35 @@ func (rc *RunContext) Executor() (common.Executor, error) {
|
|||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (rc *RunContext) containerImage(ctx context.Context) string {
|
func (rc *RunContext) containerImage(ctx context.Context) (string, error) {
|
||||||
job := rc.Run.Job()
|
c := rc.Run.Job().Container()
|
||||||
|
if c == nil {
|
||||||
c := job.Container()
|
return "", nil
|
||||||
if c != nil {
|
|
||||||
return rc.ExprEval.Interpolate(ctx, c.Image)
|
|
||||||
}
|
}
|
||||||
|
image, err := rc.ExprEval.Interpolate(ctx, c.Image)
|
||||||
return ""
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("unable to interpolate container.image: %w", err)
|
||||||
|
}
|
||||||
|
return image, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (rc *RunContext) runsOnImage(ctx context.Context) string {
|
func (rc *RunContext) runsOnImage(ctx context.Context) (string, error) {
|
||||||
if rc.Run.Job().RunsOn() == nil {
|
if rc.Run.Job().RunsOn() == nil {
|
||||||
common.Logger(ctx).Errorf("'runs-on' key not defined in %s", rc.String())
|
common.Logger(ctx).Errorf("'runs-on' key not defined in %s", rc.String())
|
||||||
}
|
}
|
||||||
|
|
||||||
job := rc.Run.Job()
|
runsOn := rc.Run.Job().RunsOn()
|
||||||
runsOn := job.RunsOn()
|
|
||||||
for i, v := range runsOn {
|
for i, v := range runsOn {
|
||||||
runsOn[i] = rc.ExprEval.Interpolate(ctx, v)
|
var err error
|
||||||
|
if runsOn[i], err = rc.ExprEval.Interpolate(ctx, v); err != nil {
|
||||||
|
return "", fmt.Errorf("unable to interpolate runs-on: %w", err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if rc.Config.PlatformPicker != nil {
|
if rc.Config.PlatformPicker != nil {
|
||||||
return rc.Config.PlatformPicker(runsOn)
|
return rc.Config.PlatformPicker(runsOn), nil
|
||||||
}
|
}
|
||||||
return ""
|
return "", nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (rc *RunContext) runsOnPlatformNames(ctx context.Context) []string {
|
func (rc *RunContext) runsOnPlatformNames(ctx context.Context) []string {
|
||||||
@@ -1112,21 +1174,26 @@ func (rc *RunContext) runsOnPlatformNames(ctx context.Context) []string {
|
|||||||
return model.RunsOnFromNode(rawRunsOn)
|
return model.RunsOnFromNode(rawRunsOn)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (rc *RunContext) platformImage(ctx context.Context) string {
|
// resolvePlatformImage evaluates the job's image once, so every consumer sees the image the job started with.
|
||||||
if containerImage := rc.containerImage(ctx); containerImage != "" {
|
func (rc *RunContext) resolvePlatformImage(ctx context.Context) error {
|
||||||
return containerImage
|
image, err := rc.containerImage(ctx)
|
||||||
|
if err == nil && image == "" {
|
||||||
|
image, err = rc.runsOnImage(ctx)
|
||||||
}
|
}
|
||||||
|
rc.platformImage = image
|
||||||
return rc.runsOnImage(ctx)
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (rc *RunContext) workflowOptions(ctx context.Context) string {
|
func (rc *RunContext) workflowOptions(ctx context.Context) (string, error) {
|
||||||
c := rc.Run.Job().Container()
|
c := rc.Run.Job().Container()
|
||||||
if c == nil {
|
if c == nil {
|
||||||
return ""
|
return "", nil
|
||||||
}
|
}
|
||||||
|
options, err := rc.ExprEval.Interpolate(ctx, c.Options)
|
||||||
return rc.ExprEval.Interpolate(ctx, c.Options)
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("unable to interpolate container.options: %w", err)
|
||||||
|
}
|
||||||
|
return options, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (rc *RunContext) isEnabled(ctx context.Context) (bool, error) {
|
func (rc *RunContext) isEnabled(ctx context.Context) (bool, error) {
|
||||||
@@ -1156,8 +1223,10 @@ func (rc *RunContext) isEnabled(ctx context.Context) (bool, error) {
|
|||||||
return true, nil
|
return true, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
img := rc.platformImage(ctx)
|
if err := rc.resolvePlatformImage(ctx); err != nil {
|
||||||
if img == "" {
|
return false, err
|
||||||
|
}
|
||||||
|
if rc.platformImage == "" {
|
||||||
for _, platformName := range rc.runsOnPlatformNames(ctx) {
|
for _, platformName := range rc.runsOnPlatformNames(ctx) {
|
||||||
l.Infof("Skipping unsupported platform -- Try running with `-P %+v=...`", platformName)
|
l.Infof("Skipping unsupported platform -- Try running with `-P %+v=...`", platformName)
|
||||||
}
|
}
|
||||||
@@ -1544,7 +1613,7 @@ func (rc *RunContext) imageOS(ctx context.Context) string {
|
|||||||
// log that runs-on is missing.
|
// log that runs-on is missing.
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
if imageOS := imageOSFromImage(rc.platformImage(ctx)); imageOS != "" {
|
if imageOS := imageOSFromImage(rc.platformImage); imageOS != "" {
|
||||||
return imageOS
|
return imageOS
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1606,14 +1675,23 @@ func (rc *RunContext) interpolateCredentials(ctx context.Context, credentials ma
|
|||||||
}
|
}
|
||||||
|
|
||||||
ee := rc.NewExpressionEvaluator(ctx)
|
ee := rc.NewExpressionEvaluator(ctx)
|
||||||
username := ee.Interpolate(ctx, credentials["username"])
|
interpolate := func(key string) (string, error) {
|
||||||
if username == "" {
|
value, err := ee.Interpolate(ctx, credentials[key])
|
||||||
return "", "", errors.New("failed to interpolate " + prefix + "credentials.username")
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("failed to interpolate %scredentials.%s: %w", prefix, key, err)
|
||||||
|
}
|
||||||
|
if value == "" {
|
||||||
|
return "", fmt.Errorf("failed to interpolate %scredentials.%s", prefix, key)
|
||||||
|
}
|
||||||
|
return value, nil
|
||||||
}
|
}
|
||||||
password := ee.Interpolate(ctx, credentials["password"])
|
username, err := interpolate("username")
|
||||||
if password == "" {
|
if err != nil {
|
||||||
return "", "", errors.New("failed to interpolate " + prefix + "credentials.password")
|
return "", "", err
|
||||||
|
}
|
||||||
|
password, err := interpolate("password")
|
||||||
|
if err != nil {
|
||||||
|
return "", "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
return username, password, nil
|
return username, password, nil
|
||||||
}
|
}
|
||||||
@@ -10,6 +10,8 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
"os"
|
"os"
|
||||||
"runtime"
|
"runtime"
|
||||||
"strings"
|
"strings"
|
||||||
@@ -221,8 +223,9 @@ func (fakeContainer) Start(bool) common.Executor { return func(context.Context)
|
|||||||
|
|
||||||
func (fakeContainer) Remove() common.Executor { return func(context.Context) error { return nil } }
|
func (fakeContainer) Remove() common.Executor { return func(context.Context) error { return nil } }
|
||||||
|
|
||||||
func (fakeContainer) Close() common.Executor { return func(context.Context) error { return nil } }
|
func (fakeContainer) Close() common.Executor { return func(context.Context) error { return nil } }
|
||||||
func (fakeContainer) GetActPath() string { return "/var/run/act" }
|
func (fakeContainer) GetActPath() string { return "/var/run/act" }
|
||||||
|
func (fakeContainer) ToContainerPath(path string) string { return path }
|
||||||
func (fakeContainer) Create([]string, []string) common.Executor {
|
func (fakeContainer) Create([]string, []string) common.Executor {
|
||||||
return func(context.Context) error { return nil }
|
return func(context.Context) error { return nil }
|
||||||
}
|
}
|
||||||
@@ -267,10 +270,28 @@ func startJobContainerInputs(t *testing.T, workflowYAML string, cfg *Config) []*
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
rc.ExprEval = rc.NewExpressionEvaluator(t.Context())
|
rc.ExprEval = rc.NewExpressionEvaluator(t.Context())
|
||||||
|
require.NoError(t, rc.resolvePlatformImage(t.Context()))
|
||||||
|
|
||||||
// the inputs are built before the missing daemon fails the first call
|
daemon := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
t.Setenv("DOCKER_HOST", "unix:///nonexistent.sock")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
require.Error(t, rc.startJobContainer()(t.Context()))
|
switch {
|
||||||
|
case strings.HasSuffix(r.URL.Path, "/_ping"):
|
||||||
|
w.Header().Set("API-Version", "1.47")
|
||||||
|
_, _ = io.WriteString(w, "OK")
|
||||||
|
case strings.HasSuffix(r.URL.Path, "/containers/json"), strings.HasSuffix(r.URL.Path, "/networks"):
|
||||||
|
_, _ = io.WriteString(w, "[]")
|
||||||
|
case strings.HasSuffix(r.URL.Path, "/volumes"):
|
||||||
|
_, _ = io.WriteString(w, `{"Volumes":[]}`)
|
||||||
|
case strings.HasSuffix(r.URL.Path, "/info"):
|
||||||
|
_, _ = io.WriteString(w, `{"Architecture":"amd64","OSType":"linux"}`)
|
||||||
|
default:
|
||||||
|
t.Errorf("unexpected Docker request: %s %s", r.Method, r.URL)
|
||||||
|
http.NotFound(w, r)
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
t.Cleanup(daemon.Close)
|
||||||
|
t.Setenv("DOCKER_HOST", daemon.URL)
|
||||||
|
require.NoError(t, rc.startJobContainer()(t.Context()))
|
||||||
|
|
||||||
return inputs
|
return inputs
|
||||||
}
|
}
|
||||||
@@ -451,7 +472,8 @@ func TestRunContext_GetBindsAndMounts(t *testing.T) {
|
|||||||
config := testcase.rc.Config
|
config := testcase.rc.Config
|
||||||
config.Workdir = testcase.name
|
config.Workdir = testcase.name
|
||||||
config.BindWorkdir = bindWorkDir
|
config.BindWorkdir = bindWorkDir
|
||||||
gotbind, gotmount := rctemplate.GetBindsAndMounts()
|
gotbind, gotmount, err := rctemplate.GetBindsAndMounts()
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
// Name binds/mounts are either/or
|
// Name binds/mounts are either/or
|
||||||
if config.BindWorkdir {
|
if config.BindWorkdir {
|
||||||
@@ -510,7 +532,8 @@ func TestRunContext_GetBindsAndMounts(t *testing.T) {
|
|||||||
rc.Run.Workflow.Jobs = map[string]*model.Job{"job1": job}
|
rc.Run.Workflow.Jobs = map[string]*model.Job{"job1": job}
|
||||||
rc.ExprEval = rc.NewExpressionEvaluator(context.Background())
|
rc.ExprEval = rc.NewExpressionEvaluator(context.Background())
|
||||||
|
|
||||||
gotbind, gotmount := rc.GetBindsAndMounts()
|
gotbind, gotmount, err := rc.GetBindsAndMounts()
|
||||||
|
require.NoError(t, err)
|
||||||
assert.Contains(t, gotbind, "/host/mame/roms:/root/.mame/roms:ro")
|
assert.Contains(t, gotbind, "/host/mame/roms:/root/.mame/roms:ro")
|
||||||
assert.NotContains(t, gotbind, "${{ secrets.MAME }}")
|
assert.NotContains(t, gotbind, "${{ secrets.MAME }}")
|
||||||
assert.NotContains(t, gotmount, "${{ secrets.MAME }}")
|
assert.NotContains(t, gotmount, "${{ secrets.MAME }}")
|
||||||
@@ -539,7 +562,8 @@ func TestRunContext_GetBindsAndMounts(t *testing.T) {
|
|||||||
rc.Run.JobID = "job1"
|
rc.Run.JobID = "job1"
|
||||||
rc.Run.Workflow.Jobs = map[string]*model.Job{"job1": job}
|
rc.Run.Workflow.Jobs = map[string]*model.Job{"job1": job}
|
||||||
|
|
||||||
gotbind, gotmount := rc.GetBindsAndMounts()
|
gotbind, gotmount, err := rc.GetBindsAndMounts()
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
if len(testcase.wantbind) > 0 {
|
if len(testcase.wantbind) > 0 {
|
||||||
assert.Contains(t, gotbind, testcase.wantbind)
|
assert.Contains(t, gotbind, testcase.wantbind)
|
||||||
@@ -574,11 +598,13 @@ func TestRunContext_GetBindsAndMounts(t *testing.T) {
|
|||||||
Config: &Config{},
|
Config: &Config{},
|
||||||
}
|
}
|
||||||
|
|
||||||
_, gotmount := rc.GetBindsAndMounts()
|
_, gotmount, err := rc.GetBindsAndMounts()
|
||||||
|
require.NoError(t, err)
|
||||||
assert.NotContains(t, gotmount, sharedToolCacheVolume)
|
assert.NotContains(t, gotmount, sharedToolCacheVolume)
|
||||||
|
|
||||||
rc.Config.SharedToolCache = true
|
rc.Config.SharedToolCache = true
|
||||||
_, gotmount = rc.GetBindsAndMounts()
|
_, gotmount, err = rc.GetBindsAndMounts()
|
||||||
|
require.NoError(t, err)
|
||||||
assert.Equal(t, container.DefaultToolCache, gotmount[sharedToolCacheVolume])
|
assert.Equal(t, container.DefaultToolCache, gotmount[sharedToolCacheVolume])
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -604,6 +630,11 @@ func TestRunContextValidVolumes(t *testing.T) {
|
|||||||
// a job may mount it only while the runner does
|
// a job may mount it only while the runner does
|
||||||
rc.Config.SharedToolCache = false
|
rc.Config.SharedToolCache = false
|
||||||
assert.NotContains(t, rc.validVolumes(), sharedToolCacheVolume)
|
assert.NotContains(t, rc.validVolumes(), sharedToolCacheVolume)
|
||||||
|
|
||||||
|
rc.Config.Workdir = "/workspace/1/owner/repo"
|
||||||
|
assert.NotContains(t, rc.validVolumes(), rc.Config.Workdir)
|
||||||
|
rc.Config.BindWorkdir = true
|
||||||
|
assert.Contains(t, rc.validVolumes(), rc.Config.Workdir)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCleanupJobResourcesCleansServicesWithoutJobContainer(t *testing.T) {
|
func TestCleanupJobResourcesCleansServicesWithoutJobContainer(t *testing.T) {
|
||||||
@@ -616,7 +647,7 @@ func TestCleanupJobResourcesCleansServicesWithoutJobContainer(t *testing.T) {
|
|||||||
serviceContainers: []*serviceContainer{{name: "svc", container: service}},
|
serviceContainers: []*serviceContainer{{name: "svc", container: service}},
|
||||||
}
|
}
|
||||||
|
|
||||||
err := rc.cleanupJobResources("external-network", false)(context.Background())
|
err := rc.cleanupJobResources("external-network", false)(common.WithDryrun(t.Context(), true))
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
service.AssertExpectations(t)
|
service.AssertExpectations(t)
|
||||||
}
|
}
|
||||||
@@ -625,11 +656,12 @@ func TestCleanupJobResourcesCleansServicesWithoutJobContainer(t *testing.T) {
|
|||||||
func TestCleanupJobResourcesContinuesAfterFailure(t *testing.T) {
|
func TestCleanupJobResourcesContinuesAfterFailure(t *testing.T) {
|
||||||
t.Setenv("DOCKER_HOST", "unix:///nonexistent.sock")
|
t.Setenv("DOCKER_HOST", "unix:///nonexistent.sock")
|
||||||
|
|
||||||
|
removeError, closeError := errors.New("remove service"), errors.New("close service")
|
||||||
jobContainer := &containerMock{}
|
jobContainer := &containerMock{}
|
||||||
jobContainer.On("Remove").Return(func(context.Context) error { return errors.New("removal failed") }).Once()
|
jobContainer.On("Remove").Return(func(context.Context) error { return errors.New("removal failed") }).Once()
|
||||||
service := &containerMock{}
|
service := &containerMock{}
|
||||||
service.On("Remove").Return(func(context.Context) error { return nil }).Once()
|
service.On("Remove").Return(func(context.Context) error { return removeError }).Once()
|
||||||
service.On("Close").Return(func(context.Context) error { return nil }).Once()
|
service.On("Close").Return(func(context.Context) error { return closeError }).Once()
|
||||||
|
|
||||||
rc := &RunContext{
|
rc := &RunContext{
|
||||||
Name: "job",
|
Name: "job",
|
||||||
@@ -641,7 +673,11 @@ func TestCleanupJobResourcesContinuesAfterFailure(t *testing.T) {
|
|||||||
|
|
||||||
ctx, cancel := context.WithCancel(context.Background())
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
cancel()
|
cancel()
|
||||||
require.Error(t, rc.cleanupJobResources("job-network", true)(ctx))
|
err := rc.cleanupJobResources("job-network", true)(ctx)
|
||||||
|
require.ErrorContains(t, err, "removal failed")
|
||||||
|
require.ErrorIs(t, err, removeError)
|
||||||
|
require.ErrorIs(t, err, closeError)
|
||||||
|
require.ErrorIs(t, err, context.Canceled)
|
||||||
jobContainer.AssertExpectations(t)
|
jobContainer.AssertExpectations(t)
|
||||||
service.AssertExpectations(t)
|
service.AssertExpectations(t)
|
||||||
}
|
}
|
||||||
@@ -655,8 +691,10 @@ func TestInterpolateOutputsIsPerMatrixCombo(t *testing.T) {
|
|||||||
r := &runnerImpl{config: &Config{}}
|
r := &runnerImpl{config: &Config{}}
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
|
|
||||||
rcA := r.newRunContext(ctx, run, map[string]any{"v": "a"})
|
rcA, err := r.newRunContext(ctx, run, map[string]any{"v": "a"})
|
||||||
rcB := r.newRunContext(ctx, run, map[string]any{"v": "b"})
|
require.NoError(t, err)
|
||||||
|
rcB, err := r.newRunContext(ctx, run, map[string]any{"v": "b"})
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
require.NoError(t, rcA.interpolateOutputs()(ctx))
|
require.NoError(t, rcA.interpolateOutputs()(ctx))
|
||||||
require.NoError(t, rcB.interpolateOutputs()(ctx))
|
require.NoError(t, rcB.interpolateOutputs()(ctx))
|
||||||
@@ -1056,12 +1094,19 @@ func TestRunContext_cleanupFailedStart(t *testing.T) {
|
|||||||
calls int
|
calls int
|
||||||
err error
|
err error
|
||||||
sentinel any
|
sentinel any
|
||||||
|
cancel context.CancelFunc
|
||||||
}
|
}
|
||||||
newRC := func(c *capture) *RunContext {
|
newRC := func(c *capture) *RunContext {
|
||||||
return &RunContext{
|
return &RunContext{
|
||||||
JobName: "job",
|
JobName: "job",
|
||||||
cleanUpJobContainer: func(ctx context.Context) error {
|
cleanUpJobContainer: func(ctx context.Context) error {
|
||||||
c.calls++
|
c.calls++
|
||||||
|
if c.cancel != nil {
|
||||||
|
c.cancel()
|
||||||
|
}
|
||||||
|
deadline, ok := ctx.Deadline()
|
||||||
|
require.True(t, ok)
|
||||||
|
assert.WithinDuration(t, time.Now().Add(time.Minute), deadline, time.Second)
|
||||||
c.err = ctx.Err()
|
c.err = ctx.Err()
|
||||||
c.sentinel = ctx.Value(sentinel)
|
c.sentinel = ctx.Value(sentinel)
|
||||||
return nil
|
return nil
|
||||||
@@ -1069,9 +1114,10 @@ func TestRunContext_cleanupFailedStart(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
t.Run("runs teardown on the live context", func(t *testing.T) {
|
t.Run("detaches teardown from cancellation during cleanup", func(t *testing.T) {
|
||||||
var c capture
|
ctx, cancel := context.WithCancel(context.WithValue(context.Background(), sentinel, "v"))
|
||||||
ctx := context.WithValue(context.Background(), sentinel, "v")
|
defer cancel()
|
||||||
|
c := capture{cancel: cancel}
|
||||||
|
|
||||||
newRC(&c).cleanupFailedStart(ctx)
|
newRC(&c).cleanupFailedStart(ctx)
|
||||||
|
|
||||||
@@ -1089,7 +1135,7 @@ func TestRunContext_cleanupFailedStart(t *testing.T) {
|
|||||||
|
|
||||||
assert.Equal(t, 1, c.calls)
|
assert.Equal(t, 1, c.calls)
|
||||||
require.NoError(t, c.err)
|
require.NoError(t, c.err)
|
||||||
assert.Nil(t, c.sentinel)
|
assert.Equal(t, "v", c.sentinel)
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("no-op when there is nothing to clean up", func(t *testing.T) {
|
t.Run("no-op when there is nothing to clean up", func(t *testing.T) {
|
||||||
@@ -1281,6 +1327,29 @@ func TestGetJobContextReportsContainers(t *testing.T) {
|
|||||||
}, jobContext.Services)
|
}, jobContext.Services)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestCaptureJobContainerInfoExportsDockerWorkspace(t *testing.T) {
|
||||||
|
job := &containerMock{}
|
||||||
|
job.On("Inspect", mock.Anything).Return(&container.Info{
|
||||||
|
ID: "job-container-id",
|
||||||
|
Mounts: map[string]string{"/workspace/owner/repo": "/var/lib/docker/volumes/job/_data"},
|
||||||
|
}, nil)
|
||||||
|
rc := &RunContext{
|
||||||
|
Config: &Config{Workdir: "/workspace/owner/repo/"},
|
||||||
|
Env: map[string]string{},
|
||||||
|
JobContainer: job,
|
||||||
|
}
|
||||||
|
|
||||||
|
require.NoError(t, rc.captureJobContainerInfo()(context.Background()))
|
||||||
|
|
||||||
|
assert.Equal(t, "job-container-id", rc.jobContainerID)
|
||||||
|
assert.Equal(t, "/var/lib/docker/volumes/job/_data", rc.Env["GITEA_DOCKER_WORKSPACE"])
|
||||||
|
|
||||||
|
rc.Config.Workdir = "/elsewhere"
|
||||||
|
rc.Env = map[string]string{}
|
||||||
|
require.NoError(t, rc.captureJobContainerInfo()(context.Background()))
|
||||||
|
assert.NotContains(t, rc.Env, "GITEA_DOCKER_WORKSPACE")
|
||||||
|
}
|
||||||
|
|
||||||
// A job that never started a container reports an empty context, not a placeholder.
|
// A job that never started a container reports an empty context, not a placeholder.
|
||||||
func TestGetJobContextWithoutContainer(t *testing.T) {
|
func TestGetJobContextWithoutContainer(t *testing.T) {
|
||||||
jobContext := (&RunContext{}).getJobContext()
|
jobContext := (&RunContext{}).getJobContext()
|
||||||
@@ -1329,12 +1398,14 @@ func TestRunContextImageOS(t *testing.T) {
|
|||||||
t.Run("prefers the release in the resolved image tag", func(t *testing.T) {
|
t.Run("prefers the release in the resolved image tag", func(t *testing.T) {
|
||||||
rc := createRunsOnRunContext(t, "ubuntu-latest")
|
rc := createRunsOnRunContext(t, "ubuntu-latest")
|
||||||
rc.Config.PlatformPicker = func([]string) string { return "docker.gitea.com/runner-images:ubuntu-24.04" }
|
rc.Config.PlatformPicker = func([]string) string { return "docker.gitea.com/runner-images:ubuntu-24.04" }
|
||||||
|
require.NoError(t, rc.resolvePlatformImage(ctx))
|
||||||
assert.Equal(t, "ubuntu24", rc.imageOS(ctx))
|
assert.Equal(t, "ubuntu24", rc.imageOS(ctx))
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("falls back to the runs-on label", func(t *testing.T) {
|
t.Run("falls back to the runs-on label", func(t *testing.T) {
|
||||||
rc := createRunsOnRunContext(t, "ubuntu-22.04")
|
rc := createRunsOnRunContext(t, "ubuntu-22.04")
|
||||||
rc.Config.PlatformPicker = func([]string) string { return "some-image" }
|
rc.Config.PlatformPicker = func([]string) string { return "some-image" }
|
||||||
|
require.NoError(t, rc.resolvePlatformImage(ctx))
|
||||||
assert.Equal(t, "ubuntu22", rc.imageOS(ctx))
|
assert.Equal(t, "ubuntu22", rc.imageOS(ctx))
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
+14
-5
@@ -198,7 +198,10 @@ func (runner *runnerImpl) NewPlanExecutor(plan *model.Plan) common.Executor {
|
|||||||
log.Debugf("Job.Strategy.MaxParallelString: %v", job.Strategy.MaxParallelString)
|
log.Debugf("Job.Strategy.MaxParallelString: %v", job.Strategy.MaxParallelString)
|
||||||
log.Debugf("Job.Strategy.RawMatrix: %v", job.Strategy.RawMatrix)
|
log.Debugf("Job.Strategy.RawMatrix: %v", job.Strategy.RawMatrix)
|
||||||
|
|
||||||
strategyRc := runner.newRunContext(ctx, run, nil)
|
strategyRc, err := runner.newRunContext(ctx, run, nil)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
// Resolve template expressions in the matrix node before Matrix() is called.
|
// Resolve template expressions in the matrix node before Matrix() is called.
|
||||||
// On failure the literal string is kept and normalizeMatrixValue wraps it as a fallback.
|
// On failure the literal string is kept and normalizeMatrixValue wraps it as a fallback.
|
||||||
if err := strategyRc.NewExpressionEvaluator(ctx).EvaluateYamlNode(ctx, &job.Strategy.RawMatrix); err != nil {
|
if err := strategyRc.NewExpressionEvaluator(ctx).EvaluateYamlNode(ctx, &job.Strategy.RawMatrix); err != nil {
|
||||||
@@ -230,7 +233,10 @@ func (runner *runnerImpl) NewPlanExecutor(plan *model.Plan) common.Executor {
|
|||||||
log.Infof("Running job with maxParallel=%d for %d matrix combinations", maxParallel, len(matrixes))
|
log.Infof("Running job with maxParallel=%d for %d matrix combinations", maxParallel, len(matrixes))
|
||||||
|
|
||||||
for i, matrix := range matrixes {
|
for i, matrix := range matrixes {
|
||||||
rc := runner.newRunContext(ctx, run, matrix)
|
rc, err := runner.newRunContext(ctx, run, matrix)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
rc.JobName = rc.Name
|
rc.JobName = rc.Name
|
||||||
if len(matrixes) > 1 {
|
if len(matrixes) > 1 {
|
||||||
rc.Name = fmt.Sprintf("%s-%d", rc.Name, i+1)
|
rc.Name = fmt.Sprintf("%s-%d", rc.Name, i+1)
|
||||||
@@ -315,7 +321,7 @@ func handleFailure(plan *model.Plan) common.Executor {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (runner *runnerImpl) newRunContext(ctx context.Context, run *model.Run, matrix map[string]any) *RunContext {
|
func (runner *runnerImpl) newRunContext(ctx context.Context, run *model.Run, matrix map[string]any) (*RunContext, error) {
|
||||||
rc := &RunContext{
|
rc := &RunContext{
|
||||||
Config: runner.config,
|
Config: runner.config,
|
||||||
Run: run,
|
Run: run,
|
||||||
@@ -324,15 +330,18 @@ func (runner *runnerImpl) newRunContext(ctx context.Context, run *model.Run, mat
|
|||||||
Matrix: matrix,
|
Matrix: matrix,
|
||||||
caller: runner.caller,
|
caller: runner.caller,
|
||||||
}
|
}
|
||||||
|
if err := rc.resolveWorkflowCall(ctx); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
rc.ExprEval = rc.NewExpressionEvaluator(ctx)
|
rc.ExprEval = rc.NewExpressionEvaluator(ctx)
|
||||||
rc.Name = rc.maskSecrets(rc.ExprEval.Interpolate(ctx, run.String()))
|
rc.Name = rc.maskSecrets(rc.ExprEval.InterpolateName(ctx, run.String()))
|
||||||
// Snapshot the job's pristine output expressions now, before any matrix combo runs and
|
// Snapshot the job's pristine output expressions now, before any matrix combo runs and
|
||||||
// rewrites the shared Job.Outputs (see interpolateOutputs).
|
// rewrites the shared Job.Outputs (see interpolateOutputs).
|
||||||
if job := run.Job(); job != nil {
|
if job := run.Job(); job != nil {
|
||||||
rc.outputTemplate = maps.Clone(job.Outputs)
|
rc.outputTemplate = maps.Clone(job.Outputs)
|
||||||
}
|
}
|
||||||
|
|
||||||
return rc
|
return rc, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// For Gitea
|
// For Gitea
|
||||||
|
|||||||
+21
-10
@@ -11,6 +11,7 @@ import (
|
|||||||
"path"
|
"path"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"gitea.com/gitea/runner/act/common"
|
"gitea.com/gitea/runner/act/common"
|
||||||
@@ -82,9 +83,11 @@ func runStepExecutor(step step, stage stepStage, executor common.Executor) commo
|
|||||||
rc.StepResults[rc.CurrentStep] = stepResult
|
rc.StepResults[rc.CurrentStep] = stepResult
|
||||||
}
|
}
|
||||||
|
|
||||||
setupEnv(ctx, step)
|
err := setupEnv(ctx, step)
|
||||||
|
var runStep bool
|
||||||
runStep, err := isStepEnabled(ctx, ifExpression, step, stage)
|
if err == nil {
|
||||||
|
runStep, err = isStepEnabled(ctx, ifExpression, step, stage)
|
||||||
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
stepResult.Conclusion = model.StepStatusFailure
|
stepResult.Conclusion = model.StepStatusFailure
|
||||||
stepResult.Outcome = model.StepStatusFailure
|
stepResult.Outcome = model.StepStatusFailure
|
||||||
@@ -99,7 +102,7 @@ func runStepExecutor(step step, stage stepStage, executor common.Executor) commo
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
stepString := rc.ExprEval.Interpolate(ctx, stepModel.String())
|
stepString := rc.ExprEval.InterpolateName(ctx, stepModel.String())
|
||||||
if strings.Contains(stepString, "::add-mask::") {
|
if strings.Contains(stepString, "::add-mask::") {
|
||||||
stepString = "add-mask command"
|
stepString = "add-mask command"
|
||||||
}
|
}
|
||||||
@@ -221,8 +224,10 @@ func runStepExecutor(step step, stage stepStage, executor common.Executor) commo
|
|||||||
}
|
}
|
||||||
|
|
||||||
func evaluateStepTimeout(ctx context.Context, exprEval *expressionEvaluator, stepModel *model.Step) (context.Context, context.CancelFunc) {
|
func evaluateStepTimeout(ctx context.Context, exprEval *expressionEvaluator, stepModel *model.Step) (context.Context, context.CancelFunc) {
|
||||||
timeout := exprEval.Interpolate(ctx, stepModel.TimeoutMinutes)
|
timeout, err := exprEval.Interpolate(ctx, stepModel.TimeoutMinutes)
|
||||||
if timeout != "" {
|
if err != nil {
|
||||||
|
common.Logger(ctx).Errorf("An error occurred when attempting to determine the step timeout: %s", err)
|
||||||
|
} else if timeout != "" {
|
||||||
if timeOutMinutes, err := strconv.ParseInt(timeout, 10, 64); err == nil && timeOutMinutes > 0 {
|
if timeOutMinutes, err := strconv.ParseInt(timeout, 10, 64); err == nil && timeOutMinutes > 0 {
|
||||||
return context.WithTimeout(ctx, time.Duration(timeOutMinutes)*time.Minute)
|
return context.WithTimeout(ctx, time.Duration(timeOutMinutes)*time.Minute)
|
||||||
}
|
}
|
||||||
@@ -230,27 +235,33 @@ func evaluateStepTimeout(ctx context.Context, exprEval *expressionEvaluator, ste
|
|||||||
return ctx, func() {}
|
return ctx, func() {}
|
||||||
}
|
}
|
||||||
|
|
||||||
func setupEnv(ctx context.Context, step step) {
|
func setupEnv(ctx context.Context, step step) error {
|
||||||
rc := step.getRunContext()
|
rc := step.getRunContext()
|
||||||
|
|
||||||
mergeEnv(ctx, step)
|
mergeEnv(ctx, step)
|
||||||
// merge step env last, since it should not be overwritten
|
// merge step env last, since it should not be overwritten
|
||||||
mergeIntoMap(step, step.getEnv(), step.getStepModel().GetEnv())
|
mergeIntoMap(step, step.getEnv(), step.getStepModel().GetEnv())
|
||||||
|
|
||||||
|
var err error
|
||||||
exprEval := rc.NewExpressionEvaluator(ctx)
|
exprEval := rc.NewExpressionEvaluator(ctx)
|
||||||
for k, v := range *step.getEnv() {
|
for k, v := range *step.getEnv() {
|
||||||
if !strings.HasPrefix(k, "INPUT_") {
|
if !strings.HasPrefix(k, "INPUT_") {
|
||||||
(*step.getEnv())[k] = exprEval.Interpolate(ctx, v)
|
if (*step.getEnv())[k], err = exprEval.Interpolate(ctx, v); err != nil {
|
||||||
|
return fmt.Errorf("unable to interpolate env %s: %w", k, err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// after we have an evaluated step context, update the expressions evaluator with a new env context
|
// after we have an evaluated step context, update the expressions evaluator with a new env context
|
||||||
// you can use step level env in the with property of a uses construct
|
// you can use step level env in the with property of a uses construct
|
||||||
exprEval = rc.NewExpressionEvaluatorWithEnv(ctx, *step.getEnv())
|
inputEval := sync.OnceValue(func() *expressionEvaluator { return rc.NewExpressionEvaluatorWithEnv(ctx, *step.getEnv()) })
|
||||||
for k, v := range *step.getEnv() {
|
for k, v := range *step.getEnv() {
|
||||||
if strings.HasPrefix(k, "INPUT_") {
|
if strings.HasPrefix(k, "INPUT_") {
|
||||||
(*step.getEnv())[k] = exprEval.Interpolate(ctx, v)
|
if (*step.getEnv())[k], err = inputEval().Interpolate(ctx, v); err != nil {
|
||||||
|
return fmt.Errorf("unable to interpolate env %s: %w", k, err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func mergeEnv(ctx context.Context, step step) {
|
func mergeEnv(ctx context.Context, step step) {
|
||||||
|
|||||||
@@ -122,15 +122,19 @@ func (sal *stepActionLocal) getActionModel() *model.Action {
|
|||||||
return sal.action
|
return sal.action
|
||||||
}
|
}
|
||||||
|
|
||||||
func (sal *stepActionLocal) getCompositeRunContext(ctx context.Context) *RunContext {
|
func (sal *stepActionLocal) getCompositeRunContext(ctx context.Context) (*RunContext, error) {
|
||||||
if sal.compositeRunContext == nil {
|
if sal.compositeRunContext == nil {
|
||||||
actionDir := filepath.Join(sal.RunContext.Config.Workdir, sal.Step.Uses)
|
actionDir := filepath.Join(sal.RunContext.Config.Workdir, sal.Step.Uses)
|
||||||
_, containerActionDir := getContainerActionPaths(sal.getStepModel(), actionDir, sal.RunContext)
|
_, containerActionDir := getContainerActionPaths(sal.getStepModel(), actionDir, sal.RunContext)
|
||||||
|
|
||||||
sal.compositeRunContext = newCompositeRunContext(ctx, sal.RunContext, sal, containerActionDir)
|
compositeRunContext, err := newCompositeRunContext(ctx, sal.RunContext, sal, containerActionDir)
|
||||||
sal.compositeSteps = sal.compositeRunContext.compositeExecutor(sal.action)
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
sal.compositeRunContext = compositeRunContext
|
||||||
|
sal.compositeSteps = compositeRunContext.compositeExecutor(sal.action)
|
||||||
}
|
}
|
||||||
return sal.compositeRunContext
|
return sal.compositeRunContext, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (sal *stepActionLocal) getCompositeSteps() *compositeSteps {
|
func (sal *stepActionLocal) getCompositeSteps() *compositeSteps {
|
||||||
|
|||||||
@@ -51,7 +51,11 @@ func (sar *stepActionRemote) prepareActionExecutor() common.Executor {
|
|||||||
// Since actions can specify the download source via a url prefix.
|
// Since actions can specify the download source via a url prefix.
|
||||||
// The prefix may contain some sensitive information that needs to be stored in secrets,
|
// The prefix may contain some sensitive information that needs to be stored in secrets,
|
||||||
// so we need to interpolate the expression value for uses first.
|
// so we need to interpolate the expression value for uses first.
|
||||||
sar.Step.Uses = sar.RunContext.NewExpressionEvaluator(ctx).Interpolate(ctx, sar.Step.Uses)
|
uses, err := sar.RunContext.NewExpressionEvaluator(ctx).Interpolate(ctx, sar.Step.Uses)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("unable to interpolate uses: %w", err)
|
||||||
|
}
|
||||||
|
sar.Step.Uses = uses
|
||||||
|
|
||||||
github := sar.getGithubContext(ctx) // read before remoteAction is set, so `$/` resolves against the enclosing action
|
github := sar.getGithubContext(ctx) // read before remoteAction is set, so `$/` resolves against the enclosing action
|
||||||
if strings.HasPrefix(sar.Step.Uses, selfRepoPrefix) {
|
if strings.HasPrefix(sar.Step.Uses, selfRepoPrefix) {
|
||||||
@@ -160,9 +164,12 @@ func (sar *stepActionRemote) main() common.Executor {
|
|||||||
common.Logger(ctx).Debugf("Skipping local actions/checkout because you bound your workspace")
|
common.Logger(ctx).Debugf("Skipping local actions/checkout because you bound your workspace")
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
eval := sar.RunContext.NewExpressionEvaluator(ctx)
|
checkoutPath, err := sar.RunContext.NewExpressionEvaluator(ctx).Interpolate(ctx, sar.Step.With["path"])
|
||||||
copyToPath := path.Join(sar.RunContext.JobContainer.ToContainerPath(sar.RunContext.Config.Workdir), eval.Interpolate(ctx, sar.Step.With["path"]))
|
if err != nil {
|
||||||
return sar.RunContext.JobContainer.CopyDir(copyToPath, sar.RunContext.Config.Workdir+string(filepath.Separator)+".", sar.RunContext.Config.UseGitIgnore)(ctx)
|
return fmt.Errorf("unable to interpolate with.path: %w", err)
|
||||||
|
}
|
||||||
|
copyToPath := path.Join(sar.RunContext.JobContainer.ToContainerPath(sar.RunContext.Config.Workdir), checkoutPath)
|
||||||
|
return sar.RunContext.JobContainer.CopyDir(copyToPath, sar.RunContext.Config.Workdir+string(filepath.Separator)+".", sar.RunContext.Config.UseGitIgnore, false)(ctx)
|
||||||
}
|
}
|
||||||
|
|
||||||
return sar.runAction(sar, sar.actionDir(), sar.remoteAction)(ctx)
|
return sar.runAction(sar, sar.actionDir(), sar.remoteAction)(ctx)
|
||||||
@@ -229,14 +236,18 @@ func (sar *stepActionRemote) getActionModel() *model.Action {
|
|||||||
return sar.action
|
return sar.action
|
||||||
}
|
}
|
||||||
|
|
||||||
func (sar *stepActionRemote) getCompositeRunContext(ctx context.Context) *RunContext {
|
func (sar *stepActionRemote) getCompositeRunContext(ctx context.Context) (*RunContext, error) {
|
||||||
if sar.compositeRunContext == nil {
|
if sar.compositeRunContext == nil {
|
||||||
actionDir := sar.actionDir()
|
actionDir := sar.actionDir()
|
||||||
actionLocation := path.Join(actionDir, sar.remoteAction.Path)
|
actionLocation := path.Join(actionDir, sar.remoteAction.Path)
|
||||||
_, containerActionDir := getContainerActionPaths(sar.getStepModel(), actionLocation, sar.RunContext)
|
_, containerActionDir := getContainerActionPaths(sar.getStepModel(), actionLocation, sar.RunContext)
|
||||||
|
|
||||||
sar.compositeRunContext = newCompositeRunContext(ctx, sar.RunContext, sar, containerActionDir)
|
compositeRunContext, err := newCompositeRunContext(ctx, sar.RunContext, sar, containerActionDir)
|
||||||
sar.compositeSteps = sar.compositeRunContext.compositeExecutor(sar.action)
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
sar.compositeRunContext = compositeRunContext
|
||||||
|
sar.compositeSteps = compositeRunContext.compositeExecutor(sar.action)
|
||||||
} else {
|
} else {
|
||||||
// Re-evaluate environment here. For remote actions the environment
|
// Re-evaluate environment here. For remote actions the environment
|
||||||
// need to be re-created for every stage (pre, main, post) as there
|
// need to be re-created for every stage (pre, main, post) as there
|
||||||
@@ -244,11 +255,14 @@ func (sar *stepActionRemote) getCompositeRunContext(ctx context.Context) *RunCon
|
|||||||
// stages are executed. (e.g. the output of another action is the
|
// stages are executed. (e.g. the output of another action is the
|
||||||
// input for this action during the main stage, but the env
|
// input for this action during the main stage, but the env
|
||||||
// was already created during the pre stage)
|
// was already created during the pre stage)
|
||||||
env := evaluateCompositeInputAndEnv(ctx, sar.RunContext, sar)
|
env, err := evaluateCompositeInputAndEnv(ctx, sar.RunContext, sar)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
sar.compositeRunContext.setCompositeActionEnv(env)
|
sar.compositeRunContext.setCompositeActionEnv(env)
|
||||||
sar.compositeRunContext.ExtraPath = sar.RunContext.ExtraPath
|
sar.compositeRunContext.ExtraPath = sar.RunContext.ExtraPath
|
||||||
}
|
}
|
||||||
return sar.compositeRunContext
|
return sar.compositeRunContext, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (sar *stepActionRemote) getCompositeSteps() *compositeSteps {
|
func (sar *stepActionRemote) getCompositeSteps() *compositeSteps {
|
||||||
|
|||||||
@@ -254,7 +254,8 @@ func TestStepActionRemote(t *testing.T) {
|
|||||||
|
|
||||||
for _, value := range []string{"first", "second"} {
|
for _, value := range []string{"first", "second"} {
|
||||||
step.env["INPUT_SHARED"] = value
|
step.env["INPUT_SHARED"] = value
|
||||||
composite := step.getCompositeRunContext(t.Context())
|
composite, err := step.getCompositeRunContext(t.Context())
|
||||||
|
require.NoError(t, err)
|
||||||
assert.Equal(t, map[string]any{"shared": value}, composite.actionInputs)
|
assert.Equal(t, map[string]any{"shared": value}, composite.actionInputs)
|
||||||
assert.NotContains(t, composite.Env, "INPUT_SHARED")
|
assert.NotContains(t, composite.Env, "INPUT_SHARED")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ package runner
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"fmt"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"gitea.com/gitea/runner/act/common"
|
"gitea.com/gitea/runner/act/common"
|
||||||
@@ -58,17 +59,28 @@ func (sd *stepDocker) runUsesContainer() common.Executor {
|
|||||||
return func(ctx context.Context) error {
|
return func(ctx context.Context) error {
|
||||||
image := strings.TrimPrefix(step.Uses, "docker://")
|
image := strings.TrimPrefix(step.Uses, "docker://")
|
||||||
eval := rc.NewExpressionEvaluator(ctx)
|
eval := rc.NewExpressionEvaluator(ctx)
|
||||||
cmd, err := shellquote.Split(eval.Interpolate(ctx, step.With["args"]))
|
args, err := eval.Interpolate(ctx, step.With["args"])
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("unable to interpolate with.args: %w", err)
|
||||||
|
}
|
||||||
|
cmd, err := shellquote.Split(args)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
var entrypoint []string
|
var entrypoint []string
|
||||||
if entry := eval.Interpolate(ctx, step.With["entrypoint"]); entry != "" {
|
entry, err := eval.Interpolate(ctx, step.With["entrypoint"])
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("unable to interpolate with.entrypoint: %w", err)
|
||||||
|
}
|
||||||
|
if entry != "" {
|
||||||
entrypoint = []string{entry}
|
entrypoint = []string{entry}
|
||||||
}
|
}
|
||||||
|
|
||||||
stepContainer := newStepContainer(ctx, sd, image, cmd, entrypoint, "")
|
stepContainer, err := newStepContainer(ctx, sd, image, cmd, entrypoint, "")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
return common.NewPipelineExecutor(
|
return common.NewPipelineExecutor(
|
||||||
stepContainer.Pull(rc.Config.ForcePull),
|
stepContainer.Pull(rc.Config.ForcePull),
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ import (
|
|||||||
"gitea.dev/actionslib/pkg/model"
|
"gitea.dev/actionslib/pkg/model"
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
"github.com/stretchr/testify/mock"
|
"github.com/stretchr/testify/mock"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestStepDockerMain(t *testing.T) {
|
func TestStepDockerMain(t *testing.T) {
|
||||||
@@ -144,7 +145,7 @@ func TestStepDockerNewStepContainerAllocatePTY(t *testing.T) {
|
|||||||
}
|
}
|
||||||
sd.RunContext.ExprEval = sd.RunContext.NewExpressionEvaluator(ctx)
|
sd.RunContext.ExprEval = sd.RunContext.NewExpressionEvaluator(ctx)
|
||||||
|
|
||||||
_ = newStepContainer(ctx, sd, "node:14", []string{"echo", "hi"}, nil, "")
|
_, _ = newStepContainer(ctx, sd, "node:14", []string{"echo", "hi"}, nil, "")
|
||||||
assert.Equal(t, tc.allocPTY, captured.AllocatePTY)
|
assert.Equal(t, tc.allocPTY, captured.AllocatePTY)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -210,10 +211,10 @@ func TestStepDockerNewStepContainerNetworkMode(t *testing.T) {
|
|||||||
}
|
}
|
||||||
sd.RunContext.ExprEval = sd.RunContext.NewExpressionEvaluator(ctx)
|
sd.RunContext.ExprEval = sd.RunContext.NewExpressionEvaluator(ctx)
|
||||||
|
|
||||||
assert.Equal(t, tc.expectDefault, sd.RunContext.IsHostEnv(ctx),
|
require.NoError(t, sd.RunContext.resolvePlatformImage(ctx))
|
||||||
"IsHostEnv mismatch for platform %q", tc.platform)
|
assert.Equal(t, tc.expectDefault, sd.RunContext.IsHostEnv(), "IsHostEnv mismatch for platform %q", tc.platform)
|
||||||
|
|
||||||
_ = newStepContainer(ctx, sd, "alpine:3.20", []string{"echo", "hello"}, nil, "")
|
_, _ = newStepContainer(ctx, sd, "alpine:3.20", []string{"echo", "hello"}, nil, "")
|
||||||
|
|
||||||
if tc.expectDefault {
|
if tc.expectDefault {
|
||||||
assert.Equal(t, "default", captured.NetworkMode,
|
assert.Equal(t, "default", captured.NetworkMode,
|
||||||
|
|||||||
+32
-25
@@ -254,12 +254,21 @@ func getScriptName(rc *RunContext, step *model.Step) string {
|
|||||||
// OCI runtime exec failed: exec failed: container_linux.go:380: starting container process caused: exec: "${{": executable file not found in $PATH: unknown
|
// OCI runtime exec failed: exec failed: container_linux.go:380: starting container process caused: exec: "${{": executable file not found in $PATH: unknown
|
||||||
func (sr *stepRun) setupShellCommand(ctx context.Context) (name, script string, err error) {
|
func (sr *stepRun) setupShellCommand(ctx context.Context) (name, script string, err error) {
|
||||||
logger := common.Logger(ctx)
|
logger := common.Logger(ctx)
|
||||||
implicitShell := sr.setupShell(ctx)
|
eval := sr.RunContext.NewStepExpressionEvaluator(ctx, sr)
|
||||||
sr.setupWorkingDirectory(ctx)
|
implicitShell, err := sr.setupShell(ctx, eval)
|
||||||
|
if err != nil {
|
||||||
|
return "", "", err
|
||||||
|
}
|
||||||
|
if err := sr.setupWorkingDirectory(ctx, eval); err != nil {
|
||||||
|
return "", "", err
|
||||||
|
}
|
||||||
|
|
||||||
step := sr.Step
|
step := sr.Step
|
||||||
|
|
||||||
script = sr.RunContext.NewStepExpressionEvaluator(ctx, sr).Interpolate(ctx, step.Run)
|
script, err = eval.Interpolate(ctx, step.Run)
|
||||||
|
if err != nil {
|
||||||
|
return "", "", fmt.Errorf("unable to interpolate the run script: %w", err)
|
||||||
|
}
|
||||||
sr.interpolatedScript = script
|
sr.interpolatedScript = script
|
||||||
|
|
||||||
// GitHub matches the built-in names case-insensitively, so `shell: PWSH` is valid
|
// GitHub matches the built-in names case-insensitively, so `shell: PWSH` is valid
|
||||||
@@ -313,19 +322,21 @@ func (sr *stepRun) setupShellCommand(ctx context.Context) (name, script string,
|
|||||||
return name, script, err
|
return name, script, err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (sr *stepRun) setupShell(ctx context.Context) bool {
|
func (sr *stepRun) setupShell(ctx context.Context, eval *expressionEvaluator) (bool, error) {
|
||||||
rc := sr.RunContext
|
rc := sr.RunContext
|
||||||
step := sr.Step
|
step := sr.Step
|
||||||
|
|
||||||
if step.Shell == "" {
|
shell, err := eval.Interpolate(ctx, step.Shell)
|
||||||
step.Shell = rc.Run.Job().Defaults.Run.Shell
|
if err != nil {
|
||||||
|
return false, fmt.Errorf("unable to interpolate the shell: %w", err)
|
||||||
}
|
}
|
||||||
|
if shell == "" {
|
||||||
step.Shell = rc.NewStepExpressionEvaluator(ctx, sr).Interpolate(ctx, step.Shell)
|
shell = rc.jobRunDefaults.Shell
|
||||||
|
|
||||||
if step.Shell == "" {
|
|
||||||
step.Shell = rc.Run.Workflow.Defaults.Run.Shell
|
|
||||||
}
|
}
|
||||||
|
if shell == "" {
|
||||||
|
shell = rc.Run.Workflow.Defaults.Run.Shell
|
||||||
|
}
|
||||||
|
step.Shell = shell
|
||||||
|
|
||||||
implicitShell := step.Shell == ""
|
implicitShell := step.Shell == ""
|
||||||
if implicitShell {
|
if implicitShell {
|
||||||
@@ -349,7 +360,7 @@ func (sr *stepRun) setupShell(ctx context.Context) bool {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return implicitShell
|
return implicitShell, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// containerHasBash probes once per job, else every implicit-shell step pays for an exec.
|
// containerHasBash probes once per job, else every implicit-shell step pays for an exec.
|
||||||
@@ -364,23 +375,19 @@ func (rc *RunContext) containerHasBash(ctx context.Context, env map[string]strin
|
|||||||
return *top.hasBash
|
return *top.hasBash
|
||||||
}
|
}
|
||||||
|
|
||||||
func (sr *stepRun) setupWorkingDirectory(ctx context.Context) {
|
func (sr *stepRun) setupWorkingDirectory(ctx context.Context, eval *expressionEvaluator) error {
|
||||||
rc := sr.RunContext
|
rc := sr.RunContext
|
||||||
step := sr.Step
|
workingdirectory, err := eval.Interpolate(ctx, sr.Step.WorkingDirectory)
|
||||||
var workingdirectory string
|
if err != nil {
|
||||||
|
return fmt.Errorf("unable to interpolate the working directory: %w", err)
|
||||||
if step.WorkingDirectory == "" {
|
|
||||||
workingdirectory = rc.Run.Job().Defaults.Run.WorkingDirectory
|
|
||||||
} else {
|
|
||||||
workingdirectory = step.WorkingDirectory
|
|
||||||
}
|
}
|
||||||
|
if workingdirectory == "" {
|
||||||
// jobs can receive context values, so we interpolate
|
workingdirectory = rc.jobRunDefaults.WorkingDirectory
|
||||||
workingdirectory = rc.NewStepExpressionEvaluator(ctx, sr).Interpolate(ctx, workingdirectory)
|
}
|
||||||
|
// top level keys in workflow file like `defaults` or `env` can't hold expressions
|
||||||
// but top level keys in workflow file like `defaults` or `env` can't
|
|
||||||
if workingdirectory == "" {
|
if workingdirectory == "" {
|
||||||
workingdirectory = rc.Run.Workflow.Defaults.Run.WorkingDirectory
|
workingdirectory = rc.Run.Workflow.Defaults.Run.WorkingDirectory
|
||||||
}
|
}
|
||||||
sr.WorkingDirectory = workingdirectory
|
sr.WorkingDirectory = workingdirectory
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
+28
-17
@@ -6,6 +6,7 @@ package runner
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
|
"cmp"
|
||||||
"context"
|
"context"
|
||||||
"io"
|
"io"
|
||||||
"os"
|
"os"
|
||||||
@@ -42,17 +43,12 @@ func TestStepRun(t *testing.T) {
|
|||||||
JobID: "1",
|
JobID: "1",
|
||||||
Workflow: &model.Workflow{
|
Workflow: &model.Workflow{
|
||||||
Jobs: map[string]*model.Job{
|
Jobs: map[string]*model.Job{
|
||||||
"1": {
|
"1": {},
|
||||||
Defaults: model.Defaults{
|
|
||||||
Run: model.RunDefaults{
|
|
||||||
Shell: "bash",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
JobContainer: cm,
|
JobContainer: cm,
|
||||||
|
jobRunDefaults: model.RunDefaults{Shell: "bash"},
|
||||||
},
|
},
|
||||||
Step: &model.Step{
|
Step: &model.Step{
|
||||||
ID: "1",
|
ID: "1",
|
||||||
@@ -84,13 +80,13 @@ func TestStepRun(t *testing.T) {
|
|||||||
|
|
||||||
func TestStepRunShellParity(t *testing.T) {
|
func TestStepRunShellParity(t *testing.T) {
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
name, shell, workingDir string
|
name, run, shell, workingDir string
|
||||||
env map[string]string
|
env map[string]string
|
||||||
host bool
|
host bool
|
||||||
probeErr error
|
probeErr error
|
||||||
wantExt string
|
wantExt string
|
||||||
wantCmd []string
|
wantCmd []string
|
||||||
wantErr string
|
wantErr string
|
||||||
}{
|
}{
|
||||||
{
|
{
|
||||||
name: "implicit host bash",
|
name: "implicit host bash",
|
||||||
@@ -130,6 +126,21 @@ func TestStepRunShellParity(t *testing.T) {
|
|||||||
wantExt: ".py",
|
wantExt: ".py",
|
||||||
wantCmd: []string{"python", "/var/run/act/workflow/1.py"},
|
wantCmd: []string{"python", "/var/run/act/workflow/1.py"},
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: "run expression without a context",
|
||||||
|
run: "echo ${{ COMMIT_SHA }}",
|
||||||
|
wantErr: "unable to interpolate the run script:",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "shell expression without a context",
|
||||||
|
shell: "${{ SHELL }}",
|
||||||
|
wantErr: "unable to interpolate the shell:",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "working directory expression without a context",
|
||||||
|
workingDir: "${{ DIR }}",
|
||||||
|
wantErr: "unable to interpolate the working directory:",
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, test := range tests {
|
for _, test := range tests {
|
||||||
@@ -156,13 +167,13 @@ func TestStepRunShellParity(t *testing.T) {
|
|||||||
Run: &model.Run{JobID: "1", Workflow: &model.Workflow{Jobs: map[string]*model.Job{"1": {}}}},
|
Run: &model.Run{JobID: "1", Workflow: &model.Workflow{Jobs: map[string]*model.Job{"1": {}}}},
|
||||||
JobContainer: jobContainer,
|
JobContainer: jobContainer,
|
||||||
},
|
},
|
||||||
Step: &model.Step{ID: "1", Run: "echo hi", Shell: test.shell, WorkingDirectory: test.workingDir},
|
Step: &model.Step{ID: "1", Run: cmp.Or(test.run, "echo hi"), Shell: test.shell, WorkingDirectory: test.workingDir},
|
||||||
env: test.env,
|
env: test.env,
|
||||||
}
|
}
|
||||||
|
|
||||||
name, script, err := sr.setupShellCommand(t.Context())
|
name, script, err := sr.setupShellCommand(t.Context())
|
||||||
if test.wantErr != "" {
|
if test.wantErr != "" {
|
||||||
require.EqualError(t, err, test.wantErr)
|
require.ErrorContains(t, err, test.wantErr)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|||||||
@@ -160,7 +160,7 @@ func TestSetupEnv(t *testing.T) {
|
|||||||
sm.On("getStepModel").Return(step)
|
sm.On("getStepModel").Return(step)
|
||||||
sm.On("getEnv").Return(&env)
|
sm.On("getEnv").Return(&env)
|
||||||
|
|
||||||
setupEnv(context.Background(), sm)
|
require.NoError(t, setupEnv(context.Background(), sm))
|
||||||
|
|
||||||
// These are commit or system specific
|
// These are commit or system specific
|
||||||
delete(env, "GITHUB_REF")
|
delete(env, "GITHUB_REF")
|
||||||
|
|||||||
@@ -0,0 +1,6 @@
|
|||||||
|
name: docker-proxy
|
||||||
|
description: Verify mounted Docker access through post steps
|
||||||
|
runs:
|
||||||
|
using: node24
|
||||||
|
main: index.js
|
||||||
|
post: index.js
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const {once} = require('node:events');
|
||||||
|
const fs = require('node:fs');
|
||||||
|
const http = require('node:http');
|
||||||
|
|
||||||
|
async function request(method, path, body) {
|
||||||
|
const req = http.request({
|
||||||
|
socketPath: '/var/run/docker.sock',
|
||||||
|
method,
|
||||||
|
path,
|
||||||
|
headers: {'Content-Type': 'application/json'},
|
||||||
|
signal: AbortSignal.timeout(10000),
|
||||||
|
});
|
||||||
|
req.end(JSON.stringify(body));
|
||||||
|
const [res] = await once(req, 'response');
|
||||||
|
req.on('error', (error) => res.destroy(error));
|
||||||
|
let data = '';
|
||||||
|
for await (const chunk of res.setEncoding('utf8')) {
|
||||||
|
data += chunk;
|
||||||
|
}
|
||||||
|
assert(res.statusCode >= 200 && res.statusCode < 300, `${method} ${path}: ${res.statusCode} ${data}`);
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
assert(fs.statSync('/var/run/docker.sock').isSocket(), 'Docker mount must be a socket');
|
||||||
|
assert.equal(await request('GET', '/_ping'), 'OK');
|
||||||
|
const api = `/v${JSON.parse(await request('GET', '/version')).ApiVersion}`;
|
||||||
|
const name = process.env.PROXY_TEST_RESOURCE;
|
||||||
|
const job = process.env.JOB_CONTAINER_NAME;
|
||||||
|
const post = process.env.STATE_post === 'true';
|
||||||
|
assert(name);
|
||||||
|
assert(job);
|
||||||
|
if (!post) {
|
||||||
|
await request('POST', `${api}/volumes/create`, {Name: name});
|
||||||
|
await request('POST', `${api}/networks/create`, {Name: name});
|
||||||
|
await request('POST', `${api}/networks/${name}/connect`, {Container: job});
|
||||||
|
fs.appendFileSync(process.env.GITHUB_STATE, 'post=true\n');
|
||||||
|
}
|
||||||
|
const label = process.env.PROXY_TEST_MODE === 'proxy' ? job : undefined;
|
||||||
|
assert.equal(JSON.parse(await request('GET', `${api}/volumes/${name}`)).Labels?.['com.gitea.runner.job'], label);
|
||||||
|
const network = JSON.parse(await request('GET', `${api}/networks/${name}`));
|
||||||
|
assert.equal(network.Labels?.['com.gitea.runner.job'], label);
|
||||||
|
assert(Object.values(network.Containers).some((container) => container.Name === job));
|
||||||
|
if (post) {
|
||||||
|
console.log('docker proxy post verified');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
main().catch((error) => {
|
||||||
|
console.error(error);
|
||||||
|
process.exitCode = 1;
|
||||||
|
});
|
||||||
+8
@@ -0,0 +1,8 @@
|
|||||||
|
name: docker-proxy
|
||||||
|
on: push
|
||||||
|
jobs:
|
||||||
|
proxy:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: ./action
|
||||||
@@ -2,7 +2,7 @@ module gitea.com/gitea/runner
|
|||||||
|
|
||||||
go 1.27
|
go 1.27
|
||||||
|
|
||||||
toolchain go1.27.0
|
toolchain go1.27.1
|
||||||
|
|
||||||
require (
|
require (
|
||||||
connectrpc.com/connect v1.20.0
|
connectrpc.com/connect v1.20.0
|
||||||
@@ -17,7 +17,7 @@ require (
|
|||||||
github.com/docker/go-units v0.5.0
|
github.com/docker/go-units v0.5.0
|
||||||
github.com/go-git/go-billy/v5 v5.9.1
|
github.com/go-git/go-billy/v5 v5.9.1
|
||||||
github.com/go-git/go-git/v5 v5.19.2
|
github.com/go-git/go-git/v5 v5.19.2
|
||||||
github.com/gobwas/glob v0.2.3
|
github.com/gobwas/glob v1.0.0
|
||||||
github.com/google/go-cmp v0.7.0
|
github.com/google/go-cmp v0.7.0
|
||||||
github.com/joho/godotenv v1.5.1
|
github.com/joho/godotenv v1.5.1
|
||||||
github.com/julienschmidt/httprouter v1.3.0
|
github.com/julienschmidt/httprouter v1.3.0
|
||||||
@@ -30,8 +30,8 @@ require (
|
|||||||
github.com/opencontainers/image-spec v1.1.1
|
github.com/opencontainers/image-spec v1.1.1
|
||||||
github.com/opencontainers/selinux v1.15.1
|
github.com/opencontainers/selinux v1.15.1
|
||||||
github.com/prometheus/client_golang v1.24.1
|
github.com/prometheus/client_golang v1.24.1
|
||||||
github.com/prometheus/client_model v0.6.2
|
github.com/prometheus/client_model v0.6.3
|
||||||
github.com/sirupsen/logrus v1.10.1
|
github.com/sirupsen/logrus v1.10.2
|
||||||
github.com/spf13/cobra v1.10.2
|
github.com/spf13/cobra v1.10.2
|
||||||
github.com/spf13/pflag v1.0.10
|
github.com/spf13/pflag v1.0.10
|
||||||
github.com/stretchr/testify v1.12.1
|
github.com/stretchr/testify v1.12.1
|
||||||
@@ -102,6 +102,6 @@ require (
|
|||||||
go.opentelemetry.io/otel/metric v1.45.0 // indirect
|
go.opentelemetry.io/otel/metric v1.45.0 // indirect
|
||||||
go.opentelemetry.io/otel/trace v1.45.0 // indirect
|
go.opentelemetry.io/otel/trace v1.45.0 // indirect
|
||||||
go.yaml.in/yaml/v3 v3.0.5 // indirect
|
go.yaml.in/yaml/v3 v3.0.5 // indirect
|
||||||
golang.org/x/crypto v0.55.0 // indirect
|
golang.org/x/crypto v0.56.0 // indirect
|
||||||
gopkg.in/warnings.v0 v0.1.2 // indirect
|
gopkg.in/warnings.v0 v0.1.2 // indirect
|
||||||
)
|
)
|
||||||
@@ -77,8 +77,8 @@ github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
|
|||||||
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
|
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
|
||||||
github.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=
|
github.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=
|
||||||
github.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
|
github.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
|
||||||
github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=
|
github.com/gobwas/glob v1.0.0 h1:p+FKbLEIsK1yZ39/OINwFvqNb5oyPY4H8xcy6uYu8dg=
|
||||||
github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=
|
github.com/gobwas/glob v1.0.0/go.mod h1:oWCdo522i2P1n/hMXGNWs7yoV4wy/ciZuUIbvKj5rkc=
|
||||||
github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8 h1:f+oWsMOmNPc8JmEHVZIycC7hBoQxHH9pNKQORJNozsQ=
|
github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8 h1:f+oWsMOmNPc8JmEHVZIycC7hBoQxHH9pNKQORJNozsQ=
|
||||||
github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8/go.mod h1:wcDNUvekVysuuOpQKo3191zZyTpiI6se1N1ULghS0sw=
|
github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8/go.mod h1:wcDNUvekVysuuOpQKo3191zZyTpiI6se1N1ULghS0sw=
|
||||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||||
@@ -157,8 +157,8 @@ github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINE
|
|||||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
github.com/prometheus/client_golang v1.24.1 h1:JnJkREXzWxUdCuPFpIWZiPispT9xVV59uiuyR2bPlnU=
|
github.com/prometheus/client_golang v1.24.1 h1:JnJkREXzWxUdCuPFpIWZiPispT9xVV59uiuyR2bPlnU=
|
||||||
github.com/prometheus/client_golang v1.24.1/go.mod h1:F+oSRECHg4sse5ucfYpYDeIv/hu68Zo0uoHKetWnzcE=
|
github.com/prometheus/client_golang v1.24.1/go.mod h1:F+oSRECHg4sse5ucfYpYDeIv/hu68Zo0uoHKetWnzcE=
|
||||||
github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=
|
github.com/prometheus/client_model v0.6.3 h1:O0jaTVAYNxTHYInEPFJt5I3+sN8zqBtVMPTB1qyxiEo=
|
||||||
github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=
|
github.com/prometheus/client_model v0.6.3/go.mod h1:gpN5P9S7Rr6Yr92PiQ+Ixvhf6JZEkF1dnxsYL2aPBEM=
|
||||||
github.com/prometheus/common v0.70.1 h1:1HvjP4D5oL3t8RsPlwxA9onvvStjtIHYE5XuuwOi/PY=
|
github.com/prometheus/common v0.70.1 h1:1HvjP4D5oL3t8RsPlwxA9onvvStjtIHYE5XuuwOi/PY=
|
||||||
github.com/prometheus/common v0.70.1/go.mod h1:VdFUQDMZK3VLkurFUVhia6uys/0suUp86TJz5qbJRhc=
|
github.com/prometheus/common v0.70.1/go.mod h1:VdFUQDMZK3VLkurFUVhia6uys/0suUp86TJz5qbJRhc=
|
||||||
github.com/prometheus/procfs v0.21.1 h1:GljZCt+zSTS+NZq88cyQ1LjZ+RCHp3uVuabBWA5+OJI=
|
github.com/prometheus/procfs v0.21.1 h1:GljZCt+zSTS+NZq88cyQ1LjZ+RCHp3uVuabBWA5+OJI=
|
||||||
@@ -173,8 +173,8 @@ github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQD
|
|||||||
github.com/sergi/go-diff v1.4.0 h1:n/SP9D5ad1fORl+llWyN+D6qoUETXNZARKjyY2/KVCw=
|
github.com/sergi/go-diff v1.4.0 h1:n/SP9D5ad1fORl+llWyN+D6qoUETXNZARKjyY2/KVCw=
|
||||||
github.com/sergi/go-diff v1.4.0/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4=
|
github.com/sergi/go-diff v1.4.0/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4=
|
||||||
github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
|
github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
|
||||||
github.com/sirupsen/logrus v1.10.1 h1:xi4336Zh11WpU14fXR6I67V3yaTPQYwRx2WEtHbRg4Q=
|
github.com/sirupsen/logrus v1.10.2 h1:G2SED73/qrAu6YwbdxOD6peLkCBI3z7L+ykJFTXJBBo=
|
||||||
github.com/sirupsen/logrus v1.10.1/go.mod h1:vsQHnG7xzNsxk3NrwboUiWPnIC3dmbjcGPykD7+tiHk=
|
github.com/sirupsen/logrus v1.10.2/go.mod h1:SLEg8TqYulVKKfIGHldVp2K2aYz2DKSVBq4g/H5bR7Q=
|
||||||
github.com/skeema/knownhosts v1.3.2 h1:EDL9mgf4NzwMXCTfaxSD/o/a5fxDw/xL9nkU28JjdBg=
|
github.com/skeema/knownhosts v1.3.2 h1:EDL9mgf4NzwMXCTfaxSD/o/a5fxDw/xL9nkU28JjdBg=
|
||||||
github.com/skeema/knownhosts v1.3.2/go.mod h1:bEg3iQAuw+jyiw+484wwFJoKSLwcfd7fqRy+N0QTiow=
|
github.com/skeema/knownhosts v1.3.2/go.mod h1:bEg3iQAuw+jyiw+484wwFJoKSLwcfd7fqRy+N0QTiow=
|
||||||
github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
|
github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
|
||||||
@@ -234,8 +234,8 @@ go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
|
|||||||
go.yaml.in/yaml/v4 v4.0.0-rc.3 h1:3h1fjsh1CTAPjW7q/EMe+C8shx5d8ctzZTrLcs/j8Go=
|
go.yaml.in/yaml/v4 v4.0.0-rc.3 h1:3h1fjsh1CTAPjW7q/EMe+C8shx5d8ctzZTrLcs/j8Go=
|
||||||
go.yaml.in/yaml/v4 v4.0.0-rc.3/go.mod h1:aZqd9kCMsGL7AuUv/m/PvWLdg5sjJsZ4oHDEnfPPfY0=
|
go.yaml.in/yaml/v4 v4.0.0-rc.3/go.mod h1:aZqd9kCMsGL7AuUv/m/PvWLdg5sjJsZ4oHDEnfPPfY0=
|
||||||
golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
|
golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
|
||||||
golang.org/x/crypto v0.55.0 h1:+KWHjbgOaAQ66dh/YlkZKHlz9ZUlq61AFirAR9ntP8M=
|
golang.org/x/crypto v0.56.0 h1:GUh5Ii4J5jtcseSMiRqr1jXCNHoxjeV9Fmekc2oLy6Y=
|
||||||
golang.org/x/crypto v0.55.0/go.mod h1:uq0V9dE/fzQuJtbnL+2EhWOE63vo164FY8xqEnV9xis=
|
golang.org/x/crypto v0.56.0/go.mod h1:OMW5y6CY9l38uPLmxU6l6pwcXp1obtLo3e6gT7gQR2I=
|
||||||
golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f h1:W3F4c+6OLc6H2lb//N1q4WpJkhzJCK5J6kUi1NTVXfM=
|
golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f h1:W3F4c+6OLc6H2lb//N1q4WpJkhzJCK5J6kUi1NTVXfM=
|
||||||
golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f/go.mod h1:J1xhfL/vlindoeF/aINzNzt2Bket5bjo9sdOYzOsU80=
|
golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f/go.mod h1:J1xhfL/vlindoeF/aINzNzt2Bket5bjo9sdOYzOsU80=
|
||||||
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
||||||
|
|||||||
@@ -256,11 +256,10 @@ container:
|
|||||||
#require_docker: false
|
#require_docker: false
|
||||||
# Timeout to wait for the docker daemon to be reachable, if docker is required by require_docker or runner
|
# Timeout to wait for the docker daemon to be reachable, if docker is required by require_docker or runner
|
||||||
#docker_timeout: 0s
|
#docker_timeout: 0s
|
||||||
# Bind the workspace to the host filesystem instead of using Docker volumes.
|
# Mount the workspace from a host directory instead of a Docker volume, so jobs
|
||||||
# This is required for Docker-in-Docker (DinD) setups when jobs use docker compose
|
# can bind-mount it by its own path into sibling containers (".:/app" in docker
|
||||||
# with bind mounts (e.g., ".:/app"), as volume-based workspaces are not accessible
|
# compose). Not needed when workflows use the GITEA_DOCKER_WORKSPACE variable.
|
||||||
# from the DinD daemon's filesystem. When enabled, ensure the workspace parent
|
# The workspace parent directory must be mounted into the runner container.
|
||||||
# directory is also mounted into the runner container and listed in valid_volumes.
|
|
||||||
#bind_workdir: false
|
#bind_workdir: false
|
||||||
# How long a job waits for a service container that declares a healthcheck to become
|
# How long a job waits for a service container that declares a healthcheck to become
|
||||||
# healthy. A negative value (e.g. -1s) starts the steps without waiting.
|
# healthy. A negative value (e.g. -1s) starts the steps without waiting.
|
||||||
|
|||||||
@@ -157,7 +157,7 @@ type Container struct {
|
|||||||
ForceRebuild bool `yaml:"force_rebuild"` // Rebuild docker image(s) even if already present
|
ForceRebuild bool `yaml:"force_rebuild"` // Rebuild docker image(s) even if already present
|
||||||
RequireDocker bool `yaml:"require_docker"` // Always require a reachable docker daemon, even if not required by runner
|
RequireDocker bool `yaml:"require_docker"` // Always require a reachable docker daemon, even if not required by runner
|
||||||
DockerTimeout time.Duration `yaml:"docker_timeout"` // Timeout to wait for the docker daemon to be reachable, if docker is required by require_docker or runner
|
DockerTimeout time.Duration `yaml:"docker_timeout"` // Timeout to wait for the docker daemon to be reachable, if docker is required by require_docker or runner
|
||||||
BindWorkdir bool `yaml:"bind_workdir"` // BindWorkdir binds the workspace to the host filesystem instead of using Docker volumes. Required for DinD when jobs use docker compose with bind mounts.
|
BindWorkdir bool `yaml:"bind_workdir"` // BindWorkdir mounts the workspace from a host directory instead of a Docker volume.
|
||||||
ServiceReadyTimeout time.Duration `yaml:"service_ready_timeout"` // ServiceReadyTimeout bounds how long a job waits for a service container that declares a healthcheck to report healthy. Negative disables waiting.
|
ServiceReadyTimeout time.Duration `yaml:"service_ready_timeout"` // ServiceReadyTimeout bounds how long a job waits for a service container that declares a healthcheck to report healthy. Negative disables waiting.
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+56
-9
@@ -9,10 +9,8 @@
|
|||||||
#
|
#
|
||||||
# Usage: scripts/test-dind.sh [target] [-- go-test-args...]
|
# Usage: scripts/test-dind.sh [target] [-- go-test-args...]
|
||||||
# target: dind (default) or dind-rootless
|
# target: dind (default) or dind-rootless
|
||||||
# go-test-args: passed verbatim to `go test`. The default exercises the daemon-facing tests
|
# go-test-args: passed verbatim to `go test`. Defaults cover image env extraction,
|
||||||
# that need no registry access (a fresh daemon, e.g. on fork-PR CI, can't
|
# symlink copying and a mounted Docker job using cached images.
|
||||||
# authenticate pulls): the env-extraction build (FROM scratch) and the #981
|
|
||||||
# /var/run symlink copy regression (which reuses a preloaded alpine).
|
|
||||||
#
|
#
|
||||||
# Env:
|
# Env:
|
||||||
# DIND_TEST_PORT host port for the daemon (default 32375)
|
# DIND_TEST_PORT host port for the daemon (default 32375)
|
||||||
@@ -25,15 +23,25 @@ case "${1:-}" in
|
|||||||
dind|dind-rootless) target="$1"; shift ;;
|
dind|dind-rootless) target="$1"; shift ;;
|
||||||
esac
|
esac
|
||||||
[ "${1:-}" = "--" ] && shift
|
[ "${1:-}" = "--" ] && shift
|
||||||
[ $# -eq 0 ] && set -- -race -run '^TestDocker$|^TestDockerCopyToSymlinkPath$' ./act/container/
|
default_tests=false
|
||||||
|
if [ $# -eq 0 ]; then
|
||||||
|
default_tests=true
|
||||||
|
set -- -count=1 -race -run '^TestDocker$|^TestDockerCopyToSymlinkPath$' ./act/container/
|
||||||
|
fi
|
||||||
|
|
||||||
port="${DIND_TEST_PORT:-32375}"
|
port="${DIND_TEST_PORT:-32375}"
|
||||||
name="gitea-runner-dind-test-$$"
|
name="gitea-runner-dind-test-$$"
|
||||||
image="${DIND_TEST_IMAGE:-gitea-runner-${target}:dind-test}"
|
image="${DIND_TEST_IMAGE:-gitea-runner-${target}:dind-test}"
|
||||||
# The host daemon endpoint, captured before DOCKER_HOST is pointed at the fresh dind daemon.
|
# The host daemon endpoint, captured before DOCKER_HOST is pointed at the fresh dind daemon.
|
||||||
host_docker="${DOCKER_HOST:-unix:///var/run/docker.sock}"
|
host_docker="${DOCKER_HOST:-$(docker context inspect --format '{{.Endpoints.docker.Host}}')}"
|
||||||
|
test_dir=""
|
||||||
|
|
||||||
cleanup() { docker rm -f "$name" >/dev/null 2>&1 || true; }
|
cleanup() {
|
||||||
|
docker -H "$host_docker" rm -fv "$name" >/dev/null 2>&1 || true
|
||||||
|
if [ -n "$test_dir" ]; then
|
||||||
|
rm -rf "$test_dir"
|
||||||
|
fi
|
||||||
|
}
|
||||||
trap cleanup EXIT
|
trap cleanup EXIT
|
||||||
|
|
||||||
if [ -z "${DIND_TEST_IMAGE:-}" ]; then
|
if [ -z "${DIND_TEST_IMAGE:-}" ]; then
|
||||||
@@ -71,7 +79,7 @@ else
|
|||||||
fi
|
fi
|
||||||
# Create the dind container on the host daemon first, then repoint DOCKER_HOST at it: exporting
|
# Create the dind container on the host daemon first, then repoint DOCKER_HOST at it: exporting
|
||||||
# DOCKER_HOST before `docker run` would make this `docker run` target the not-yet-existent dind.
|
# DOCKER_HOST before `docker run` would make this `docker run` target the not-yet-existent dind.
|
||||||
docker run -d --privileged --name "$name" "${run_args[@]}" \
|
docker -H "$host_docker" run -d --privileged --name "$name" "${run_args[@]}" \
|
||||||
-e DOCKER_TLS_CERTDIR= \
|
-e DOCKER_TLS_CERTDIR= \
|
||||||
--entrypoint dockerd-entrypoint.sh \
|
--entrypoint dockerd-entrypoint.sh \
|
||||||
"$image" --host=tcp://0.0.0.0:2375 >/dev/null
|
"$image" --host=tcp://0.0.0.0:2375 >/dev/null
|
||||||
@@ -82,11 +90,20 @@ for _ in $(seq 1 60); do
|
|||||||
docker version --format 'server docker {{.Server.Version}}' 2>/dev/null && break
|
docker version --format 'server docker {{.Server.Version}}' 2>/dev/null && break
|
||||||
sleep 1
|
sleep 1
|
||||||
done
|
done
|
||||||
|
if ! docker version --format 'server docker {{.Server.Version}}'; then
|
||||||
|
docker -H "$host_docker" logs "$name" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
# Seed the fresh daemon with images the host already has (the CI job pulls them in the
|
# Seed the fresh daemon with images the host already has (the CI job pulls them in the
|
||||||
# preceding `make test`), so the daemon-facing tests run without registry access.
|
# preceding `make test`), so the daemon-facing tests run without registry access.
|
||||||
echo "==> Seeding daemon with cached host images"
|
echo "==> Seeding daemon with cached host images"
|
||||||
for img in ${DIND_TEST_PRELOAD:-alpine:latest}; do
|
preload="${DIND_TEST_PRELOAD:-alpine:latest}"
|
||||||
|
job_image="${ACT_TEST_IMAGE:-node:24-bookworm-slim}"
|
||||||
|
if [ "$default_tests" = true ]; then
|
||||||
|
preload="$preload $job_image"
|
||||||
|
fi
|
||||||
|
for img in $preload; do
|
||||||
if docker -H "$host_docker" image inspect "$img" >/dev/null 2>&1; then
|
if docker -H "$host_docker" image inspect "$img" >/dev/null 2>&1; then
|
||||||
docker -H "$host_docker" save "$img" | docker load >/dev/null 2>&1 && echo " loaded $img" || true
|
docker -H "$host_docker" save "$img" | docker load >/dev/null 2>&1 && echo " loaded $img" || true
|
||||||
fi
|
fi
|
||||||
@@ -94,3 +111,33 @@ done
|
|||||||
|
|
||||||
echo "==> Running tests against dind daemon"
|
echo "==> Running tests against dind daemon"
|
||||||
go test "$@"
|
go test "$@"
|
||||||
|
|
||||||
|
if [ "$default_tests" = true ]; then
|
||||||
|
if ! docker image inspect "$job_image" >/dev/null 2>&1; then
|
||||||
|
echo "mounted Docker test requires ${job_image}, pull it on the host before running this harness" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
test_dir="$(mktemp -d)"
|
||||||
|
echo "==> Building mounted Docker test for the dind container"
|
||||||
|
CGO_ENABLED=0 GOOS=linux GOARCH="$(docker -H "$host_docker" image inspect "$image" --format '{{.Architecture}}')" \
|
||||||
|
go test -c -o "$test_dir/runner.test" ./act/runner/
|
||||||
|
docker -H "$host_docker" exec "$name" mkdir -p /tmp/gitea-runner-proxy-test/testdata
|
||||||
|
tar -C "$test_dir" -cf - runner.test -C "$PWD/act/runner" testdata/docker-proxy | \
|
||||||
|
docker -H "$host_docker" exec -i "$name" tar -x -C /tmp/gitea-runner-proxy-test
|
||||||
|
socket="unix:///var/run/docker.sock"
|
||||||
|
users=(0)
|
||||||
|
if [ "$target" = dind-rootless ]; then
|
||||||
|
socket="unix:///run/user/1000/docker.sock"
|
||||||
|
users=(1000 0)
|
||||||
|
fi
|
||||||
|
for user in "${users[@]}"; do
|
||||||
|
proxy_mode="proxy"
|
||||||
|
if [ "$user" != 0 ]; then
|
||||||
|
proxy_mode="direct"
|
||||||
|
fi
|
||||||
|
echo "==> Running mounted Docker job inside ${target} as UID ${user}, expecting ${proxy_mode} access"
|
||||||
|
docker -H "$host_docker" exec --user "$user" -w /tmp/gitea-runner-proxy-test \
|
||||||
|
-e DOCKER_HOST="$socket" -e ACT_TEST_DOCKER_PROXY="$proxy_mode" -e ACT_TEST_IMAGE="$job_image" \
|
||||||
|
"$name" ./runner.test -test.v -test.run '^TestDockerProxyMountedJob$' -test.timeout 3m
|
||||||
|
done
|
||||||
|
fi
|
||||||
Reference in new issue
Block a user