From e71a5028b057b773e4c8f5f935c319edc1c46b9c Mon Sep 17 00:00:00 2001 From: silverwind Date: Sun, 22 Nov 2026 10:11:23 +0000 Subject: [PATCH] enhance: align job execution closer to GitHub Actions (#1421) Closes many small gaps between how workflows run on GitHub and on the runner, each checked against GitHub's runner and live runs. - `action.yml` expressions are checked against the contexts GitHub allows per field, and input defaults are evaluated with those contexts only - Reusable workflows take inputs from `workflow_call` only, evaluate outputs once after all called jobs finish, stop at 10 nested workflows and resolve relative `./` paths in remote workflows against that workflow's repository - A called job failing under `continue-on-error` no longer fails the caller, and same-repository calls use their own clone cache - Job timeouts cancel the job with GitHub's message, step timeouts fail the step with GitHub's message, and invalid `timeout-minutes` values behave like on GitHub - `runner.timeout` expiry names the setting and server cancellation is logged - Matrix and strategy evaluation errors fail the job - `exec` records skipped jobs and sets `github.run_attempt`, `workflow_ref` and `workflow_sha` - `runs-on` expressions keep their types - Step summaries upload as each step ends - Docker actions join the job network, and the job container no longer gets a network alias from the job name - Container, network and volume names are unique per job invocation - Cached images are matched against the daemon's platform and Dockerfile actions build for the requested platform - `runner.arch` maps 32-bit ARM and x86 names like GitHub - Pinned action SHAs are verified and git replace objects are ignored - `hashFiles` uses GitHub's current bundle - Registration trims labels and writes `.runner` as `0600` - The container entrypoint quotes its arguments and reads the registration token from the environment or a file - The systemd example uses `KillMode=mixed` so running jobs can finish on stop - The cache server releases its database between eviction batches - Shared rules come from actionslib v1.7.0, added in https://gitea.com/gitea/actionslib/pulls/34 _Written by Claude (Opus 5.5)._ Reviewed-on: https://gitea.com/gitea/runner/pulls/1421 Reviewed-by: bircni Co-authored-by: silverwind --- act/artifactcache/handler.go | 250 +++--- act/artifactcache/handler_test.go | 67 +- act/common/git/fetch_action.go | 33 +- act/common/git/fetch_action_test.go | 34 +- act/common/git/git.go | 39 +- act/common/git/git_test.go | 5 + act/container/docker_images.go | 31 +- act/container/docker_pull.go | 3 +- act/container/docker_pull_test.go | 38 + act/container/docker_run.go | 20 +- act/container/docker_run_test.go | 25 +- act/container/docker_stub.go | 2 - act/container/host_environment.go | 21 +- act/container/host_environment_test.go | 10 +- act/runner/action.go | 654 ++++++---------- act/runner/action_composite.go | 145 ++-- act/runner/action_composite_test.go | 56 +- act/runner/action_test.go | 452 +++-------- act/runner/cancellation_test.go | 172 ++--- act/runner/docker_proxy_integration_test.go | 24 +- act/runner/expression.go | 152 ++-- act/runner/expression_test.go | 79 +- act/runner/hashfiles/index.js | 793 ++++++++++++++------ act/runner/job_executor.go | 527 ++++++------- act/runner/job_executor_test.go | 773 +++++++------------ act/runner/max_parallel_test.go | 53 +- act/runner/reusable_workflow.go | 281 +++---- act/runner/reusable_workflow_test.go | 242 +++--- act/runner/run_context.go | 176 ++--- act/runner/run_context_test.go | 28 +- act/runner/runner.go | 64 +- act/runner/runner_test.go | 54 +- act/runner/step.go | 45 +- act/runner/step_action_local.go | 17 +- act/runner/step_action_local_test.go | 6 +- act/runner/step_action_remote.go | 33 +- act/runner/step_action_remote_test.go | 12 +- act/runner/step_docker.go | 63 +- act/runner/step_docker_test.go | 98 +-- act/runner/step_run.go | 26 +- act/runner/step_test.go | 58 +- e2e/failure_test.go | 9 +- examples/systemd/gitea-runner.service | 1 + go.mod | 2 +- go.sum | 4 +- internal/app/cmd/daemon.go | 16 +- internal/app/cmd/daemon_test.go | 6 +- internal/app/cmd/register.go | 14 +- internal/app/cmd/register_test.go | 8 +- internal/app/run/post_task_script_test.go | 18 +- internal/app/run/runner.go | 21 +- internal/app/run/runner_test.go | 3 +- internal/app/run/workflow.go | 2 +- internal/pkg/config/registration.go | 6 +- internal/pkg/config/registration_test.go | 9 + internal/pkg/report/joblog_test.go | 6 +- internal/pkg/report/reporter.go | 139 ++-- internal/pkg/report/reporter_test.go | 192 ++--- scripts/run.sh | 54 +- 59 files changed, 2783 insertions(+), 3388 deletions(-) diff --git a/act/artifactcache/handler.go b/act/artifactcache/handler.go index c1a7e94e..f9d3d346 100644 --- a/act/artifactcache/handler.go +++ b/act/artifactcache/handler.go @@ -725,7 +725,7 @@ func (h *Handler) lookupCache(db *cacheDB, cred JobCredential, keys []string, ve h.touch(db, cache) return cache, nil } - if !h.deleteCache(db, cache) { + if !h.removeBlob(cache) || !h.deleteEntries(db, cache) { return nil, nil //nolint:nilnil // absence is not an error here } } @@ -900,16 +900,12 @@ func (h *Handler) commitCache(cache *Cache) error { if err != nil { return err } - defer db.Close() - if err := db.save(cache); err != nil { - return err + err = db.save(cache) + db.Close() + if err == nil && h.s3 == nil { // lifecycle rules on the bucket bound its size + h.evictOversized(&cache.Repo) } - if h.s3 != nil { - return nil // lifecycle rules on the bucket bound its size - } - h.evictRepo(db, cache.Repo) - h.evictTotal(db) - return nil + return err } // GET /_apis/artifactcache/artifacts/:id @@ -1243,6 +1239,7 @@ const ( miB = 1024 * 1024 defaultSweepInterval = time.Hour + evictionBatchSize = 8 touchStale = time.Minute // how stale a completed entry's UsedAt may get before an access rewrites it, sparing hits the fsync @@ -1298,144 +1295,163 @@ func (h *Handler) gcCache() { if err != nil { return } - defer db.Close() - if err := db.dropLegacyIndexes(); err != nil { h.logger.Warnf("drop legacy indexes: %v", err) } - h.evictIncomplete(db) + db.Close() + + stalled := h.gcAt.Add(-uploadStallTimeout).Unix() + expired := h.gcAt.Add(-max(h.policy.Retention+touchStale, inUseGrace)).Unix() // never below inUseGrace, or a short retention would outrun a signed URL already issued + h.evictBatches(func(batch *evictionBatch) { + for _, cache := range h.caches(batch.db, func(cache *Cache) bool { + return !cache.Complete && cache.UsedAt < stalled || + h.s3 == nil && h.policy.Retention > 0 && cache.UsedAt < expired + }) { + h.deleteCache(batch, cache) + } + }) if h.s3 != nil { return // lifecycle rules on the bucket expire its entries } - h.evictExpired(db) - h.evictSuperseded(db) - h.evictOversized(db) - _ = db.Close() + h.evictBatches(h.evictSuperseded) + h.evictOversized(nil) h.makeRoom(0) } +type evictionBatch struct { + db *cacheDB + failed map[uint64]bool + removed []*Cache + candidates int +} + +func (h *Handler) evictBatches(evict func(*evictionBatch)) { + failed := make(map[uint64]bool) + for { + db, err := h.openDB() + if err != nil { + return + } + batch := evictionBatch{db: db, failed: failed} + evict(&batch) + deleted := len(batch.removed) == 0 || h.deleteEntries(db, batch.removed...) + db.Close() + if !deleted || batch.candidates <= evictionBatchSize { + return + } + } +} + +func (h *Handler) deleteCache(batch *evictionBatch, cache *Cache) bool { + if batch.failed[cache.ID] { + return false + } + batch.candidates++ + if batch.candidates > evictionBatchSize { + return false + } + if !h.removeBlob(cache) { + batch.failed[cache.ID] = true + return false + } + batch.removed = append(batch.removed, cache) + return true +} + +func (h *Handler) diskShortfall(need int64) int64 { + free, err := h.freeDisk(h.dir) + if err != nil { + h.logger.Debugf("free disk check: %v", err) // unsupported platform, treat as unavailable rather than full + return 0 + } + return max(h.policy.MinFreeDisk+max(need, 0)-int64(free), 0) +} + // makeRoom evicts the least recently used entries to keep need bytes above the floor, as GitHub saves new over old. func (h *Handler) makeRoom(need int64) { - free, err := h.freeDisk(h.dir) - if err != nil { - h.logger.Debugf("free disk check: %v", err) // unsupported platform, treat as unavailable rather than full + if h.s3 != nil || h.diskShortfall(need) == 0 { return } - shortfall := h.policy.MinFreeDisk + max(need, 0) - int64(free) - if h.s3 != nil || shortfall <= 0 { - return - } - db, err := h.openDB() - if err != nil { - return - } - defer db.Close() - - caches := h.completedByUse(db) - total := totalSize(caches) - if total <= shortfall { - // Say so, or shedding everything and still being short reads as the backstop working. - h.logger.Warnf("cache volume is %d MiB short of the free space floor with only %d MiB of cache on it; something else is filling it", shortfall/miB, total/miB) - } - h.evictTo(db, caches, total-shortfall, "the cache volume") -} - -// evictIncomplete removes uploads that stopped part way, which are most likely broken. -func (h *Handler) evictIncomplete(db *cacheDB) { - stalled := time.Now().Add(-uploadStallTimeout).Unix() - h.sweep(db, func(cache *Cache) bool { return cache.UsedAt < stalled && !cache.Complete }) -} - -func (h *Handler) evictExpired(db *cacheDB) { - if h.policy.Retention <= 0 { - return - } - // Never below inUseGrace, or a short retention would outrun a signed URL already issued. - expired := time.Now().Add(-max(h.policy.Retention+touchStale, inUseGrace)).Unix() - h.sweep(db, func(cache *Cache) bool { return cache.UsedAt < expired }) + h.evictBatches(func(batch *evictionBatch) { + shortfall := h.diskShortfall(need) + if shortfall == 0 { + return + } + caches := h.cachesByUse(batch.db, func(cache *Cache) bool { return cache.Complete }) + total := totalSize(caches) + if total <= shortfall { // say so, or shedding everything and still being short reads as the backstop working + h.logger.Warnf("cache volume is %d MiB short of the free space floor with only %d MiB of cache on it. Something else is filling it", shortfall/miB, total/miB) + } + h.evictTo(batch, caches, total-shortfall, "the cache volume") + }) } // evictSuperseded removes entries a newer one with the same repo, ref, key and version replaced. -func (h *Handler) evictSuperseded(db *cacheDB) { +func (h *Handler) evictSuperseded(batch *evictionBatch) { type entry struct{ repo, ref, key, version string } groups := make(map[entry][]*Cache) - for _, cache := range h.caches(db, func(cache *Cache) bool { return cache.Complete }) { + for _, cache := range h.caches(batch.db, func(cache *Cache) bool { return cache.Complete }) { group := entry{cache.Repo, cache.Ref, cache.Key, cache.Version} groups[group] = append(groups[group], cache) } for _, caches := range groups { - slices.SortFunc(caches, func(left, right *Cache) int { - return cmp.Or(cmp.Compare(left.createdAtNano(), right.createdAtNano()), cmp.Compare(left.ID, right.ID)) - }) - for _, cache := range caches[:len(caches)-1] { - if inUse(cache) { - continue + newest := latest(caches, (*Cache).createdAtNano) + for _, cache := range caches { + if cache != newest && !inUse(cache) { + h.deleteCache(batch, cache) } - h.deleteCache(db, cache) } } } // evictOversized applies the per-repository limit, then the whole-store one. Only completed // entries count, since only those carry a size measured at commit rather than claimed. -func (h *Handler) evictOversized(db *cacheDB) { - if h.policy.RepoSizeLimit > 0 { - byRepo := make(map[string][]*Cache) - for _, cache := range h.completedByUse(db) { - byRepo[cache.Repo] = append(byRepo[cache.Repo], cache) - } - for repo, caches := range byRepo { - h.evictTo(db, caches, h.policy.RepoSizeLimit, "repository "+repo) - } - } - h.evictTotal(db) -} - -// evictTotal caps the store as a whole. It re-queries because the per-repo pass may have -// deleted rows an earlier result still holds. -func (h *Handler) evictTotal(db *cacheDB) { - if h.policy.SizeLimit <= 0 { +func (h *Handler) evictOversized(repo *string) { + if h.policy.RepoSizeLimit <= 0 && h.policy.SizeLimit <= 0 { return } - h.evictTo(db, h.completedByUse(db), h.policy.SizeLimit, "the cache") -} - -// evictRepo reclaims space when a commit pushes a repo over, rather than at the next sweep. -func (h *Handler) evictRepo(db *cacheDB, repo string) { - if h.policy.RepoSizeLimit <= 0 { - return - } - h.evictTo(db, h.cachesByUse(db, func(cache *Cache) bool { return cache.Repo == repo && cache.Complete }), h.policy.RepoSizeLimit, "repository "+repo) + h.evictBatches(func(batch *evictionBatch) { + caches := h.cachesByUse(batch.db, func(cache *Cache) bool { return cache.Complete }) + overTotal := h.policy.SizeLimit > 0 && totalSize(caches) > h.policy.SizeLimit + if h.policy.RepoSizeLimit > 0 { + byRepo := make(map[string][]*Cache) + for _, cache := range caches { + if overTotal || repo == nil || cache.Repo == *repo { + byRepo[cache.Repo] = append(byRepo[cache.Repo], cache) + } + } + for repo, caches := range byRepo { + h.evictTo(batch, caches, h.policy.RepoSizeLimit, "repository "+repo) + } + } + if overTotal { + caches = slices.DeleteFunc(caches, func(cache *Cache) bool { return slices.Contains(batch.removed, cache) }) + h.evictTo(batch, caches, h.policy.SizeLimit, "the cache") + } + }) } // evictTo deletes until caches fit limit. caches must be ordered by UsedAt ascending. -func (h *Handler) evictTo(db *cacheDB, caches []*Cache, limit int64, scope string) { +func (h *Handler) evictTo(batch *evictionBatch, caches []*Cache, limit int64, scope string) { // An entry bigger than the limit never fits, so it goes on its own account instead of // dragging every neighbour out first and then following them next sweep. - fits := caches[:0] + var total int64 for _, cache := range caches { if cache.Size <= limit { - fits = append(fits, cache) - continue - } - if !inUse(cache) { + total += cache.Size + } else if !inUse(cache) && h.deleteCache(batch, cache) { h.logger.Warnf("cache %q is %d MiB on its own, over the limit for %s; dropping it", cache.Key, cache.Size/miB, scope) - h.deleteCache(db, cache) } } - caches = fits - total := totalSize(caches) var freed int64 for _, cache := range caches { - if total <= limit { + if total-freed <= limit { break } - if inUse(cache) || !h.deleteCache(db, cache) { - continue + if cache.Size <= limit && !inUse(cache) && h.deleteCache(batch, cache) { + freed += cache.Size } - total -= cache.Size - freed += cache.Size } if freed > 0 { h.logger.Warnf("evicted %d MiB from %s, least recently used first", freed/miB, scope) @@ -1466,12 +1482,6 @@ func (h *Handler) touch(db *cacheDB, cache *Cache) { } } -func (h *Handler) sweep(db *cacheDB, match func(*Cache) bool) { - for _, cache := range h.caches(db, match) { - h.deleteCache(db, cache) - } -} - func (h *Handler) caches(db *cacheDB, match func(*Cache) bool) []*Cache { caches, err := db.find(match) if err != nil { @@ -1486,11 +1496,6 @@ func (h *Handler) cachesByUse(db *cacheDB, match func(*Cache) bool) []*Cache { return caches } -// completedByUse returns every entry the size limits count, least recently accessed first. -func (h *Handler) completedByUse(db *cacheDB) []*Cache { - return h.cachesByUse(db, func(cache *Cache) bool { return cache.Complete }) -} - func totalSize(caches []*Cache) int64 { var total int64 for _, cache := range caches { @@ -1499,9 +1504,7 @@ func totalSize(caches []*Cache) int64 { return total } -// deleteCache drops an entry and its bytes, reporting whether it went fully. The blob goes -// first, so a failed unlink leaves the row for the next sweep instead of orphaning bytes. -func (h *Handler) deleteCache(db *cacheDB, cache *Cache) bool { +func (h *Handler) removeBlob(cache *Cache) bool { storage := h.storage if h.s3 != nil && !cache.Complete { storage = h.s3.Storage // an upload not yet committed has nothing in the bucket @@ -1510,11 +1513,24 @@ func (h *Handler) deleteCache(db *cacheDB, cache *Cache) bool { h.logger.Warnf("remove cache blob: %v", err) return false } - if err := db.update(func(bucket *bbolt.Bucket) error { return db.delete(bucket, cache.ID) }); err != nil { + return true +} + +func (h *Handler) deleteEntries(db *cacheDB, caches ...*Cache) bool { + if err := db.update(func(bucket *bbolt.Bucket) error { + for _, cache := range caches { + if err := db.delete(bucket, cache.ID); err != nil { + return err + } + } + return nil + }); err != nil { h.logger.Warnf("delete cache: %v", err) return false } - h.logger.Infof("deleted cache: %+v", cache) + for _, cache := range caches { + h.logger.Infof("deleted cache: %+v", cache) + } return true } diff --git a/act/artifactcache/handler_test.go b/act/artifactcache/handler_test.go index 7b88da13..d90d4a41 100644 --- a/act/artifactcache/handler_test.go +++ b/act/artifactcache/handler_test.go @@ -731,40 +731,61 @@ func TestHandler_makeRoom(t *testing.T) { } } -func TestHandler_SweepKeepsEntryWhenBlobSurvives(t *testing.T) { +func TestHandler_SweepKeepsEntriesWhenBlobsSurviveAcrossBatches(t *testing.T) { t.Parallel() - cache := &Cache{Key: "stuck", Complete: true, UsedAt: time.Now().Add(-(testRetention + time.Hour)).Unix()} - handler := newTestHandler(t, Policy{Retention: testRetention}, cache) - - blob := handler.storage.(*Storage).filename(cache.ID) - require.NoError(t, os.MkdirAll(blob, 0o755)) - require.NoError(t, os.WriteFile(filepath.Join(blob, "held"), []byte("x"), 0o600)) + var caches []*Cache + for range evictionBatchSize + 1 { + caches = append(caches, &Cache{Key: "stuck", Complete: true, UsedAt: time.Now().Add(-(testRetention + time.Hour)).Unix()}) + } + handler := newTestHandler(t, Policy{Retention: testRetention}, caches...) + for _, cache := range caches { + blob := handler.storage.(*Storage).filename(cache.ID) + require.NoError(t, os.MkdirAll(blob, 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(blob, "held"), []byte("x"), 0o600)) + } handler.gcAt = time.Time{} handler.gcCache() - assert.Equal(t, []string{"stuck"}, keptKeys(t, handler, []*Cache{cache}), "the entry must outlive a blob that could not be removed") + assert.Len(t, keptKeys(t, handler, caches), len(caches), "an entry must outlive a blob that could not be removed") } -func TestHandler_FindProtectsFromEviction(t *testing.T) { +func TestHandler_EvictionRechecksLookupsAndRepoLimitsBetweenBatches(t *testing.T) { t.Parallel() - wanted := &Cache{Repo: testRepo, Key: "wanted", Version: "v", Complete: true, Size: 4 * miB, UsedAt: time.Now().Add(-3 * time.Hour).Unix()} - other := &Cache{Repo: testRepo, Key: "other", Version: "v", Complete: true, Size: 4 * miB, UsedAt: time.Now().Add(-2 * time.Hour).Unix()} - newest := &Cache{Repo: testRepo, Key: "newest", Version: "v", Complete: true, Size: 4 * miB, UsedAt: time.Now().Add(-time.Hour).Unix()} - handler := newTestHandler(t, Policy{RepoSizeLimit: 10 * miB}, wanted, other, newest) - writeBlob(t, handler, wanted.ID) + synctest.Test(t, func(t *testing.T) { + wanted := &Cache{Repo: testRepo, Key: "wanted", Complete: true, Size: 1, UsedAt: 1} + entries := []*Cache{ + wanted, + {Key: "other", Complete: true, Size: 3, UsedAt: 2}, + {Repo: "o/b", Key: "old", Complete: true, Size: 2, UsedAt: 3}, + } + for range 8 { + entries = append(entries, &Cache{Complete: true, Size: 1}) + } + handler := newTestHandler(t, Policy{RepoSizeLimit: 3, SizeLimit: 5}, entries...) + require.NoError(t, handler.Close()) + writeBlob(t, handler, wanted.ID) - resp, err := testClient.Get(fmt.Sprintf("%s%s/cache?keys=wanted&version=v", handler.ExternalURL(), apiPath)) - require.NoError(t, err) - defer resp.Body.Close() - require.Equal(t, 200, resp.StatusCode) + locked, err := handler.openDB() + require.NoError(t, err) + go handler.evictOversized(&wanted.Repo) + synctest.Wait() + go func() { + synctest.Wait() + locked.Close() + }() - db, err := handler.openDB() - require.NoError(t, err) - handler.evictOversized(db) - require.NoError(t, db.Close()) + db, err := handler.openDB() + require.NoError(t, err) + require.Len(t, handler.caches(db, func(*Cache) bool { return true }), 3) + _, err = handler.lookupCache(db, JobCredential{Repo: testRepo}, []string{"wanted"}, "") + require.NoError(t, err) + require.NoError(t, handler.insertCache(db, &Cache{Repo: "o/b", Complete: true, Size: 2, UsedAt: time.Now().Unix()})) + require.NoError(t, db.Close()) + synctest.Wait() - assert.Equal(t, []string{wanted.Key}, keptKeys(t, handler, []*Cache{wanted, other}), "the entry just promised to a job survives, the next least recently used goes instead") + assert.Equal(t, []string{"wanted"}, keptKeys(t, handler, entries)) + }) } func TestHandler_PrefixUsesNewestReservationWithinSecond(t *testing.T) { diff --git a/act/common/git/fetch_action.go b/act/common/git/fetch_action.go index 0d67778e..5454f839 100644 --- a/act/common/git/fetch_action.go +++ b/act/common/git/fetch_action.go @@ -100,7 +100,7 @@ func fetchAction(ctx context.Context, input NewGitCloneExecutorInput) (string, s data, _ := os.ReadFile(record) sha, etag, _ := strings.Cut(string(data), "\n") switch { - case !isFullObjectID(sha): + case !isFullObjectID(sha) || verifyPin(ctx, filepath.Join(input.Dir, "git"), input.Ref, sha) != nil: sha, etag = "", "" case input.OfflineMode && exists(tree(sha)) && !exists(tree(sha)+treeSizes): return tree(sha), sha, nil // from an older runner, with no sizes to check, so offline mode uses it as before @@ -114,7 +114,7 @@ func fetchAction(ctx context.Context, input NewGitCloneExecutorInput) (string, s if err != nil && ctx.Err() == nil { common.Logger(ctx).Debugf("Cloning %s@%s: %v", input.URL, input.Ref, err) newEtag = "" - newSha, err = exportClone(ctx, input) + newSha, err = exportClone(ctx, input, err) } if err != nil { return "", "", err @@ -151,7 +151,7 @@ func downloadArchive(ctx context.Context, input NewGitCloneExecutorInput, sha, e return nil }} for attempt := 1; ; attempt++ { - newSha, newEtag, retryAfter, err := downloadArchiveOnce(ctx, client, archive.String(), input.Token, sha, etag, input.Dir) + newSha, newEtag, retryAfter, err := downloadArchiveOnce(ctx, client, archive.String(), input, sha, etag) if retryAfter == 0 || attempt == 3 || ctx.Err() != nil { return newSha, newEtag, err } @@ -164,7 +164,7 @@ func downloadArchive(ctx context.Context, input NewGitCloneExecutorInput, sha, e } } -func downloadArchiveOnce(ctx context.Context, client *http.Client, archive, token, sha, etag, dir string) (string, string, time.Duration, error) { +func downloadArchiveOnce(ctx context.Context, client *http.Client, archive string, input NewGitCloneExecutorInput, sha, etag string) (string, string, time.Duration, error) { request, err := http.NewRequestWithContext(ctx, http.MethodGet, archive, nil) if err != nil { return "", "", 0, err @@ -172,8 +172,8 @@ func downloadArchiveOnce(ctx context.Context, client *http.Client, archive, toke if etag != "" { request.Header.Set("If-None-Match", etag) } - if token != "" { - request.SetBasicAuth("token", token) + if input.Token != "" { + request.SetBasicAuth("token", input.Token) } response, err := client.Do(request) if err != nil { @@ -191,7 +191,7 @@ func downloadArchiveOnce(ctx context.Context, client *http.Client, archive, toke newEtag := response.Header.Get("ETag") gz, err := gzip.NewReader(response.Body) if err == nil { - sha, err = extractTree(ctx, gz, dir, !strings.HasSuffix(newEtag, `-false"`)) // Gitea's mark of an unprefixed archive + sha, err = extractTree(ctx, gz, input.Dir, input.Ref, !strings.HasSuffix(newEtag, `-false"`)) // Gitea's mark of an unprefixed archive } var netErr net.Error if errors.Is(err, io.ErrUnexpectedEOF) || errors.As(err, &netErr) { @@ -205,10 +205,13 @@ func downloadArchiveOnce(ctx context.Context, client *http.Client, archive, toke } } -func exportClone(ctx context.Context, input NewGitCloneExecutorInput) (string, error) { +func exportClone(ctx context.Context, input NewGitCloneExecutorInput, archiveErr error) (string, error) { clone := input clone.Dir = filepath.Join(input.Dir, "git") sha, _, err := resolveClone(ctx, clone) + if mismatch, ok := archiveErr.(*Error); ok && !strings.EqualFold(sha, mismatch.commit) { + return "", errors.Join(err, mismatch) + } if err != nil || treeIntact(input.Dir, sha) { return sha, err } @@ -216,11 +219,10 @@ func exportClone(ctx context.Context, input NewGitCloneExecutorInput) (string, e if err != nil { return "", err } - _, err = extractTree(ctx, bytes.NewReader(archive), input.Dir, false) - return sha, err + return extractTree(ctx, bytes.NewReader(archive), input.Dir, sha, false) } -func extractTree(ctx context.Context, archive io.Reader, dir string, strip bool) (string, error) { // into dir/, strip dropping the directory wrapping the files +func extractTree(ctx context.Context, archive io.Reader, dir, ref string, strip bool) (string, error) { // into dir/, strip dropping the directory wrapping the files temp, err := os.MkdirTemp(dir, "tmp-") if err != nil { return "", err @@ -246,8 +248,13 @@ func extractTree(ctx context.Context, archive io.Reader, dir string, strip bool) return "", err } if header.Typeflag == tar.TypeXGlobalHeader { - if sha = header.PAXRecords["comment"]; isFullObjectID(sha) && treeIntact(dir, sha) { - return sha, nil + if sha = header.PAXRecords["comment"]; isFullObjectID(sha) { + if err := verifyPin(ctx, "", ref, sha); err != nil { + return "", err + } + if treeIntact(dir, sha) { + return sha, nil + } } continue } diff --git a/act/common/git/fetch_action_test.go b/act/common/git/fetch_action_test.go index df4292b9..fec85a7f 100644 --- a/act/common/git/fetch_action_test.go +++ b/act/common/git/fetch_action_test.go @@ -79,6 +79,8 @@ func TestFetchAction(t *testing.T) { case archives == "redirect" && request.Host != mirror.Listener.Addr().String(): http.Redirect(writer, request, mirror.URL+request.URL.Path, http.StatusFound) return + case archives == "wrong commit": + ref = "main.tar.gz" } sha, ok := revisions[ref] if !ok { @@ -192,7 +194,7 @@ func TestFetchAction(t *testing.T) { } }) - t.Run("downloads, revalidates and follows a moved tag", func(t *testing.T) { + t.Run("revalidates a moved tag and rejects mismatched cached and archived commits", func(t *testing.T) { serve("prefixed", 0) input := newInput("v1") tree, sha, err := FetchAction(t.Context(), input) @@ -244,12 +246,29 @@ func TestFetchAction(t *testing.T) { assert.Empty(t, headers[0].Get("If-None-Match")) assert.Equal(t, fmt.Sprintf(`W/"%s-tar.gz-true"`, sha), headers[1].Get("If-None-Match")) assert.Equal(t, headers[1].Get("If-None-Match"), headers[2].Get("If-None-Match")) + + require.NoError(t, gitCmd("-C", remote, "tag", "-a", "pinned", "-m", "release", sha)) + input.Ref = gitRevParse(t, remote, "pinned") + for range 2 { + _, got, err := FetchAction(t.Context(), input) + require.NoError(t, err) + assert.Equal(t, sha, got) + } + _, headers = served() + require.Len(t, headers, 5) + + serve("wrong commit", 0) + input = newInput(sha) + _, _, err = FetchAction(t.Context(), input) + require.ErrorContains(t, err, sha) + require.ErrorContains(t, err, movedSha) + assert.NoDirExists(t, filepath.Join(input.Dir, movedSha)) }) t.Run("downloads a pinned commit once and rejects a short one", func(t *testing.T) { serve("prefixed", 0) sha := expectedSha - input := newInput(sha) + input := newInput(strings.ToUpper(sha)) for range 2 { tree, got, err := FetchAction(t.Context(), input) require.NoError(t, err) @@ -270,6 +289,9 @@ func TestFetchAction(t *testing.T) { input := newInput(sha) tree, _, err := FetchAction(t.Context(), input) require.NoError(t, err, mode) + if mode == "none" { + require.NoError(t, gitCmd("-C", filepath.Join(input.Dir, "git"), "replace", sha+":action.yml", sha+":run.sh")) + } yml := filepath.Join(tree, "action.yml") require.NoError(t, os.WriteFile(filepath.Join(tree, "trampoline.js"), nil, 0o644)) // the runner's own, no damage _, _, err = FetchAction(t.Context(), input) @@ -398,7 +420,7 @@ func TestExtractTreeConfinesEntries(t *testing.T) { require.NoError(t, writer.Close()) dir := t.TempDir() - _, err := extractTree(t.Context(), &archive, dir, false) + _, err := extractTree(t.Context(), &archive, dir, "", false) require.Error(t, err) assert.NoFileExists(t, filepath.Join(dir, "escape")) assert.NoFileExists(t, filepath.Join(outside, "escape")) @@ -448,7 +470,7 @@ func TestExtractTreeCopiesDeferredLinks(t *testing.T) { require.NoError(t, writer.Close()) dir := t.TempDir() - _, err := extractTree(t.Context(), &archive, dir, false) + _, err := extractTree(t.Context(), &archive, dir, sha, false) require.NoError(t, err) assert.True(t, treeIntact(dir, sha)) if test.text { @@ -493,7 +515,7 @@ func TestTreeIntactFindsNamesThatAreNotUTF8(t *testing.T) { require.NoError(t, writer.Close()) dir := t.TempDir() - _, err = extractTree(t.Context(), &archive, dir, false) + _, err = extractTree(t.Context(), &archive, dir, sha, false) require.NoError(t, err) require.FileExists(t, filepath.Join(dir, sha, "caf\xe9.js")) assert.True(t, treeIntact(dir, sha)) @@ -534,7 +556,7 @@ func TestExtractTreeCreatesLinksInPlatformOrder(t *testing.T) { t.Run(test.name, func(t *testing.T) { symlinkFallback = test.fallback created = nil - _, err := extractTree(t.Context(), bytes.NewReader(archive.Bytes()), t.TempDir(), false) + _, err := extractTree(t.Context(), bytes.NewReader(archive.Bytes()), t.TempDir(), "", false) require.NoError(t, err) assert.Equal(t, test.want, created) }) diff --git a/act/common/git/git.go b/act/common/git/git.go index 7eee1099..e4f56536 100644 --- a/act/common/git/git.go +++ b/act/common/git/git.go @@ -255,10 +255,10 @@ func resolveClone(ctx context.Context, input NewGitCloneExecutorInput) (string, return "", false, err } resolved, err := resolveRef(ctx, input.Dir, input.Ref) - if errors.Is(err, ErrShortRef) || (err != nil && input.OfflineMode) { - return "", false, err + if _, invalidRef := errors.AsType[*Error](err); invalidRef || input.OfflineMode { + return resolved, reused, err } - if !input.OfflineMode && (err != nil || (reused && !isFullHash(input.Ref, resolved))) { + if err != nil || (reused && !isFullObjectID(input.Ref)) { if err := fetch(ctx, input); err != nil { return "", false, err } @@ -340,20 +340,39 @@ func resolveRef(ctx context.Context, dir, ref string) (string, error) { } } sha, err := gitOutput(ctx, dir, "rev-parse", "--verify", ref+"^{commit}") - if err == nil && hexRefRegex.MatchString(ref) && len(sha) != len(ref) { + if err != nil { + return "", err + } + if err := verifyPin(ctx, dir, ref, sha); err != nil { + return "", err + } + if len(sha) != len(ref) && hexRefRegex.MatchString(ref) { return "", &Error{err: ErrShortRef, commit: sha} } - return sha, err + return sha, nil +} + +func verifyPin(ctx context.Context, gitDir, ref, sha string) error { + if strings.EqualFold(ref, sha) || !isFullObjectID(ref) { + return nil + } + if gitDir != "" && len(ref) == len(sha) { + objects, err := gitOutput(ctx, gitDir, "rev-parse", ref+"^{tag}", ref+"^{commit}") + if err == nil && strings.EqualFold(objects, ref+"\n"+sha) { + return nil + } + } + err := fmt.Errorf("action pinned to %s, got commit %s", ref, sha) + if gitDir != "" && len(ref) < len(sha) && strings.EqualFold(ref, sha[:len(ref)]) { + err = fmt.Errorf("%w: %w", err, ErrShortRef) + } + return &Error{err: err, commit: sha} } func isFullObjectID(ref string) bool { return ObjectFormat(ref) != "" } -func isFullHash(ref, resolved string) bool { - return isFullObjectID(ref) && len(ref) == len(resolved) -} - // ObjectFormat returns the object format of a full commit hash, empty for anything else. func ObjectFormat(sha string) string { switch { @@ -476,7 +495,7 @@ func runGitWithStdin(ctx context.Context, dir string, input *NewGitCloneExecutor for key, value := range ConfigEnv(config...) { cmd.Env = append(cmd.Env, key+"="+value) } - cmd.Env = append(cmd.Env, "GIT_TERMINAL_PROMPT=0") + cmd.Env = append(cmd.Env, "GIT_TERMINAL_PROMPT=0", "GIT_NO_REPLACE_OBJECTS=1") var treeKill *process.TreeKill if runtime.GOOS == "windows" { treeKill = process.NewTreeKill(cmd) // a cancelled git leaves its remote helper holding the repository otherwise diff --git a/act/common/git/git_test.go b/act/common/git/git_test.go index 825ec148..6149031c 100644 --- a/act/common/git/git_test.go +++ b/act/common/git/git_test.go @@ -488,6 +488,11 @@ func TestGitCloneExecutorShallow(t *testing.T) { require.NoError(t, clone(t.Context())) assert.FileExists(t, shallowMarker(dir)) require.ErrorIs(t, NewGitCloneExecutor(NewGitCloneExecutorInput{URL: remote, Ref: sha[:40], Dir: dir, Depth: 1, OfflineMode: true})(t.Context()), ErrShortRef) + tag := strings.Repeat("a", 40) + require.NoError(t, gitCmd("-C", dir, "tag", tag, sha)) + err := NewGitCloneExecutor(NewGitCloneExecutorInput{URL: remote, Ref: tag, Dir: dir, OfflineMode: true})(t.Context()) + require.ErrorContains(t, err, sha) + require.NotErrorIs(t, err, ErrShortRef) require.NoError(t, os.RemoveAll(remote)) require.NoError(t, clone(t.Context())) assert.Equal(t, sha, gitRevParse(t, dir, "HEAD")) diff --git a/act/container/docker_images.go b/act/container/docker_images.go index 6594db79..dd1b85be 100644 --- a/act/container/docker_images.go +++ b/act/container/docker_images.go @@ -11,6 +11,7 @@ import ( cerrdefs "github.com/containerd/errdefs" "github.com/moby/moby/client" + "github.com/moby/moby/client/pkg/versions" specs "github.com/opencontainers/image-spec/specs-go/v1" ) @@ -23,22 +24,30 @@ func ImageExistsLocally(ctx context.Context, imageName, platform string) (bool, } defer cli.Close() - inspectImage, err := cli.ImageInspect(ctx, imageName) + var requested *specs.Platform + if platform == "" { + if version, err := cli.ServerVersion(ctx, client.ServerVersionOptions{}); err == nil { + requested = &specs.Platform{OS: version.Os, Architecture: version.Arch} + } + } else if platform != "any" { + requested, err = parsePlatform(platform) + if err != nil { + return false, err + } + } + + inspectPlatform := requested + if versions.LessThan(cli.ClientVersion(), "1.49") { + inspectPlatform = nil + } + inspectImage, err := cli.ImageInspect(ctx, imageName, client.ImageInspectWithPlatform(inspectPlatform)) if cerrdefs.IsNotFound(err) { return false, nil } else if err != nil { return false, err } - if platform == "" || platform == "any" { - return true, nil - } - - requested, err := parsePlatform(platform) - if err != nil { - return false, err - } - return platformMatches(requested, &specs.Platform{OS: inspectImage.Os, Architecture: inspectImage.Architecture, Variant: inspectImage.Variant}), nil + return requested == nil || platformMatches(requested, &specs.Platform{OS: inspectImage.Os, Architecture: inspectImage.Architecture, Variant: inspectImage.Variant}), nil } func platformMatches(requested, image *specs.Platform) bool { @@ -49,8 +58,6 @@ func platformMatches(requested, image *specs.Platform) bool { return image.OS == requested.OS && image.Architecture == requested.Architecture && (requested.Variant == "" || requested.Variant == variant) } -// RemoveImage removes image from local store, the function is used to run different -// container image architectures func RemoveImage(ctx context.Context, imageName string, force, pruneChildren bool) (bool, error) { cli, err := GetDockerClient(ctx) if err != nil { diff --git a/act/container/docker_pull.go b/act/container/docker_pull.go index 00f81644..2d1a2000 100644 --- a/act/container/docker_pull.go +++ b/act/container/docker_pull.go @@ -7,6 +7,7 @@ package container import ( + "cmp" "context" "fmt" "strings" @@ -77,7 +78,7 @@ func NewDockerPullExecutor(input NewDockerPullExecutorInput) common.Executor { return nil } // a registry that is down should not fail a job whose image is already here - if exists, existsErr := ImageExistsLocally(ctx, input.Image, input.Platform); existsErr == nil && exists { + if exists, existsErr := ImageExistsLocally(ctx, input.Image, cmp.Or(input.Platform, "any")); existsErr == nil && exists { logger.Warnf("could not update image '%s' (%s), continuing with the local copy: %v", imageRef, input.Platform, err) return nil } diff --git a/act/container/docker_pull_test.go b/act/container/docker_pull_test.go index 6b5b0c24..aac0ae1d 100644 --- a/act/container/docker_pull_test.go +++ b/act/container/docker_pull_test.go @@ -8,7 +8,10 @@ package container import ( "io" + "net/http" + "net/http/httptest" "os" + "path" "path/filepath" "strings" "testing" @@ -94,6 +97,41 @@ func TestIsPinnedImage(t *testing.T) { assert.False(t, isPinnedImage("alpine:latest")) } +func TestDockerPullFallsBackToLocalPlatform(t *testing.T) { + t.Setenv("DOCKER_API_VERSION", "1.49") + t.Setenv("DOCKER_CONFIG", t.TempDir()) + t.Setenv("DOCKER_AUTH_CONFIG", "") + for _, image := range []string{"multiarch", "foreign", "no-version"} { + pulled := false + daemon := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + switch path.Base(request.URL.Path) { + case "version": + if image == "no-version" { + writer.WriteHeader(http.StatusForbidden) + } + _, _ = io.WriteString(writer, `{"Os":"linux","Arch":"s390x"}`) + case "json": + if platform := request.URL.Query().Get("platform"); platform == "" { + _, _ = io.WriteString(writer, `{"Os":"linux","Architecture":"arm64"}`) + } else if image == "multiarch" { + assert.JSONEq(t, `{"os":"linux","architecture":"s390x"}`, platform) + _, _ = io.WriteString(writer, `{"Os":"linux","Architecture":"s390x"}`) + } else { + writer.WriteHeader(http.StatusNotFound) + } + case "create": + pulled = true + writer.WriteHeader(http.StatusServiceUnavailable) + } + })) + t.Setenv("DOCKER_HOST", daemon.URL) + err := NewDockerPullExecutor(NewDockerPullExecutorInput{Image: image})(t.Context()) + daemon.Close() + require.NoError(t, err, image) + assert.Equal(t, image == "foreign", pulled, image) + } +} + // The pull path reports a failure the daemon sent mid-stream, so it must carry the reason // whichever of the two shapes the daemon used. func TestLogDockerResponseError(t *testing.T) { diff --git a/act/container/docker_run.go b/act/container/docker_run.go index 07223cf5..b6047a2f 100644 --- a/act/container/docker_run.go +++ b/act/container/docker_run.go @@ -334,12 +334,16 @@ func (cr *containerReference) UpdateFromImageEnv(env *map[string]string) common. } func (cr *containerReference) Exec(command []string, env map[string]string, user, workdir string) common.Executor { - return common.NewPipelineExecutor( + run := common.NewPipelineExecutor( common.NewInfoExecutor("docker exec cmd=[%s] user=%s workdir=%s", strings.Join(command, " "), user, workdir), cr.connect(), cr.find(), cr.exec(command, env, user, workdir), - ).IfNot(common.Dryrun) + ) + return common.Executor(func(ctx context.Context) error { + err := run(ctx) + return cmp.Or(context.Cause(ctx), err) + }).IfNot(common.Dryrun) } func (cr *containerReference) Remove() common.Executor { @@ -436,17 +440,7 @@ func RunnerArch(ctx context.Context) string { return "" } - archMapper := map[string]string{ - "x86_64": "X64", - "amd64": "X64", - "386": "X86", - "aarch64": "ARM64", - "arm64": "ARM64", - } - if arch, ok := archMapper[info.Architecture]; ok { - return arch - } - return info.Architecture + return goArchToActionArch(info.Architecture) } func (cr *containerReference) targetOS(ctx context.Context) string { diff --git a/act/container/docker_run_test.go b/act/container/docker_run_test.go index 8bfcd4a2..a22e0998 100644 --- a/act/container/docker_run_test.go +++ b/act/container/docker_run_test.go @@ -204,7 +204,7 @@ func (m *mockConn) Close() (err error) { } func TestDockerExecAbort(t *testing.T) { - ctx, cancel := context.WithCancel(t.Context()) + ctx, cancel := context.WithCancelCause(t.Context()) reader := &interruptReader{started: make(chan struct{}), interrupted: make(chan struct{}), stopped: make(chan struct{})} conn := &mockConn{} @@ -213,30 +213,25 @@ func TestDockerExecAbort(t *testing.T) { Return(1, nil) client := &mockDockerClient{} + client.On("ContainerInspect", ctx, "123", mobyclient.ContainerInspectOptions{}).Return(mobyclient.ContainerInspectResult{}, nil) client.On("ExecCreate", ctx, "123", mock.AnythingOfType("client.ExecCreateOptions")).Return(mobyclient.ExecCreateResult{ID: "id"}, nil) client.On("ExecAttach", ctx, "id", mock.AnythingOfType("client.ExecAttachOptions")).Return(mobyclient.ExecAttachResult{ Conn: conn, Reader: bufio.NewReader(reader), }, nil) - cr := &containerReference{ - id: "123", - cli: client, - input: &NewContainerInput{}, - } - + run := (&containerReference{id: "123", cli: client, input: &NewContainerInput{}}).Exec(nil, nil, "", "") channel := make(chan error) - go func() { - channel <- cr.exec([]string{""}, map[string]string{}, "user", "workdir")(ctx) + channel <- run(ctx) }() <-reader.started - cancel() + cancel(assert.AnError) - err := <-channel + require.ErrorIs(t, <-channel, assert.AnError) <-reader.stopped - assert.ErrorIs(t, err, context.Canceled) //nolint:testifylint // pre-existing issue from nektos/act + require.ErrorIs(t, run(ctx), assert.AnError) conn.AssertExpectations(t) client.AssertExpectations(t) @@ -521,7 +516,7 @@ func TestRunnerArchCachedPerRun(t *testing.T) { writer.Header().Set("API-Version", "1.47") if strings.HasSuffix(request.URL.Path, "/info") { infos.Add(1) - _, _ = io.WriteString(writer, `{"Architecture":"aarch64"}`) + _, _ = io.WriteString(writer, `{"Architecture":"armv7l"}`) } })) t.Cleanup(daemon.Close) @@ -530,10 +525,10 @@ func TestRunnerArchCachedPerRun(t *testing.T) { run := WithRunnerArch(t.Context()) var lookups sync.WaitGroup for range 4 { - lookups.Go(func() { assert.Equal(t, "ARM64", extensions.GetRunnerContext(run)["arch"]) }) + lookups.Go(func() { assert.Equal(t, "ARM", extensions.GetRunnerContext(run)["arch"]) }) } lookups.Wait() - assert.Equal(t, "ARM64", extensions.GetRunnerContext(t.Context())["arch"]) + assert.Equal(t, "ARM", extensions.GetRunnerContext(t.Context())["arch"]) assert.EqualValues(t, 2, infos.Load()) } diff --git a/act/container/docker_stub.go b/act/container/docker_stub.go index 30e9e403..e7bd7a30 100644 --- a/act/container/docker_stub.go +++ b/act/container/docker_stub.go @@ -33,8 +33,6 @@ func ImageExistsLocally(ctx context.Context, imageName, platform string) (bool, return false, errors.ErrUnsupported } -// RemoveImage removes image from local store, the function is used to run different -// container image architectures func RemoveImage(ctx context.Context, imageName string, force, pruneChildren bool) (bool, error) { return false, errors.ErrUnsupported } diff --git a/act/container/host_environment.go b/act/container/host_environment.go index 8aa3f8ce..401de12c 100644 --- a/act/container/host_environment.go +++ b/act/container/host_environment.go @@ -349,15 +349,8 @@ func (e *HostEnvironment) Exec(command []string, env map[string]string, _user, w func (e *HostEnvironment) ExecWithCmdLine(command []string, cmdline string, env map[string]string, workdir string) common.Executor { return func(ctx context.Context) error { - if err := e.exec(ctx, command, cmdline, env, workdir); err != nil { - select { - case <-ctx.Done(): - return fmt.Errorf("this step has been cancelled: %w", err) - default: - return err - } - } - return nil + err := e.exec(ctx, command, cmdline, env, workdir) + return cmp.Or(context.Cause(ctx), err) } } @@ -483,12 +476,10 @@ func (*HostEnvironment) JoinPathVariable(paths ...string) string { // https://docs.github.com/en/actions/learn-github-actions/contexts#runner-context func goArchToActionArch(arch string) string { return cmp.Or(map[string]string{ - "x86_64": "X64", - "amd64": "X64", - "386": "X86", - "arm": "ARM", - "aarch64": "ARM64", - "arm64": "ARM64", + "386": "X86", "i386": "X86", "i686": "X86", + "amd64": "X64", "x86_64": "X64", + "arm": "ARM", "armv6l": "ARM", "armv7l": "ARM", + "arm64": "ARM64", "aarch64": "ARM64", }[arch], arch) } diff --git a/act/container/host_environment_test.go b/act/container/host_environment_test.go index 49ae0d46..90b685cc 100644 --- a/act/container/host_environment_test.go +++ b/act/container/host_environment_test.go @@ -28,7 +28,9 @@ var _ ExecutionsEnvironment = &HostEnvironment{} func TestActionPlatformNames(t *testing.T) { assert.Equal(t, []string{"Linux", "macOS", "Windows", "FreeBSD"}, []string{goOsToActionOs("linux"), goOsToActionOs("darwin"), goOsToActionOs("windows"), goOsToActionOs("freebsd")}) - assert.Equal(t, []string{"X86", "X64", "ARM", "ARM64"}, []string{goArchToActionArch("386"), goArchToActionArch("amd64"), goArchToActionArch("arm"), goArchToActionArch("arm64")}) + for arch, want := range map[string]string{"386": "X86", "i686": "X86", "amd64": "X64", "arm": "ARM", "armv6l": "ARM", "arm64": "ARM64", "riscv64": "riscv64"} { + assert.Equal(t, want, goArchToActionArch(arch), arch) + } } func TestCopyDir(t *testing.T) { @@ -124,6 +126,12 @@ func TestHostEnvironmentExecExitCode(t *testing.T) { } } +func TestHostEnvironmentExecDeadline(t *testing.T) { + ctx, cancel := context.WithTimeoutCause(t.Context(), 0, assert.AnError) + defer cancel() + require.ErrorIs(t, (&HostEnvironment{}).Exec([]string{os.Args[0], "-test.run=^$"}, nil, "", "")(ctx), assert.AnError) +} + func TestHostEnvironmentAllocatePTY(t *testing.T) { t.Parallel() if runtime.GOOS == "windows" { diff --git a/act/runner/action.go b/act/runner/action.go index 6436841c..117b5e4e 100644 --- a/act/runner/action.go +++ b/act/runner/action.go @@ -28,6 +28,8 @@ import ( _ "embed" + "gitea.dev/actionslib/pkg/expreval" + "gitea.dev/actionslib/pkg/exprparser" "gitea.dev/actionslib/pkg/model" "github.com/kballard/go-shellquote" ) @@ -36,7 +38,7 @@ type actionStep interface { step getActionModel() *model.Action - getCompositeRunContext(context.Context) (*RunContext, error) + getCompositeRunContext(ctx context.Context, inputs map[string]string) *RunContext getCompositeSteps() *compositeSteps } @@ -46,7 +48,7 @@ type actionYamlReader func(filename string) (io.Reader, io.Closer, error) type fileWriter func(filename string, data []byte, perm fs.FileMode) error -type runAction func(step actionStep, actionDir string, remoteAction *remoteAction) common.Executor +type runAction func(step actionStep) common.Executor //go:embed res/trampoline.js var trampoline string @@ -59,77 +61,49 @@ var ( ) func readActionImpl(ctx context.Context, step *model.Step, actionDir, actionPath string, readFile actionYamlReader, writeFile fileWriter) (*model.Action, error) { - logger := common.Logger(ctx) - allErrors := []error{} - addError := func(fileName string, err error) { + var readErrors []error + for _, filename := range []string{"action.yml", "action.yaml", "Dockerfile", "dockerfile"} { + manifest := strings.HasPrefix(filename, "action.") + reader, closer, err := readFile(filename) if err != nil { - allErrors = append(allErrors, fmt.Errorf("failed to read '%s' from action '%s' with path '%s' of step %w", fileName, step.String(), actionPath, err)) - } else { - // One successful read, clear error state - allErrors = nil - } - } - reader, closer, err := readFile("action.yml") - addError("action.yml", err) - if os.IsNotExist(err) { - reader, closer, err = readFile("action.yaml") - addError("action.yaml", err) - if os.IsNotExist(err) { - dockerfile := "Dockerfile" - _, closer, err := readFile(dockerfile) - addError(dockerfile, err) + readErrors = append(readErrors, fmt.Errorf("failed to read '%s' from action '%s' with path '%s' of step %w", filename, step.String(), actionPath, err)) if os.IsNotExist(err) { - dockerfile = "dockerfile" - _, closer, err = readFile(dockerfile) - addError(dockerfile, err) + continue } - if err == nil { - closer.Close() - action := &model.Action{ - Name: "(Synthetic)", - Runs: model.ActionRuns{ - Using: "docker", - Image: dockerfile, - }, - } - logger.Debugf("Using synthetic action %v for %s", action, dockerfile) - return action, nil - } - if val, ok := step.With["args"]; ok { - if err := writeFile(filepath.Join(actionDir, actionPath, "trampoline.js"), []byte(trampoline), 0o644); err != nil { - return nil, err - } - action := &model.Action{ - Name: "(Synthetic)", - Inputs: map[string]model.Input{ - "args": {}, - "cwd": { - Description: "(Actual working directory)", - Required: false, - Default: filepath.Join(actionDir, actionPath), - }, - "command": { - Description: "(Actual program)", - Required: false, - Default: val, - }, - }, - Runs: model.ActionRuns{ - Using: "node12", - Main: "trampoline.js", - }, - } - logger.Debugf("Using synthetic action %v", action) - return action, nil + if manifest { + return nil, errors.Join(readErrors...) } + break } + defer closer.Close() + if manifest { + action, err := model.ReadAction(reader) + if err != nil { + return nil, &fs.PathError{Op: "Failed to load", Path: filepath.Join(actionDir, actionPath, filename), Err: err} + } + return action, nil + } + action := &model.Action{Name: "(Synthetic)", Runs: model.ActionRuns{Using: model.ActionRunsUsingDocker, Image: filename}} + common.Logger(ctx).Debugf("Using synthetic action %v for %s", action, filename) + return action, nil } - if allErrors != nil { - return nil, errors.Join(allErrors...) + if val, ok := step.With["args"]; ok { + if err := writeFile(filepath.Join(actionDir, actionPath, "trampoline.js"), []byte(trampoline), 0o644); err != nil { + return nil, err + } + action := &model.Action{ + Name: "(Synthetic)", + Inputs: map[string]model.Input{ + "args": {}, + "cwd": {Description: "(Actual working directory)", Default: filepath.Join(actionDir, actionPath)}, + "command": {Description: "(Actual program)", Default: val}, + }, + Runs: model.ActionRuns{Using: model.ActionRunsUsingNode12, Main: "trampoline.js"}, + } + common.Logger(ctx).Debugf("Using synthetic action %v", action) + return action, nil } - defer closer.Close() - - return model.ReadAction(reader) + return nil, errors.Join(readErrors...) } func maybeCopyToActionDir(ctx context.Context, step actionStep, actionDir, actionPath, containerActionDir string) error { @@ -167,81 +141,81 @@ func maybeCopyToActionDir(ctx context.Context, step actionStep, actionDir, actio return rc.JobContainer.Copy(containerActionDirCopy, patched...)(ctx) } -func runActionImpl(step actionStep, actionDir string, remoteAction *remoteAction) common.Executor { - rc := step.getRunContext() - stepModel := step.getStepModel() - +func runActionImpl(step actionStep) common.Executor { return func(ctx context.Context) error { - logger := common.Logger(ctx) - actionPath := "" - if remoteAction != nil { - actionPath = remoteAction.Path - } - - action := step.getActionModel() - + rc := step.getRunContext() rc.withGithubEnv(ctx, getStepGithubContext(ctx, step), *step.getEnv()) populateEnvsFromSavedState(step.getEnv(), step, rc) - if err := populateEnvsFromInput(ctx, step, action); err != nil { - return err - } - warnUnexpectedInputs(ctx, action, stepModel.With) - printRunActionHeader(ctx, stepModel, action, *step.getEnv(), rc) - - actionName, containerActionDir := getContainerActionPaths(step) - - logger.Debugf("type=%v actionDir=%s actionPath=%s workdir=%s actionCacheDir=%s actionName=%s containerActionDir=%s", stepModel.Type(), actionDir, actionPath, rc.Config.Workdir, rc.ActionCacheDir(), actionName, containerActionDir) - - x := action.Runs.Using - switch { - case x.IsNode(): - if err := maybeCopyToActionDir(ctx, step, actionDir, actionPath, containerActionDir); err != nil { - return err - } - containerArgs := nodeActionCommand(container.JoinPath(containerActionDir, action.Runs.Main)) - logger.Debugf("executing remote job container: %s", containerArgs) - - rc.ApplyExtraPath(ctx, step.getEnv()) - - return rc.JobContainer.Exec(containerArgs, *step.getEnv(), "", "")(ctx) - case x.IsDocker(): - location := path.Join(actionDir, actionPath) - if remoteAction == nil { - location = containerActionDir - } - return execAsDocker(ctx, step, actionName, actionDir, location, remoteAction == nil, stepStageMain) - case x.IsComposite(): - if err := maybeCopyToActionDir(ctx, step, actionDir, actionPath, containerActionDir); err != nil { - return err - } - - return execAsComposite(step)(ctx) - case x == model.ActionRunsUsingGo: - if err := maybeCopyToActionDir(ctx, step, actionDir, actionPath, containerActionDir); err != nil { - return err - } - - rc.ApplyExtraPath(ctx, step.getEnv()) - - execFileName := action.Runs.Main + ".out" - return common.NewPipelineExecutor( - rc.JobContainer.Exec([]string{"go", "build", "-o", execFileName, action.Runs.Main}, *step.getEnv(), "", containerActionDir), - rc.JobContainer.Exec([]string{container.JoinPath(containerActionDir, execFileName)}, *step.getEnv(), "", ""), - )(ctx) - default: - return fmt.Errorf("the runs.using key must be one of: %v, got %s", []string{ - model.ActionRunsUsingDocker, - model.ActionRunsUsingNode12, - model.ActionRunsUsingNode16, - model.ActionRunsUsingNode20, - model.ActionRunsUsingNode24, - model.ActionRunsUsingComposite, - model.ActionRunsUsingGo, - }, action.Runs.Using) - } + return runActionStage(ctx, step, stepStageMain) } } +func runActionStage(ctx context.Context, step actionStep, stage stepStage) error { + rc := step.getRunContext() + stepModel := step.getStepModel() + action := step.getActionModel() + inputs, err := rc.resolveActionInputs(ctx, step, action) + if err != nil { + return err + } + applyActionInputs(step, inputs) + if stage == stepStageMain { + warnUnexpectedInputs(ctx, action, stepModel.With) + } + if stage == stepStagePost { + populateEnvsFromSavedState(step.getEnv(), step, rc) + } else { + printRunActionHeader(ctx, stepModel, action, *step.getEnv(), rc) + } + + actionDir, actionPath := actionSourcePaths(step) + actionName, containerActionDir := getContainerActionPaths(step) + if stage == stepStageMain { + common.Logger(ctx).Debugf("type=%v actionDir=%s actionPath=%s workdir=%s actionCacheDir=%s actionName=%s containerActionDir=%s", stepModel.Type(), actionDir, actionPath, rc.Config.Workdir, rc.ActionCacheDir(), actionName, containerActionDir) + } + using := action.Runs.Using + switch { + case using.IsDocker(): + return execAsDocker(ctx, step, stage, inputs, actionName, containerActionDir) + case using.IsNode(), using.IsComposite(), using == model.ActionRunsUsingGo: + if stage != stepStagePost { + if err := maybeCopyToActionDir(ctx, step, actionDir, actionPath, containerActionDir); err != nil { + return err + } + } + if using.IsComposite() { + return execAsComposite(ctx, step, inputs) + } + return runActionScript(ctx, step, containerActionDir, [...]string{action.Runs.Pre, action.Runs.Main, action.Runs.Post}[stage]) + default: + return fmt.Errorf("the runs.using key must be one of: %v, got %s", []string{ + model.ActionRunsUsingDocker, + model.ActionRunsUsingNode12, + model.ActionRunsUsingNode16, + model.ActionRunsUsingNode20, + model.ActionRunsUsingNode24, + model.ActionRunsUsingComposite, + model.ActionRunsUsingGo, + }, using) + } +} + +func runActionScript(ctx context.Context, step actionStep, actionDir, script string) error { + rc := step.getRunContext() + env := step.getEnv() + rc.ApplyExtraPath(ctx, env) + if step.getActionModel().Runs.Using.IsNode() { + args := nodeActionCommand(container.JoinPath(actionDir, script)) + common.Logger(ctx).Debugf("executing remote job container: %s", args) + return rc.JobContainer.Exec(args, *env, "", "")(ctx) + } + executable := script + ".out" + return common.NewPipelineExecutor( + rc.JobContainer.Exec([]string{"go", "build", "-o", executable, script}, *env, "", actionDir), + rc.JobContainer.Exec([]string{container.JoinPath(actionDir, executable)}, *env, "", ""), + )(ctx) +} + // /var/run is a symlink, so without the flag node's import.meta.url differs from argv[1], which ESM actions compare. func nodeActionCommand(script string) []string { return []string{"node", "--preserve-symlinks-main", script} @@ -291,115 +265,76 @@ func (rc *RunContext) dockerActionImage(ctx context.Context, step actionStep, ac return image } -// TODO: break out parts of function to reduce complexicity -func execAsDocker(ctx context.Context, step actionStep, actionName, actionDir, basedir string, localAction bool, stage stepStage) error { - logger := common.Logger(ctx) +func execAsDocker(ctx context.Context, step actionStep, stage stepStage, inputs map[string]string, actionName, buildDir string) error { rc := step.getRunContext() if rc.isWindowsHost() { return errWindowsHostContainer } - action := step.getActionModel() if rc.kubernetes { return errKubernetesDocker } - var prepImage common.Executor - var image string - forcePull := false - if after, ok := strings.CutPrefix(action.Runs.Image, "docker://"); ok { - image = after - // Apply forcePull only for prebuild docker images - forcePull = rc.Config.ForcePull - } else { - image = rc.dockerActionImage(ctx, step, actionName, localAction) - contextDir, fileName := filepath.Split(filepath.Join(basedir, action.Runs.Image)) - - anyArchExists, err := ContainerImageExistsLocally(ctx, image, "any") - if err != nil { - return err - } - - correctArchExists := anyArchExists - if anyArchExists && rc.Config.ContainerArchitecture != "" && rc.Config.ContainerArchitecture != "any" { - correctArchExists, err = ContainerImageExistsLocally(ctx, image, rc.Config.ContainerArchitecture) - if err != nil { - return err - } - } - - if anyArchExists && !correctArchExists { - wasRemoved, err := container.RemoveImage(ctx, image, true, true) - if err != nil { - return err - } - if !wasRemoved { - return fmt.Errorf("failed to remove image '%s'", image) - } - } - - if !correctArchExists || rc.Config.ForceRebuild { - logger.Debugf("image '%s' for architecture '%s' will be built from context '%s", image, rc.Config.ContainerArchitecture, contextDir) - prepImage = common.Executor(func(ctx context.Context) error { - input := container.NewDockerBuildExecutorInput{ - ContextDir: contextDir, - Dockerfile: fileName, - ImageTag: image, - Platform: rc.Config.ContainerArchitecture, - BuildArgs: rc.proxyBuildArgs(), - Stdout: common.NewLineWriter(rawLogLine(ctx)), - } - if localAction { - input.Dockerignore, _ = readSingleFileFromContainerArchive(ctx, rc.JobContainer, contextDir+"/.dockerignore", 1<<20) - buildContext, err := rc.JobContainer.GetContainerArchive(ctx, contextDir+"/.") - if err != nil { - return err - } - defer buildContext.Close() - input.BuildContext = buildContext - } else { - unlock, err := git.AcquireCloneLock(ctx, actionDir) // held across the whole build, the daemon drains contextDir lazily - if err != nil { - return err - } - defer unlock() - } - return ContainerNewDockerBuildExecutor(input)(ctx) - }).Retry(3) - } else { - logger.Debugf("image '%s' for architecture '%s' already exists", image, rc.Config.ContainerArchitecture) - } + action := step.getActionModel() + remote, isRemote := step.(*stepActionRemote) + image, prebuilt := strings.CutPrefix(action.Runs.Image, "docker://") + if !prebuilt { + image = rc.dockerActionImage(ctx, step, actionName, !isRemote) } - ee, err := evalDockerEnv(ctx, step, action) + cmd, err := evalDockerArgsAndEnv(ctx, step, action, inputs) if err != nil { return err } - var cmd []string - if action.Runs.Args != nil { - // a fresh slice, the manifest is evaluated again for every stage - cmd = make([]string, len(action.Runs.Args)) - for i, v := range action.Runs.Args { - if cmd[i], err = ee.Interpolate(ctx, v); err != nil { - return fmt.Errorf("unable to interpolate runs.args: %w", err) - } - } - } else { - cmd, err = shellquote.Split(stepInput(step.getStepModel(), "args")) - if err != nil { - return err - } - } entrypoint, err := dockerEntrypoint(step, stage) if err != nil { return err } - stepContainer := newStepContainer(ctx, step, image, cmd, entrypoint, rc.Config.ContainerOptions) - return common.NewPipelineExecutor( - prepImage, - stepContainer.Pull(forcePull), - stepContainer.Remove(), - stepContainer.Create(rc.Config.ContainerCapAdd, rc.Config.ContainerCapDrop), - stepContainer.Start(true), - ).Finally(stepContainer.Close())(ctx) + containerInput := stepContainerInput(ctx, step, image, cmd, entrypoint, rc.Config.ContainerOptions) + stepContainer := ContainerNewContainer(containerInput) + if prebuilt { + return rc.runStepContainer(ctx, stepContainer, nil, rc.Config.ForcePull) + } + + platform := containerInput.Platform + exists, err := ContainerImageExistsLocally(ctx, image, platform) + if err != nil { + return err + } + if exists && !rc.Config.ForceRebuild { + common.Logger(ctx).Debugf("image '%s' for architecture '%s' already exists", image, platform) + return rc.runStepContainer(ctx, stepContainer, nil, false) + } + if isRemote { + buildDir = path.Join(remote.actionDir, remote.remoteAction.Path) + } + contextDir, filename := filepath.Split(filepath.Join(buildDir, action.Runs.Image)) + common.Logger(ctx).Debugf("image '%s' for architecture '%s' will be built from context '%s'", image, platform, contextDir) + buildImage := common.Executor(func(ctx context.Context) error { + input := container.NewDockerBuildExecutorInput{ + ContextDir: contextDir, + Dockerfile: filename, + ImageTag: image, + Platform: platform, + BuildArgs: rc.proxyBuildArgs(), + Stdout: common.NewLineWriter(rawLogLine(ctx)), + } + if isRemote { + unlock, err := git.AcquireCloneLock(ctx, remote.actionDir) // held across the whole build, the daemon drains contextDir lazily + if err != nil { + return err + } + defer unlock() + } else { + input.Dockerignore, _ = readSingleFileFromContainerArchive(ctx, rc.JobContainer, contextDir+"/.dockerignore", 1<<20) + buildContext, err := rc.JobContainer.GetContainerArchive(ctx, contextDir+"/.") + if err != nil { + return err + } + defer buildContext.Close() + input.BuildContext = buildContext + } + return ContainerNewDockerBuildExecutor(input)(ctx) + }) + return rc.runStepContainer(ctx, stepContainer, buildImage.Retry(3), false) } // dockerEntrypoint returns the entrypoint the action's image runs with for the given @@ -428,40 +363,31 @@ func dockerEntrypoint(step actionStep, stage stepStage) ([]string, error) { return shellquote.Split(entrypoint) } -// evalDockerEnv returns an evaluator bound to the environment it installed. -func evalDockerEnv(ctx context.Context, step step, action *model.Action) (*expressionEvaluator, error) { - rc := step.getRunContext() - - var err error - inputs := make(map[string]string) - providedInputs := make(map[string]bool, len(step.getStepModel().With)) - for key := range step.getStepModel().With { - providedInputs[strings.ToLower(key)] = true - } - eval := rc.NewStepExpressionEvaluator(ctx, step) - for k, input := range action.Inputs { - if providedInputs[strings.ToLower(k)] { - continue - } - 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) - } - } - mergeIntoMap(step, step.getEnv(), inputs, step.getStepModel().With) - - ee := rc.NewActionInputsExpressionEvaluator(ctx, step) +func evalDockerArgsAndEnv(ctx context.Context, step step, action *model.Action, inputs map[string]string) ([]string, error) { + env := step.getEnv() + ee := newActionInputsExpressionEvaluator(inputs) runsEnv := make(map[string]string, len(action.Runs.Env)) - for k, v := range action.Runs.Env { - if runsEnv[k], err = ee.Interpolate(ctx, v); err != nil { - return nil, fmt.Errorf("unable to interpolate env %s: %w", k, err) + var err error + for name, expression := range action.Runs.Env { + if runsEnv[name], err = ee.Interpolate(ctx, expression); err != nil { + return nil, fmt.Errorf("unable to interpolate env %s: %w", name, err) } } - mergeIntoMap(step, step.getEnv(), runsEnv, maps.Clone(*step.getEnv())) - aliasGiteaEnv(*step.getEnv()) - return ee, nil + *env = step.getRunContext().mergeEnv(runsEnv, *env, inputs) + aliasGiteaEnv(*env) + if action.Runs.Args == nil { + return shellquote.Split(stepInput(step.getStepModel(), "args")) + } + cmd := make([]string, len(action.Runs.Args)) + for i, expression := range action.Runs.Args { + if cmd[i], err = ee.Interpolate(ctx, expression); err != nil { + return nil, fmt.Errorf("unable to interpolate runs.args: %w", err) + } + } + return cmd, nil } -func newStepContainer(ctx context.Context, step step, image string, cmd, entrypoint []string, runnerOptions string) container.Container { +func stepContainerInput(ctx context.Context, step step, image string, cmd, entrypoint []string, runnerOptions string) *container.NewContainerInput { rc := step.getRunContext() logWriter := rc.commandLogWriter(ctx) envList := make([]string, 0) @@ -475,11 +401,11 @@ func newStepContainer(ctx context.Context, step step, image string, cmd, entrypo envList = append(envList, rc.runnerEnv(ctx)...) binds, mounts, _ := rc.GetBindsAndMounts(ctx) - networkMode := "container:" + rc.jobContainerName() + networkMode := rc.topLevelRunContext().jobNetworkName if rc.IsHostEnv() { networkMode = "default" } - return ContainerNewContainer(&container.NewContainerInput{ + return &container.NewContainerInput{ Cmd: cmd, Entrypoint: entrypoint, WorkingDir: rc.JobContainer.ToContainerPath(rc.Config.Workdir), @@ -498,7 +424,7 @@ func newStepContainer(ctx context.Context, step step, image string, cmd, entrypo AutoRemove: true, ValidVolumes: rc.validVolumes(), AllocatePTY: rc.Config.AllocatePTY, - }) + } } func populateEnvsFromSavedState(env *map[string]string, step actionStep, rc *RunContext) { @@ -511,19 +437,30 @@ func inputEnvKey(inputID string) string { return "INPUT_" + inputEnvPattern.ReplaceAllString(strings.ToUpper(inputID), "_") } -func populateEnvsFromInput(ctx context.Context, step step, action *model.Action) error { - env := step.getEnv() - eval := step.getRunContext().NewStepExpressionEvaluator(ctx, step) - for inputID, input := range action.Inputs { - envKey := inputEnvKey(inputID) - if _, ok := (*env)[envKey]; !ok { +func (rc *RunContext) resolveActionInputs(ctx context.Context, step step, action *model.Action) (map[string]string, error) { + provided := step.getStepModel().With + inputs := mergeMaps(provided) + var evaluator *expressionEvaluator + eval := expreval.New(func(expression string, statusCheck exprparser.DefaultStatusCheck) (any, error) { + if evaluator == nil { + evaluator = &expressionEvaluator{interpreter: exprparser.NewInterpeter( + rc.actionDefaultEnvironment(ctx, getStepGithubContext(ctx, step), rc.getJobContext()), exprparser.Config{Context: "step"})} + } + return evaluator.evaluate(ctx, expression, statusCheck) + }) + for name, input := range action.Inputs { + if _, ok := common.LookupFold(provided, name, true); !ok { 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) + if inputs[name], err = eval.Interpolate(input.Default); err != nil { + return nil, fmt.Errorf("unable to interpolate the default of input %s: %w", name, err) } } } - return nil + return inputs, nil +} + +func applyActionInputs(step step, inputs map[string]string) { + mergeIntoMap(step, step.getEnv(), (&model.Step{With: inputs}).GetEnv()) } func stepInput(step *model.Step, name string) string { @@ -588,108 +525,18 @@ func shouldRunPreStep(step actionStep) common.Conditional { func hasPreStep(step actionStep) common.Conditional { return func(ctx context.Context) bool { - action := step.getActionModel() - // a pre stage evaluates `with` before earlier steps run, so only a composite nesting actions gets one - return (action.Runs.Using.IsComposite() && slices.ContainsFunc(action.Runs.Steps, func(compositeStep model.Step) bool { return compositeStep.Uses != "" })) || - (action.Runs.Using.IsNode() && - action.Runs.Pre != "") || - (action.Runs.Using.IsDocker() && - action.Runs.PreEntrypoint != "") || - (action.Runs.Using == model.ActionRunsUsingGo && - action.Runs.Pre != "") + runs := &step.getActionModel().Runs + return (runs.Using.IsComposite() && slices.ContainsFunc(runs.Steps, func(child model.Step) bool { return child.Uses != "" })) || // pre evaluates with before preceding steps produce outputs + (runs.Using.IsDocker() && runs.PreEntrypoint != "") || + ((runs.Using.IsNode() || runs.Using == model.ActionRunsUsingGo) && runs.Pre != "") } } -// actionStagePaths resolves where a step's action lives and where the job container sees -// it, for the pre and post stage. -func actionStagePaths(step actionStep) (actionDir, actionPath, actionName, containerActionDir string) { - rc := step.getRunContext() - stepModel := step.getStepModel() - +func actionSourcePaths(step actionStep) (actionDir, actionPath string) { if sar, ok := step.(*stepActionRemote); ok { - actionDir = sar.actionDir - actionPath = sar.remoteAction.Path + return sar.actionDir, sar.remoteAction.Path } else { - actionDir = filepath.Join(rc.Config.Workdir, stepModel.Uses) - } - - actionName, containerActionDir = getContainerActionPaths(step) - return actionDir, actionPath, actionName, containerActionDir -} - -// execDockerActionStage runs a docker action's image for its pre or post stage. -func execDockerActionStage(ctx context.Context, step actionStep, stage stepStage) error { - actionDir, actionPath, actionName, containerActionDir := actionStagePaths(step) - - _, remote := step.(*stepActionRemote) - location := containerActionDir - if remote { - location = path.Join(actionDir, actionPath) - } - return execAsDocker(ctx, step, actionName, actionDir, location, !remote, stage) -} - -func runPreStep(step actionStep) common.Executor { - return func(ctx context.Context) error { - logger := common.Logger(ctx) - logger.Debugf("run pre step for '%s'", step.getStepModel()) - - rc := step.getRunContext() - action := step.getActionModel() - - actionDir, actionPath, _, containerActionDir := actionStagePaths(step) - - x := action.Runs.Using - if !x.IsComposite() { - // defaults in pre steps were missing, however provided inputs are available - if err := populateEnvsFromInput(ctx, step, action); err != nil { - return err - } - } - printRunActionHeader(ctx, step.getStepModel(), action, *step.getEnv(), rc) - switch { - case x.IsNode(): - if err := maybeCopyToActionDir(ctx, step, actionDir, actionPath, containerActionDir); err != nil { - return err - } - - containerArgs := nodeActionCommand(container.JoinPath(containerActionDir, action.Runs.Pre)) - logger.Debugf("executing remote job container: %s", containerArgs) - - rc.ApplyExtraPath(ctx, step.getEnv()) - - return rc.JobContainer.Exec(containerArgs, *step.getEnv(), "", "")(ctx) - - case x.IsDocker(): - return execDockerActionStage(ctx, step, stepStagePre) - - case x.IsComposite(): - if step.getCompositeSteps() == nil { - if _, err := step.getCompositeRunContext(ctx); err != nil { - return err - } - } - - if steps := step.getCompositeSteps(); steps != nil && steps.pre != nil { - return steps.pre(ctx) - } - return errors.New("missing steps in composite action") - - case x == model.ActionRunsUsingGo: - if err := maybeCopyToActionDir(ctx, step, actionDir, actionPath, containerActionDir); err != nil { - return err - } - - rc.ApplyExtraPath(ctx, step.getEnv()) - - execFileName := action.Runs.Pre + ".out" - return common.NewPipelineExecutor( - rc.JobContainer.Exec([]string{"go", "build", "-o", execFileName, action.Runs.Pre}, *step.getEnv(), "", containerActionDir), - rc.JobContainer.Exec([]string{container.JoinPath(containerActionDir, execFileName)}, *step.getEnv(), "", ""), - )(ctx) - default: - return nil - } + return filepath.Join(step.getRunContext().Config.Workdir, step.getStepModel().Uses), "" } } @@ -723,70 +570,45 @@ func shouldRunPostStep(step actionStep) common.Conditional { func hasPostStep(step actionStep) common.Conditional { return func(ctx context.Context) bool { - action := step.getActionModel() - return action.Runs.Using.IsComposite() || - (action.Runs.Using.IsNode() && - action.Runs.Post != "") || - (action.Runs.Using.IsDocker() && - action.Runs.PostEntrypoint != "") || - (action.Runs.Using == model.ActionRunsUsingGo && - action.Runs.Post != "") + runs := &step.getActionModel().Runs + return runs.Using.IsComposite() || (runs.Using.IsDocker() && runs.PostEntrypoint != "") || + ((runs.Using.IsNode() || runs.Using == model.ActionRunsUsingGo) && runs.Post != "") } } -func runPostStep(step actionStep) common.Executor { +func runActionHook(step actionStep, stage stepStage) common.Executor { return func(ctx context.Context) error { logger := common.Logger(ctx) - logger.Debugf("run post step for '%s'", step.getStepModel()) + logger.Debugf("run %s step for '%s'", strings.ToLower(stage.String()), step.getStepModel()) - rc := step.getRunContext() - action := step.getActionModel() - - actionDir, actionPath, _, containerActionDir := actionStagePaths(step) - - x := action.Runs.Using - if !x.IsComposite() { // a composite's children print their own - logger.With(rawOutputField, true).Info("Post job cleanup.") + if !step.getActionModel().Runs.Using.IsComposite() { + if stage == stepStagePost { + logger.With(rawOutputField, true).Info("Post job cleanup.") + } + return runActionStage(ctx, step, stage) } - switch { - case x.IsNode(): - populateEnvsFromSavedState(step.getEnv(), step, rc) - - containerArgs := nodeActionCommand(container.JoinPath(containerActionDir, action.Runs.Post)) - logger.Debugf("executing remote job container: %s", containerArgs) - - rc.ApplyExtraPath(ctx, step.getEnv()) - - return rc.JobContainer.Exec(containerArgs, *step.getEnv(), "", "")(ctx) - - case x.IsDocker(): - populateEnvsFromSavedState(step.getEnv(), step, rc) - - return execDockerActionStage(ctx, step, stepStagePost) - - case x.IsComposite(): + if stage == stepStagePre { + rc := step.getRunContext() + printRunActionHeader(ctx, step.getStepModel(), step.getActionModel(), *step.getEnv(), rc) + inputs, err := rc.resolveActionInputs(ctx, step, step.getActionModel()) + if err != nil { + return err + } + step.getCompositeRunContext(ctx, inputs) + if pre := step.getCompositeSteps().pre; pre != nil { + return pre(ctx) + } + } else { + actionDir, actionPath := actionSourcePaths(step) + _, containerActionDir := getContainerActionPaths(step) if err := maybeCopyToActionDir(ctx, step, actionDir, actionPath, containerActionDir); err != nil { return err } - if steps := step.getCompositeSteps(); steps != nil && steps.post != nil { return steps.post(ctx) } - return errors.New("missing steps in composite action") - - case x == model.ActionRunsUsingGo: - populateEnvsFromSavedState(step.getEnv(), step, rc) - rc.ApplyExtraPath(ctx, step.getEnv()) - - execFileName := action.Runs.Post + ".out" - return common.NewPipelineExecutor( - rc.JobContainer.Exec([]string{"go", "build", "-o", execFileName, action.Runs.Post}, *step.getEnv(), "", containerActionDir), - rc.JobContainer.Exec([]string{container.JoinPath(containerActionDir, execFileName)}, *step.getEnv(), "", ""), - )(ctx) - - default: - return nil } + return errors.New("missing steps in composite action") } } diff --git a/act/runner/action_composite.go b/act/runner/action_composite.go index 1dba9f3b..5cd4dd84 100644 --- a/act/runner/action_composite.go +++ b/act/runner/action_composite.go @@ -8,6 +8,7 @@ import ( "context" "errors" "fmt" + "maps" "slices" "strconv" "strings" @@ -17,65 +18,18 @@ import ( "gitea.dev/actionslib/pkg/model" ) -func evaluateCompositeInputAndEnv(ctx context.Context, parent *RunContext, step actionStep) (map[string]string, error) { - env := make(map[string]string) - stepEnv := *step.getEnv() - for k, v := range stepEnv { - // do not set current inputs into composite action - // the required inputs are added in the second loop - if !strings.HasPrefix(k, "INPUT_") { - env[k] = v - } +func (rc *RunContext) setCompositeActionEnv(stepEnv, inputs map[string]string) { + isInput := func(key, _value string) bool { return strings.HasPrefix(key, "INPUT_") } + env := maps.Clone(stepEnv) + maps.DeleteFunc(env, isInput) + for name, value := range inputs { + env[inputEnvKey(name)] = value } - - ee := parent.NewStepExpressionEvaluator(ctx, step) - - for inputID, input := range step.getActionModel().Inputs { - envKey := inputEnvKey(inputID) - - // lookup if key is defined in the step but the already - // evaluated value from the environment - defined := false - for key := range step.getStepModel().With { - if strings.EqualFold(key, inputID) { - defined = true - break - } - } - if value, ok := stepEnv[envKey]; defined && ok { - env[envKey] = value - } else { - // defaults could contain expressions - 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) - } - } - } - for envKey, value := range (&model.Step{With: step.getStepModel().With}).GetEnv() { - if _, ok := env[envKey]; !ok { - env[envKey] = value - } - } - - return env, nil -} - -func (rc *RunContext) setCompositeActionEnv(env map[string]string) { rc.setActionEnv(env) - for key := range rc.Env { - if strings.HasPrefix(key, "INPUT_") { - delete(rc.Env, key) - } - } + maps.DeleteFunc(rc.Env, isInput) } -func newCompositeRunContext(ctx context.Context, parent *RunContext, step actionStep, actionPath string) (*RunContext, error) { - env, err := evaluateCompositeInputAndEnv(ctx, parent, step) - if err != nil { - return nil, err - } - +func newCompositeRunContext(ctx context.Context, parent *RunContext, step actionStep, actionPath string, inputs map[string]string) *RunContext { // run with the global config but without secrets configCopy := *parent.Config configCopy.Secrets = nil @@ -109,10 +63,10 @@ func newCompositeRunContext(ctx context.Context, parent *RunContext, step action jobTotal: parent.jobTotal, runtimeToken: parent.runtimeToken, } - compositerc.setCompositeActionEnv(env) + compositerc.setCompositeActionEnv(*step.getEnv(), inputs) compositerc.ExprEval = compositerc.NewExpressionEvaluator(ctx) - return compositerc, nil + return compositerc } // appendUniqueMasks appends the masks from src to dst, skipping any mask that @@ -128,56 +82,41 @@ func appendUniqueMasks(dst, src []string) []string { return dst } -func execAsComposite(step actionStep) common.Executor { +func execAsComposite(ctx context.Context, step actionStep, inputs map[string]string) error { + compositeRC := step.getCompositeRunContext(ctx, inputs) + ctx = WithCompositeLogger(ctx, &compositeRC.Masks) rc := step.getRunContext() - action := step.getActionModel() + err := step.getCompositeSteps().main(ctx) - return func(ctx context.Context) error { - compositeRC, err := step.getCompositeRunContext(ctx) - if err != nil { - return err + // Map outputs from composite RunContext to job RunContext + eval := compositeRC.NewExpressionEvaluator(ctx) + for outputName, output := range step.getActionModel().Outputs { + value, outputErr := eval.Interpolate(ctx, output.Value) + if outputErr != nil { + err = errors.Join(err, fmt.Errorf("unable to interpolate output %s: %w", outputName, outputErr)) + continue } - - steps := step.getCompositeSteps() - - if steps == nil || steps.main == nil { - return errors.New("missing steps in composite action") - } - - ctx = WithCompositeLogger(ctx, &compositeRC.Masks) - - err = steps.main(ctx) - - // Map outputs from composite RunContext to job RunContext - eval := compositeRC.NewExpressionEvaluator(ctx) - for outputName, output := range action.Outputs { - value, outputErr := eval.Interpolate(ctx, output.Value) - if outputErr != nil { - 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) - // and may have additional masks appended while the composite action runs. - // Only append masks that are not already present, otherwise nested or - // repeated composite actions grow rc.Masks exponentially. - rc.Masks = appendUniqueMasks(rc.Masks, compositeRC.Masks) - rc.ExtraPath = compositeRC.ExtraPath - // Propagate GlobalEnv only, so composite inputs and step-local values do not escape. - mergeIntoMap := mergeIntoMapCaseSensitive - if rc.JobContainer.IsEnvironmentCaseInsensitive() { - mergeIntoMap = mergeIntoMapCaseInsensitive - } - if rc.GlobalEnv == nil { - rc.GlobalEnv = map[string]string{} - } - mergeIntoMap(rc.GlobalEnv, compositeRC.GlobalEnv) - mergeIntoMap(rc.Env, compositeRC.GlobalEnv) - - return err + rc.setOutput(ctx, map[string]string{"name": outputName}, value) } + + // compositeRC.Masks is seeded with rc.Masks (see newCompositeRunContext) + // and may have additional masks appended while the composite action runs. + // Only append masks that are not already present, otherwise nested or + // repeated composite actions grow rc.Masks exponentially. + rc.Masks = appendUniqueMasks(rc.Masks, compositeRC.Masks) + rc.ExtraPath = compositeRC.ExtraPath + // Propagate GlobalEnv only, so composite inputs and step-local values do not escape. + mergeIntoMap := mergeIntoMapCaseSensitive + if rc.JobContainer.IsEnvironmentCaseInsensitive() { + mergeIntoMap = mergeIntoMapCaseInsensitive + } + if rc.GlobalEnv == nil { + rc.GlobalEnv = map[string]string{} + } + mergeIntoMap(rc.GlobalEnv, compositeRC.GlobalEnv) + mergeIntoMap(rc.Env, compositeRC.GlobalEnv) + + return err } type compositeSteps struct { diff --git a/act/runner/action_composite_test.go b/act/runner/action_composite_test.go index 65ca0ad3..ab3ddb86 100644 --- a/act/runner/action_composite_test.go +++ b/act/runner/action_composite_test.go @@ -23,7 +23,7 @@ func TestCompositeActionParity(t *testing.T) { for _, uses := range []string{"./action", "own/action@v2"} { t.Run(uses, func(t *testing.T) { rc := &RunContext{ - Config: &Config{PresetGitHubContext: &model.GithubContext{}}, + Config: &Config{PresetGitHubContext: &model.GithubContext{}, Secrets: map[string]string{"key": "secret"}, Vars: map[string]string{"key": "var"}}, Run: &model.Run{JobID: "job", Workflow: &model.Workflow{Jobs: map[string]*model.Job{"job": {}}}}, Env: map[string]string{"GITHUB_ACTION_REPOSITORY": "other/composite", "GITHUB_ACTION_REF": "v1"}, } @@ -34,16 +34,17 @@ func TestCompositeActionParity(t *testing.T) { want = "own/action|v2" } action := &model.Action{ - Inputs: map[string]model.Input{"identity": {Default: "${{ github.action_repository }}|${{ github.action_ref }}"}}, - Runs: model.ActionRuns{Env: map[string]string{"GITHUB_WORKFLOW_SHA": "runs-sha"}}, + Inputs: map[string]model.Input{"identity": {Default: "${{ secrets.key || vars.key || env.GITHUB_JOB || github.action_repository }}|${{ gitea.action_ref }}"}}, + Runs: model.ActionRuns{Env: map[string]string{"GITHUB_WORKFLOW_SHA": "${{ env.GITHUB_JOB || inputs.identity }}"}}, } require.NoError(t, setupEnv(t.Context(), currentStep)) - require.NoError(t, populateEnvsFromInput(t.Context(), currentStep, action)) - assert.Equal(t, want, (*currentStep.getEnv())["INPUT_IDENTITY"]) - _, err := evalDockerEnv(t.Context(), currentStep, action) + inputs, err := rc.resolveActionInputs(t.Context(), currentStep, action) + require.NoError(t, err) + assert.Equal(t, want, inputs["identity"]) + _, err = evalDockerArgsAndEnv(t.Context(), currentStep, action, inputs) require.NoError(t, err) assert.Equal(t, want, (*currentStep.getEnv())["identity"]) - assert.Equal(t, "runs-sha", (*currentStep.getEnv())["GITEA_WORKFLOW_SHA"]) + assert.Equal(t, want, (*currentStep.getEnv())["GITEA_WORKFLOW_SHA"]) }) } }) @@ -51,12 +52,19 @@ func TestCompositeActionParity(t *testing.T) { t.Run("inherits contexts without leaking inputs", func(t *testing.T) { hook := logtest.NewWithLevel(logging.LevelWarn) ctx := common.WithLogger(t.Context(), logging.New(hook)) + hashCalls := 0 strategy := &model.Strategy{MaxParallelString: "3", RawMatrix: yaml.Node{Kind: yaml.MappingNode}} parent := &RunContext{ - Config: &Config{PresetGitHubContext: &model.GithubContext{}}, - Matrix: map[string]any{"os": "linux"}, - Run: &model.Run{JobID: "job", Workflow: &model.Workflow{Name: "workflow", Jobs: map[string]*model.Job{"job": {Strategy: strategy}}}}, - JobContainer: &jobContainerMock{}, + Config: &Config{PresetGitHubContext: &model.GithubContext{}}, + Matrix: map[string]any{"os": "linux"}, + Run: &model.Run{JobID: "job", Workflow: &model.Workflow{Name: "workflow", Jobs: map[string]*model.Job{"job": {Strategy: strategy}}}}, + JobContainer: &hashFilesContainer{ + ExecutionsEnvironment: &jobContainerMock{}, + execute: func(_command []string, _env map[string]string, _user, _workdir string) common.Executor { + hashCalls++ + return noopExecutor + }, + }, platformImage: "-self-hosted", jobIndex: 1, jobTotal: 4, @@ -64,27 +72,23 @@ func TestCompositeActionParity(t *testing.T) { step := &stepActionLocal{ Step: &model.Step{Uses: "./action", With: map[string]string{"SHARED": "outer", "extra": "literal${{ github.job }}"}}, RunContext: parent, - action: &model.Action{Inputs: map[string]model.Input{"shared": {Default: "outer-default"}}, Runs: model.ActionRuns{Using: "composite"}}, - env: map[string]string{"INPUT_SHARED": "outer"}, + action: &model.Action{Inputs: map[string]model.Input{"shared": {}, "target region": {Default: "${{ hashFiles('region') || 'local' }}"}}, Runs: model.ActionRuns{Using: "composite"}}, + env: map[string]string{"INPUT_TARGET_REGION": "inherited"}, } - require.NoError(t, runActionImpl(step, "/action", nil)(ctx)) + require.NoError(t, runActionImpl(step)(ctx)) + assert.Equal(t, 1, hashCalls) require.Len(t, hook.AllRecords(), 1) - assert.Equal(t, "##[warning]Unexpected input(s) 'extra', valid inputs are ['shared']", hook.LastRecord().Message) - composite, err := step.getCompositeRunContext(ctx) - require.NoError(t, err) + assert.Equal(t, "##[warning]Unexpected input(s) 'extra', valid inputs are ['shared', 'target region']", hook.LastRecord().Message) + composite := step.compositeRunContext assert.Same(t, strategy, composite.Run.Job().Strategy) assert.True(t, composite.IsHostEnv()) interpolated, err := composite.NewExpressionEvaluator(ctx).Interpolate(ctx, - "${{ matrix.os }}|${{ strategy.max-parallel }}|${{ strategy.job-index }}|${{ inputs.shared }}|${{ inputs.extra }}") + "${{ matrix.os }}|${{ strategy.max-parallel }}|${{ strategy.job-index }}|${{ inputs.shared }}|${{ inputs.target_region }}|${{ inputs.extra }}") require.NoError(t, err) - assert.Equal(t, "linux|3|1|outer|literal${{ github.job }}", interpolated) + assert.Equal(t, "linux|3|1|outer|local|literal${{ github.job }}", interpolated) assert.NotContains(t, composite.Env, "INPUT_SHARED") assert.NotContains(t, composite.Env, "INPUT_EXTRA") - - nestedEnv := composite.GetEnv() - require.NoError(t, populateEnvsFromInput(ctx, &stepActionLocal{RunContext: composite, env: nestedEnv}, &model.Action{Inputs: map[string]model.Input{"shared": {Default: "inner-default"}}})) - assert.Equal(t, "inner-default", nestedEnv["INPUT_SHARED"]) }) t.Run("propagates pre failures", func(t *testing.T) { @@ -186,12 +190,10 @@ func TestCompositeStepIfReadsJobStatusExceptInItsOwnMainSteps(t *testing.T) { } func newTestCompositeRunContext(t *testing.T, parent *RunContext) *RunContext { - composite, err := newCompositeRunContext(t.Context(), parent, &stepActionRemote{ + return newCompositeRunContext(t.Context(), parent, &stepActionRemote{ Step: &model.Step{}, RunContext: parent, action: &model.Action{}, env: map[string]string{}, - }, "/action") - require.NoError(t, err) - return composite + }, "/action", nil) } diff --git a/act/runner/action_test.go b/act/runner/action_test.go index 706282e1..08f8cbd7 100644 --- a/act/runner/action_test.go +++ b/act/runner/action_test.go @@ -14,15 +14,13 @@ import ( "path/filepath" "runtime" "strings" - "sync" "testing" - "time" "gitea.com/gitea/runner/act/common" - "gitea.com/gitea/runner/act/common/git" "gitea.com/gitea/runner/act/common/logging" "gitea.com/gitea/runner/act/common/logging/logtest" "gitea.com/gitea/runner/act/container" + "gitea.com/gitea/runner/internal/pkg/lock" "gitea.dev/actionslib/pkg/model" "github.com/stretchr/testify/assert" @@ -54,72 +52,27 @@ runs: }, } - table := []struct { + type readerCase struct { name string - step *model.Step + step model.Step filename string fileContent string expected *model.Action - }{ - { - name: "readActionYml", - step: &model.Step{}, - filename: "action.yml", - fileContent: yaml, - expected: yamlAction, - }, - { - name: "readActionYaml", - step: &model.Step{}, - filename: "action.yaml", - fileContent: yaml, - expected: yamlAction, - }, - { - name: "readDockerfile", - step: &model.Step{}, - filename: "Dockerfile", - fileContent: "FROM ubuntu:20.04", - expected: &model.Action{ - Name: "(Synthetic)", - Runs: model.ActionRuns{ - Using: "docker", - Image: "Dockerfile", - }, - }, - }, - { - name: "readLowercaseDockerfile", - step: &model.Step{}, - filename: "dockerfile", - fileContent: "FROM ubuntu:20.04", - expected: &model.Action{ - Name: "(Synthetic)", - Runs: model.ActionRuns{ - Using: "docker", - Image: "dockerfile", - }, - }, - }, + } + table := []readerCase{ { name: "readWithArgs", - step: &model.Step{ - With: map[string]string{ - "args": "cmd", - }, - }, + step: model.Step{With: map[string]string{"args": "cmd"}}, expected: &model.Action{ Name: "(Synthetic)", Inputs: map[string]model.Input{ "args": {}, "cwd": { Description: "(Actual working directory)", - Required: false, Default: filepath.Join("actionDir", "actionPath"), }, "command": { Description: "(Actual program)", - Required: false, Default: "cmd", }, }, @@ -129,6 +82,20 @@ runs: }, }, }, + { + name: "invalid manifest", + filename: "action.yaml", + fileContent: "runs: {using: node99}\n", + }, + } + + for _, filename := range []string{"action.yml", "action.yaml"} { + table = append(table, readerCase{name: filename, filename: filename, fileContent: yaml, expected: yamlAction}) + } + for _, filename := range []string{"Dockerfile", "dockerfile"} { + table = append(table, readerCase{name: filename, filename: filename, expected: &model.Action{ + Name: "(Synthetic)", Runs: model.ActionRuns{Using: "docker", Image: filename}, + }}) } for _, tt := range table { @@ -149,12 +116,15 @@ runs: return nil } - action, err := readActionImpl(t.Context(), tt.step, "actionDir", "actionPath", readFile, writeFile) - - require.NoError(t, err) - assert.Equal(t, tt.expected, action) + action, err := readActionImpl(t.Context(), &tt.step, "actionDir", "actionPath", readFile, writeFile) assert.Equal(t, tt.filename != "", closed) + if tt.expected == nil { + require.ErrorContains(t, err, "Failed to load "+filepath.Join("actionDir", "actionPath", tt.filename)) + return + } + require.NoError(t, err) + assert.Equal(t, tt.expected, action) }) } } @@ -165,20 +135,18 @@ func TestActionRunner(t *testing.T) { name string inputs map[string]model.Input with map[string]string + inherited map[string]string state map[string]string expectedEnv map[string]string warning string }{ { - name: "with-input", - inputs: map[string]model.Input{"key": {Default: "default value"}}, - expectedEnv: map[string]string{"INPUT_KEY": "default value"}, - }, - { - name: "declared input ignores case", - inputs: map[string]model.Input{"key": {Default: "default value"}}, - with: map[string]string{"KEY": "provided value"}, - expectedEnv: map[string]string{"INPUT_KEY": "provided value"}, + name: "input precedence and saved state across stages", + inputs: map[string]model.Input{"foo": {Default: "default"}, "key": {Default: "${{ fromJSON('') }}"}}, + with: map[string]string{"KEY": "provided"}, + inherited: map[string]string{"INPUT_FOO": "inherited", "INPUT_KEY": "inherited"}, + state: map[string]string{"name": "state value"}, + expectedEnv: map[string]string{"INPUT_FOO": "default", "INPUT_KEY": "provided", "STATE_name": "state value"}, }, { name: "unexpected inputs warn once across stages", @@ -191,30 +159,26 @@ func TestActionRunner(t *testing.T) { with: map[string]string{"unknown": "value"}, warning: "##[warning]Unexpected input(s) 'unknown', valid inputs are ['']", }, - { - name: "restore-saved-state", - state: map[string]string{"name": "state value"}, - expectedEnv: map[string]string{"STATE_name": "state value"}, - }, } { t.Run(tt.name, func(t *testing.T) { hook := logtest.NewWithLevel(logging.LevelWarn) ctx := common.WithLogger(t.Context(), logging.New(hook)) cm := &containerMock{} containerActionDir := "/var/run/act/actions/" + model.UsesHash("/org/repo/path@ref") + "/" - cm.On("CopyDir", containerActionDir, "dir/", false, true).Return(func(_ctx context.Context) error { return nil }) + cm.On("CopyDir", containerActionDir, "dir/", false, true).Return(noopExecutor) - envMatcher := mock.MatchedBy(func(env map[string]string) bool { - for k, v := range tt.expectedEnv { - if env[k] != v { - return false + for _, script := range []string{"path/pre.js", "path/main.js", "path/post.js"} { + cm.On("Exec", nodeActionCommand(containerActionDir+script), mock.Anything, "", "").Return(noopExecutor).Once().Run(func(args mock.Arguments) { + env := args.Get(1).(map[string]string) + for key, value := range tt.expectedEnv { + if script == "path/pre.js" && strings.HasPrefix(key, "STATE_") { + assert.NotContains(t, env, key) + } else { + assert.Equal(t, value, env[key], "%s in %s", key, script) + } } - } - return true - }) - cm.On("Exec", []string{"node", "--preserve-symlinks-main", containerActionDir + "path"}, envMatcher, "", "").Return(func(_ctx context.Context) error { return nil }) - cm.On("Exec", nodeActionCommand(containerActionDir+"path/pre.js"), mock.Anything, "", "").Return(func(_ctx context.Context) error { return nil }) - cm.On("Exec", nodeActionCommand(containerActionDir+"path/post.js"), envMatcher, "", "").Return(func(_ctx context.Context) error { return nil }) + }) + } remoteAction := mustNewRemoteAction(t, "org/repo/path@ref") step := &stepActionRemote{ @@ -225,15 +189,17 @@ func TestActionRunner(t *testing.T) { IntraActionState: map[string]map[string]string{"step": tt.state}, JobContainer: cm, }, - action: &model.Action{Inputs: tt.inputs, Runs: model.ActionRuns{Using: "node16", Pre: "pre.js", Post: "post.js"}}, + action: &model.Action{Inputs: tt.inputs, Runs: model.ActionRuns{Using: "node16", Pre: "pre.js", Main: "main.js", Post: "post.js"}}, actionDir: "dir", - env: (&model.Step{With: tt.with}).GetEnv(), remoteAction: remoteAction, } - require.NoError(t, runPreStep(step)(ctx)) - assert.Empty(t, hook.AllRecords()) - require.NoError(t, runActionImpl(step, "dir", remoteAction)(ctx)) - require.NoError(t, runPostStep(step)(ctx)) + for index, execute := range []common.Executor{runActionHook(step, stepStagePre), runActionImpl(step), runActionHook(step, stepStagePost)} { + step.env = mergeMaps(tt.inherited) + require.NoError(t, execute(ctx)) + if index == 0 { + assert.Empty(t, hook.AllRecords()) + } + } if tt.warning == "" { assert.Empty(t, hook.AllRecords()) } else { @@ -254,7 +220,9 @@ func TestGoActionUsesLinuxExecutablePaths(t *testing.T) { t.Run(stage, func(t *testing.T) { cm := &containerMock{} containerActionDir := "/var/run/act/actions/" + model.UsesHash("/org/repo@ref") - cm.On("CopyDir", containerActionDir+"/", mock.Anything, false, true).Return(noopExecutor).Maybe() + if stage != "post" { + cm.On("CopyDir", containerActionDir+"/", mock.Anything, false, true).Return(noopExecutor).Once() + } cm.On("Exec", []string{"go", "build", "-o", stage + ".go.out", stage + ".go"}, mock.Anything, "", containerActionDir).Return(noopExecutor).Once() cm.On("Exec", []string{containerActionDir + "/" + stage + ".go.out"}, mock.Anything, "", "").Return(noopExecutor).Once() step := &stepActionRemote{ @@ -271,11 +239,11 @@ func TestGoActionUsesLinuxExecutablePaths(t *testing.T) { } switch stage { case "main": - require.NoError(t, runActionImpl(step, step.actionDir, step.remoteAction)(t.Context())) + require.NoError(t, runActionImpl(step)(t.Context())) case "pre": - require.NoError(t, runPreStep(step)(t.Context())) + require.NoError(t, runActionHook(step, stepStagePre)(t.Context())) case "post": - require.NoError(t, runPostStep(step)(t.Context())) + require.NoError(t, runActionHook(step, stepStagePost)(t.Context())) } cm.AssertExpectations(t) }) @@ -308,242 +276,54 @@ if (process.argv[1] !== self) { require.NoError(t, err, "%s", output) } -func TestNewStepContainerDoesNotUseDockerSecrets(t *testing.T) { - cm := &containerMock{} - - var captured *container.NewContainerInput - origContainerNewContainer := ContainerNewContainer - ContainerNewContainer = func(input *container.NewContainerInput) container.ExecutionsEnvironment { - captured = input - return cm - } - defer func() { - ContainerNewContainer = origContainerNewContainer - }() - - ctx := t.Context() - rc := &RunContext{ - Name: "job", - Config: &Config{ - Secrets: map[string]string{ - "DOCKER_USERNAME": "docker-user", - "DOCKER_PASSWORD": "docker-password", - }, - }, - Run: &model.Run{ - JobID: "job", - Workflow: &model.Workflow{ - Name: "test", - Jobs: map[string]*model.Job{ - "job": {}, - }, - }, - }, - JobContainer: cm, - StepResults: map[string]*model.StepResult{}, - } - env := map[string]string{} - step := &stepMock{} - step.On("getRunContext").Return(rc) - step.On("getStepModel").Return(&model.Step{ID: "action"}) - step.On("getEnv").Return(&env) - - newStepContainer(ctx, step, "registry.example.com/action:tag", nil, nil, "") - - assert.Empty(t, captured.Username) - assert.Empty(t, captured.Password) - assert.True(t, captured.AutoRemove) - step.AssertExpectations(t) -} - func TestMaybeCopyToActionDirHoldsCloneLock(t *testing.T) { - ctx := t.Context() - actionDir := t.TempDir() - - releaseCopy := make(chan struct{}) - release := sync.OnceFunc(func() { close(releaseCopy) }) - defer release() - - copyEntered := make(chan struct{}) - cm := &containerMock{} - cm.On("CopyDir", "/var/run/act/actions/", actionDir+"/", false, true).Return(func(ctx context.Context) error { - close(copyEntered) - <-releaseCopy + cm.On("CopyDir", "/var/run/act/actions/", actionDir+"/", false, true).Return(func(context.Context) error { + _, err := lock.TryLock(actionDir) + assert.ErrorIs(t, err, lock.ErrLocked) return nil }) + step := &stepActionRemote{Step: &model.Step{Uses: "remote/action@v1"}, RunContext: &RunContext{Config: &Config{}, JobContainer: cm}} - step := &stepActionRemote{ - Step: &model.Step{Uses: "remote/action@v1"}, - RunContext: &RunContext{ - Config: &Config{}, - JobContainer: cm, - }, - } - - copyDone := make(chan error, 1) - go func() { - copyDone <- maybeCopyToActionDir(ctx, step, actionDir, "", "/var/run/act/actions/") - }() - - select { - case <-copyEntered: - case err := <-copyDone: - t.Fatalf("maybeCopyToActionDir returned before CopyDir was entered: %v", err) - case <-time.After(time.Second): - t.Fatal("CopyDir was not entered within 1 second") - } - - peerAcquired := make(chan struct{}) - go func() { - unlock, err := git.AcquireCloneLock(t.Context(), actionDir) - if !assert.NoError(t, err) { - return - } - close(peerAcquired) - unlock() - }() - - select { - case <-peerAcquired: - t.Fatal("peer AcquireCloneLock returned while CopyDir was running") - case <-time.After(50 * time.Millisecond): - } - - release() - - select { - case err := <-copyDone: - if err != nil { - t.Fatalf("maybeCopyToActionDir returned error: %v", err) - } - case <-time.After(time.Second): - t.Fatal("maybeCopyToActionDir did not return after CopyDir was unblocked") - } - - select { - case <-peerAcquired: - case <-time.After(time.Second): - t.Fatal("peer AcquireCloneLock did not proceed after lock released") - } - + require.NoError(t, maybeCopyToActionDir(t.Context(), step, actionDir, "", "/var/run/act/actions/")) + release, err := lock.TryLock(actionDir) + require.NoError(t, err) + require.NoError(t, release()) cm.AssertExpectations(t) } -func TestExecAsDockerHoldsCloneLockForRemoteUncached(t *testing.T) { - actionDir := t.TempDir() - - unlock, err := git.AcquireCloneLock(t.Context(), actionDir) - require.NoError(t, err) - unlockOnce := sync.OnceFunc(unlock) - defer unlockOnce() - - innerEntered := make(chan struct{}) - releaseInner := make(chan struct{}) - releaseOnce := sync.OnceFunc(func() { close(releaseInner) }) - defer releaseOnce() - - origImageExists := ContainerImageExistsLocally - ContainerImageExistsLocally = func(_ context.Context, _, _ string) (bool, error) { - return false, nil - } - defer func() { ContainerImageExistsLocally = origImageExists }() - - origBuildExec := ContainerNewDockerBuildExecutor - ContainerNewDockerBuildExecutor = func(_ container.NewDockerBuildExecutorInput) common.Executor { - return func(_ context.Context) error { - close(innerEntered) - <-releaseInner - return nil - } - } - defer func() { ContainerNewDockerBuildExecutor = origBuildExec }() - - step := &stepActionRemote{ - Step: &model.Step{ID: "1", Uses: "remote/action@v1", With: map[string]string{}}, - RunContext: &RunContext{ - Config: &Config{Env: testCheckoutEnv()}, - Run: &model.Run{ - JobID: "1", - Workflow: &model.Workflow{ - Name: "wf", - Jobs: map[string]*model.Job{"1": {}}, - }, - }, - JobContainer: &containerMock{}, - }, - action: &model.Action{Runs: model.ActionRuns{Using: "docker", Image: "Dockerfile"}}, - env: map[string]string{}, - } - - ctx, cancel := context.WithCancel(t.Context()) - defer cancel() - - done := make(chan error, 1) - go func() { done <- execAsDocker(ctx, step, "test-action", actionDir, actionDir, false, stepStageMain) }() - - select { - case <-innerEntered: - t.Fatal("inner build executor ran before clone lock was released") - case err := <-done: - t.Fatalf("execAsDocker returned before inner was entered: %v", err) - case <-time.After(50 * time.Millisecond): - } - - unlockOnce() - - select { - case <-innerEntered: - case err := <-done: - t.Fatalf("execAsDocker returned without entering inner: %v", err) - } - - cancel() - releaseOnce() - assert.ErrorIs(t, <-done, context.Canceled) -} - func TestExecAsDockerImageChecks(t *testing.T) { - actionRoot := t.TempDir() - originalExists, originalBuild, originalContainer := ContainerImageExistsLocally, ContainerNewDockerBuildExecutor, ContainerNewContainer + if container.NewContainer(&container.NewContainerInput{}) == nil { + t.Skip("Docker backend is disabled") + } + originalExists, originalBuild := ContainerImageExistsLocally, ContainerNewDockerBuildExecutor t.Cleanup(func() { - ContainerImageExistsLocally, ContainerNewDockerBuildExecutor, ContainerNewContainer = originalExists, originalBuild, originalContainer + ContainerImageExistsLocally, ContainerNewDockerBuildExecutor = originalExists, originalBuild }) - ContainerNewContainer = func(*container.NewContainerInput) container.ExecutionsEnvironment { return fakeContainer{} } - var removed bool - fakeDockerDaemon(t, func(writer http.ResponseWriter, request *http.Request) { - if request.Method == http.MethodDelete { - removed = true - _, _ = io.WriteString(writer, `[]`) - } else { - _, _ = io.WriteString(writer, `{"Architecture":"aarch64"}`) - } - }) - for _, testcase := range []struct { - name, platform string - exists, matches, rebuild bool - wantBuild, wantRemove bool - wantChecks []string + name, platform, options, wantPlatform string + exists, rebuild, wantBuild bool }{ - {name: "missing image", platform: "linux/arm64", wantBuild: true, wantChecks: []string{"any"}}, - {name: "unspecified platform", exists: true, matches: true, wantChecks: []string{"any"}}, - {name: "any platform", platform: "any", exists: true, matches: true, wantChecks: []string{"any"}}, - {name: "matching platform", platform: "linux/arm64", exists: true, matches: true, wantChecks: []string{"any", "linux/arm64"}}, - {name: "different platform", platform: "linux/arm64", exists: true, wantBuild: true, wantRemove: true, wantChecks: []string{"any", "linux/arm64"}}, - {name: "forced rebuild", exists: true, matches: true, rebuild: true, wantBuild: true, wantChecks: []string{"any"}}, + {name: "matching platform", platform: "linux/arm64", wantPlatform: "linux/arm64", exists: true}, + {name: "runner options override architecture", platform: "linux/arm64", options: "--platform linux/amd64", wantPlatform: "linux/amd64", wantBuild: true}, + {name: "forced rebuild", exists: true, rebuild: true, wantBuild: true}, } { t.Run(testcase.name, func(t *testing.T) { - var checks []string + actionDir := t.TempDir() ContainerImageExistsLocally = func(_ctx context.Context, _image, platform string) (bool, error) { - checks = append(checks, platform) - return testcase.exists && (platform == "any" || testcase.matches), nil + assert.Equal(t, testcase.wantPlatform, platform) + return testcase.exists, nil } var built bool - removed = false - ContainerNewDockerBuildExecutor = func(container.NewDockerBuildExecutorInput) common.Executor { - return func(context.Context) error { built = true; return nil } + ContainerNewDockerBuildExecutor = func(input container.NewDockerBuildExecutorInput) common.Executor { + assert.Equal(t, testcase.wantPlatform, input.Platform) + return func(context.Context) error { + built = true + _, err := lock.TryLock(actionDir) + assert.ErrorIs(t, err, lock.ErrLocked) + return nil + } } step := &stepActionRemote{ Step: &model.Step{ID: "action"}, @@ -551,19 +331,19 @@ func TestExecAsDockerImageChecks(t *testing.T) { Config: &Config{ PresetGitHubContext: &model.GithubContext{}, ContainerArchitecture: testcase.platform, + ContainerOptions: testcase.options, ForceRebuild: testcase.rebuild, }, Run: &model.Run{JobID: "job", Workflow: &model.Workflow{Jobs: map[string]*model.Job{"job": {}}}}, JobContainer: &jobContainerMock{}, }, - action: &model.Action{Runs: model.ActionRuns{Using: "docker", Image: "Dockerfile"}}, - env: map[string]string{}, + action: &model.Action{Runs: model.ActionRuns{Using: "docker", Image: "Dockerfile"}}, + actionDir: actionDir, + remoteAction: mustNewRemoteAction(t, "remote/action@v1"), + env: map[string]string{}, } - dir := filepath.Join(actionRoot, testcase.name) - require.NoError(t, execAsDocker(t.Context(), step, "action", dir, dir, false, stepStageMain)) - assert.Equal(t, testcase.wantChecks, checks) + require.NoError(t, runActionImpl(step)(common.WithDryrun(t.Context(), true))) assert.Equal(t, testcase.wantBuild, built) - assert.Equal(t, testcase.wantRemove, removed) }) } } @@ -657,21 +437,12 @@ func TestExecAsDockerStageEntrypoint(t *testing.T) { warning: "##[warning]Unexpected input(s) 'unknown', valid inputs are ['entryPoint', 'args', 'message']", }, { - name: "manifest args keep caller input quotes literal", + name: "manifest args preserve quoted and explicitly empty caller inputs", stage: stepStageMain, - with: map[string]string{"args": "it's literal"}, - runs: model.ActionRuns{Args: []string{"${{ inputs.args }}"}}, - env: map[string]string{"INPUT_ARGS": "it's literal"}, - wantCmd: []string{"it's literal"}, - }, - { - name: "caller input skips its default expression", - stage: stepStageMain, - with: map[string]string{"MESSAGE": "provided"}, + with: map[string]string{"args": "it's literal", "MESSAGE": ""}, inputs: map[string]model.Input{"message": {Default: "${{ fromJSON('') }}"}}, - runs: model.ActionRuns{Args: []string{"${{ inputs.message }}"}}, - env: map[string]string{"INPUT_MESSAGE": "provided"}, - wantCmd: []string{"provided"}, + runs: model.ActionRuns{Args: []string{"${{ inputs.args }}", "${{ inputs.message }}"}}, + wantCmd: []string{"it's literal", ""}, }, { name: "explicit empty manifest args suppress caller args", @@ -696,7 +467,8 @@ func TestExecAsDockerStageEntrypoint(t *testing.T) { { name: "post stage uses manifest entrypoint", stage: stepStagePost, - runs: model.ActionRuns{PostEntrypoint: "post.sh", Args: []string{"hello"}}, + inputs: map[string]model.Input{"message": {Default: "hello"}}, + runs: model.ActionRuns{PostEntrypoint: "post.sh", Args: []string{"${{ github.job || inputs.message }}"}}, wantCmd: []string{"hello"}, wantEntrypoint: []string{"post.sh"}, }, @@ -705,11 +477,10 @@ func TestExecAsDockerStageEntrypoint(t *testing.T) { hook := logtest.NewWithLevel(logging.LevelWarn) ctx := common.WithLogger(t.Context(), logging.New(hook)) tc.runs.Using, tc.runs.Image = "docker", "docker://node:14" - cm := &containerMock{} var input *container.NewContainerInput ContainerNewContainer = func(in *container.NewContainerInput) container.ExecutionsEnvironment { input = in - return cm + return fakeContainer{} } step := &stepActionRemote{ @@ -717,23 +488,20 @@ func TestExecAsDockerStageEntrypoint(t *testing.T) { RunContext: &RunContext{ Config: &Config{PresetGitHubContext: &model.GithubContext{}}, Run: &model.Run{JobID: "1", Workflow: &model.Workflow{Jobs: map[string]*model.Job{"1": {}}}}, - JobContainer: cm, + JobContainer: &jobContainerMock{}, }, action: &model.Action{Inputs: tc.inputs, Runs: tc.runs}, env: mergeMaps(tc.env), remoteAction: mustNewRemoteAction(t, "org/action@v1"), } - cm.On("Pull", false).Return(func(context.Context) error { return nil }) - cm.On("Remove").Return(func(context.Context) error { return nil }) - cm.On("Create", []string(nil), []string(nil)).Return(func(context.Context) error { return nil }) - cm.On("Start", true).Return(func(context.Context) error { return nil }) - cm.On("Close").Return(func(context.Context) error { return nil }) - - if tc.stage == stepStageMain { - require.NoError(t, runActionImpl(step, "", step.remoteAction)(ctx)) - } else { - require.NoError(t, execAsDocker(ctx, step, "action", "", "", false, tc.stage)) + switch tc.stage { + case stepStageMain: + require.NoError(t, runActionImpl(step)(ctx)) + case stepStagePre: + require.NoError(t, runActionHook(step, stepStagePre)(ctx)) + case stepStagePost: + require.NoError(t, runActionHook(step, stepStagePost)(ctx)) } if tc.warning == "" { assert.Empty(t, hook.AllRecords()) diff --git a/act/runner/cancellation_test.go b/act/runner/cancellation_test.go index 55dcdba4..317c0879 100644 --- a/act/runner/cancellation_test.go +++ b/act/runner/cancellation_test.go @@ -18,143 +18,57 @@ import ( "go.yaml.in/yaml/v4" ) -// TestCancelledJobStatusEnablesAlwaysAndCancelledSteps verifies that once a job is -// cancelled, getJobContext reports the "cancelled" status so the step `if` functions -// evaluate the way GitHub Actions does: cancelled()/always() are true, success()/failure() -// are false. A step that defaults to success() is therefore skipped while an always() step -// still runs. Before the fix the status could only ever be success/failure, so cancelled() -// was structurally impossible and cancel-only cleanup steps never ran. -func TestCancelledJobStatusEnablesAlwaysAndCancelledSteps(t *testing.T) { - rc := createIfTestRunContext(map[string]*model.Job{ - "job1": createJob(t, `runs-on: ubuntu-latest`, ""), - }) - rc.markCancelled() - - // The core fix: the job status context now reports "cancelled" instead of being - // pinned to success/failure. - jobCtx := rc.getJobContext() - require.Equal(t, "cancelled", jobCtx.Status) - - // Feed that status through the step-context expression functions, which is what a - // step `if` evaluates. On a cancelled job only always()/cancelled() are true. - interp := exprparser.NewInterpeter( - &exprparser.EvaluationEnvironment{Job: jobCtx}, - exprparser.Config{Context: "step"}, - ) - for expr, want := range map[string]bool{ - "cancelled()": true, - "always()": true, - "success()": false, - "failure()": false, - "!cancelled()": false, +func TestStepsExecutorRunsMainStepsUnlessSetupFailed(t *testing.T) { + for name, tt := range map[string]struct { + stage, status, result string + cause error + ran []string + }{ + "setup failure": {"pre", "failure", "failure", setupError{assert.AnError}, []string{"pre"}}, + "pre step failure": {"pre", "failure", "failure", assert.AnError, []string{"pre", "main", "always"}}, + "cancel during pre": {"pre", "cancelled", "cancelled", context.Canceled, []string{"pre", "main", "always"}}, + "cancel during main": {"main", "cancelled", "cancelled", context.Canceled, []string{"pre", "main", "always"}}, + "deadline during main": {"main", "cancelled", "failure", context.DeadlineExceeded, []string{"pre", "main", "always"}}, } { - got, err := interp.Evaluate(expr, exprparser.DefaultStatusCheckNone) - require.NoErrorf(t, err, "Evaluate(%q)", expr) - assert.Equalf(t, want, got, "Evaluate(%q) on a cancelled job", expr) - } - - // A step without an `if` defaults to success() and must be skipped on cancel, - // while an `if: always()` step must still run. - disabled, err := interp.Evaluate("", exprparser.DefaultStatusCheckSuccess) - require.NoError(t, err) - assert.Equal(t, false, disabled, "default-success step must be skipped on a cancelled job") - - enabled, err := interp.Evaluate("always()", exprparser.DefaultStatusCheckSuccess) - require.NoError(t, err) - assert.Equal(t, true, enabled, "`if: always()` step must run on a cancelled job") - setJobResult(t.Context(), rc, rc, true) - assert.Equal(t, "cancelled", rc.Run.Job().Result) -} - -func TestMainStepsExecutorRunsAlwaysStepsAfterInterruption(t *testing.T) { - for name, wantError := range map[string]error{"cancel": context.Canceled, "timeout": context.DeadlineExceeded} { t.Run(name, func(t *testing.T) { - rc := createIfTestRunContext(map[string]*model.Job{ - "job1": createJob(t, `runs-on: ubuntu-latest`, ""), - }) - var ctx context.Context - var interrupt func() - if wantError == context.Canceled { - ctx, interrupt = context.WithCancel(t.Context()) - defer interrupt() - } else { - deadline := newControllableDeadlineContext(t.Context()) + rc := makeTestRC(t, "{}") + ctx, interrupt := context.WithCancel(common.WithJobErrorContainer(t.Context())) + defer interrupt() + if tt.cause == context.DeadlineExceeded { + deadline := newControllableDeadlineContext(ctx) ctx, interrupt = deadline, deadline.expire } - var ran []string - var laterStepCtxErr error - err := newMainStepsExecutor(rc, []common.Executor{ - func(_ctx context.Context) error { - ran = append(ran, "step1") - interrupt() - return nil - }, - func(ctx context.Context) error { - ran = append(ran, "always-step") - laterStepCtxErr = ctx.Err() - return nil - }, - })(ctx) - - require.ErrorIs(t, err, wantError) - assert.Equal(t, []string{"step1", "always-step"}, ran) - require.NoError(t, laterStepCtxErr) - assert.Equal(t, wantError == context.Canceled, rc.jobCancelled) - assert.Equal(t, "cancelled", rc.getJobContext().Status) - setJobResult(t.Context(), rc, rc, true) - if wantError == context.DeadlineExceeded { - assert.True(t, rc.jobFailed) - assert.Equal(t, "failure", rc.Run.Job().Result) - } else { - assert.Equal(t, "cancelled", rc.Run.Job().Result) - } - }) - } -} - -func TestStepsExecutorRunsMainStepsAfterPreInterruption(t *testing.T) { - for name, tt := range map[string]struct { - cancel bool - preErr error - wantError error - }{ - "cancel": {cancel: true, wantError: context.Canceled}, - "failure": {preErr: assert.AnError, wantError: assert.AnError}, - } { - t.Run(name, func(t *testing.T) { - rc := createIfTestRunContext(map[string]*model.Job{ - "job1": createJob(t, `runs-on: ubuntu-latest`, ""), - }) - ctx := t.Context() - var cancel context.CancelFunc - if tt.cancel { - ctx, cancel = context.WithCancel(ctx) - defer cancel() - } - - var ran []string - var mainStepCtxErr error - err := newStepsExecutor(rc, []common.Executor{ - func(_ctx context.Context) error { - ran = append(ran, "pre1") - if tt.cancel { - cancel() + phase := func(stage string) common.Executor { + return func(stepCtx context.Context) error { + ran = append(ran, stage) + require.NoError(t, stepCtx.Err()) + switch { + case stage != tt.stage: + case tt.cause == context.Canceled || tt.cause == context.DeadlineExceeded: + interrupt() + default: + reportStepError(stepCtx, rc, tt.cause) + return tt.cause } - return tt.preErr - }, - }, []common.Executor{ - func(ctx context.Context) error { - ran = append(ran, "always-step") - mainStepCtxErr = ctx.Err() return nil - }, - })(ctx) + } + } - require.ErrorIs(t, err, tt.wantError) - assert.Equal(t, []string{"pre1", "always-step"}, ran) - require.NoError(t, mainStepCtxErr) - assert.Equal(t, tt.cancel, rc.jobCancelled) + require.ErrorIs(t, newStepsExecutor(rc, []common.Executor{phase("pre")}, []common.Executor{phase("main"), phase("always")})(ctx), tt.cause) + assert.Equal(t, tt.ran, ran) + assert.Equal(t, tt.cause == context.Canceled, rc.jobCancelled) + jobContext := rc.getJobContext() + assert.Equal(t, tt.status, jobContext.Status) + cancelled := tt.status == "cancelled" + evaluator := exprparser.NewInterpeter(&exprparser.EvaluationEnvironment{Job: jobContext}, exprparser.Config{Context: "step"}) + for condition, want := range map[string]bool{"cancelled()": cancelled, "always()": true, "success()": false, "failure()": !cancelled, "!cancelled()": !cancelled, "": false} { + got, err := evaluator.Evaluate(condition, exprparser.DefaultStatusCheckSuccess) + require.NoError(t, err, condition) + assert.Equal(t, want, got, condition) + } + rc.setJobResult(t.Context(), true) + assert.Equal(t, tt.result, rc.Run.Job().Result) }) } } diff --git a/act/runner/docker_proxy_integration_test.go b/act/runner/docker_proxy_integration_test.go index 8a0687da..58627d56 100644 --- a/act/runner/docker_proxy_integration_test.go +++ b/act/runner/docker_proxy_integration_test.go @@ -62,26 +62,18 @@ func TestDockerProxyMountedJob(t *testing.T) { plan, err = planner.PlanJob("proxy") } 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) { + containers, err := dockerClient.ContainerList(cleanCtx, client.ContainerListOptions{All: true, Filters: make(client.Filters).Add("name", resourceName)}) + assert.NoError(t, err) + assert.Empty(t, containers.Items, "job container survived cleanup") + for _, leftover := range containers.Items { + _, err := dockerClient.ContainerRemove(cleanCtx, leftover.ID, client.ContainerRemoveOptions{Force: true, RemoveVolumes: true}) 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) - } - } + assert.NoError(t, container.NewDockerNetworkRemoveExecutor(resourceName)(cleanCtx)) + assert.NoError(t, container.NewDockerVolumeRemoveExecutor(resourceName, false)(cleanCtx)) }) hook := logtest.New() @@ -94,8 +86,6 @@ func TestDockerProxyMountedJob(t *testing.T) { if mode == "proxy" { require.Contains(t, messages, "docker binds 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) diff --git a/act/runner/expression.go b/act/runner/expression.go index fbfecedb..c6803ad3 100644 --- a/act/runner/expression.go +++ b/act/runner/expression.go @@ -32,54 +32,25 @@ func (rc *RunContext) NewExpressionEvaluator(ctx context.Context) *ExpressionEva } func (rc *RunContext) NewExpressionEvaluatorWithEnv(ctx context.Context, env map[string]string) *ExpressionEvaluator { - var workflowCallResult map[string]*model.WorkflowCallResult + return rc.newExpressionEvaluator(ctx, env, rc.getJobContext(), rc.getGithubContext(ctx), "job") +} - // todo: cleanup EvaluationEnvironment creation - strategy := make(map[string]any) - if rc.Run != nil { - strategy = exprparser.StrategyContext(rc.Run.Job().Strategy, rc.jobIndex, rc.jobTotal) - - // only setup jobs context in case of workflow_call - // and existing expression evaluator (this means, jobs are at - // least ready to run) - if rc.caller != nil && rc.ExprEval != nil { - workflowCallResult = map[string]*model.WorkflowCallResult{} - - for jobName, job := range rc.Run.Workflow.Jobs { - result := model.WorkflowCallResult{ - Outputs: map[string]string{}, - } - unlock := lockJob(job) - maps.Copy(result.Outputs, job.Outputs) - unlock() - workflowCallResult[jobName] = &result - } - } +func (rc *RunContext) newExpressionEvaluator(ctx context.Context, env map[string]string, jobContext *model.JobContext, github *model.GithubContext, scope string) *ExpressionEvaluator { + ee := rc.actionDefaultEnvironment(ctx, github, jobContext) + if scope == "job" { + ee.Jobs = new(map[string]*model.WorkflowCallResult) } - - ghc := rc.getGithubContext(ctx) - ee := &exprparser.EvaluationEnvironment{ - Github: ghc, - Env: env, - Job: rc.getJobContext(), - Jobs: &workflowCallResult, - // todo: should be unavailable - // but required to interpolate/evaluate the step outputs on the job - Steps: rc.StepResults, - Secrets: getWorkflowSecrets(rc), - Vars: rc.Config.Vars, - Strategy: strategy, - Matrix: rc.Matrix, - Needs: exprparser.NeedsContext(rc.Run), - Inputs: getEvaluatorInputs(rc, rc.actionInputs, ghc), - HashFiles: getHashFilesFunction(ctx, rc), - } - ee.Runner = rc.getRunnerContext(ctx) + ee.Env = env + ee.Steps = rc.StepResults + ee.Secrets = getWorkflowSecrets(rc) + ee.Vars = rc.Config.Vars + ee.Needs = exprparser.NeedsContext(rc.Run) + ee.Inputs = rc.getEvaluatorInputs(github) return &expressionEvaluator{ interpreter: exprparser.NewInterpeter(ee, exprparser.Config{ Run: rc.Run, WorkingDir: rc.Config.Workdir, - Context: "job", + Context: scope, }), } } @@ -89,39 +60,26 @@ var hashfiles string // NewStepExpressionEvaluator creates a new evaluator with the `inputs` of the enclosing workflow or composite action func (rc *RunContext) NewStepExpressionEvaluator(ctx context.Context, step step) *ExpressionEvaluator { - return rc.newStepExpressionEvaluator(ctx, step, rc.actionInputs, rc.getJobContext(), getStepGithubContext(ctx, step)) + return rc.newExpressionEvaluator(ctx, *step.getEnv(), rc.getJobContext(), getStepGithubContext(ctx, step), "step") } -// NewActionInputsExpressionEvaluator creates a new evaluator with the step's own with: values as `inputs` -func (rc *RunContext) NewActionInputsExpressionEvaluator(ctx context.Context, step step) *ExpressionEvaluator { - return rc.newStepExpressionEvaluator(ctx, step, inputsFromEnv(*step.getEnv()), rc.getJobContext(), getStepGithubContext(ctx, step)) -} - -func (rc *RunContext) newStepExpressionEvaluator(ctx context.Context, step step, stepInputs map[string]any, jobContext *model.JobContext, github *model.GithubContext) *ExpressionEvaluator { - // todo: cleanup EvaluationEnvironment creation - ee := &exprparser.EvaluationEnvironment{ - Github: github, - Env: *step.getEnv(), - Job: jobContext, - Steps: rc.StepResults, - Secrets: getWorkflowSecrets(rc), - Vars: rc.Config.Vars, - Strategy: exprparser.StrategyContext(rc.Run.Job().Strategy, rc.jobIndex, rc.jobTotal), - Matrix: rc.Matrix, - Needs: exprparser.NeedsContext(rc.Run), - // todo: should be unavailable - // but required to interpolate/evaluate the inputs in actions/composite - Inputs: getEvaluatorInputs(rc, stepInputs, github), +func (rc *RunContext) actionDefaultEnvironment(ctx context.Context, github *model.GithubContext, job *model.JobContext) *exprparser.EvaluationEnvironment { + return &exprparser.EvaluationEnvironment{ + Github: github, + Strategy: exprparser.StrategyContext(rc.Run.Job().Strategy, rc.jobIndex, rc.jobTotal), + Matrix: rc.Matrix, + Job: job, + Runner: rc.getRunnerContext(ctx), HashFiles: getHashFilesFunction(ctx, rc), } - ee.Runner = rc.getRunnerContext(ctx) - return &expressionEvaluator{ - interpreter: exprparser.NewInterpeter(ee, exprparser.Config{ - Run: rc.Run, - WorkingDir: rc.Config.Workdir, - Context: "step", - }), +} + +func newActionInputsExpressionEvaluator(inputs map[string]string) *ExpressionEvaluator { + values := make(map[string]any, len(inputs)) + for name, value := range inputs { + values[name] = value } + return &expressionEvaluator{interpreter: exprparser.NewInterpeter(&exprparser.EvaluationEnvironment{Inputs: values}, exprparser.Config{Context: "step"})} } func getHashFilesFunction(ctx context.Context, rc *RunContext) func(v []reflect.Value) (any, error) { @@ -160,18 +118,17 @@ func getHashFilesFunction(ctx context.Context, rc *RunContext) func(v []reflect. Mode: 0o644, Body: hashfiles, }).Then(rc.JobContainer.Exec([]string{"node", container.JoinPath(rc.JobContainer.GetActPath(), name)}, env, "", ""))(timeoutCtx) - quotedPatterns := expressionStringEscape(strings.Join(patterns, ", ")) switch { case err == nil: case ctx.Err() != nil: return "", ctx.Err() case timeoutCtx.Err() != nil || errors.Is(err, context.DeadlineExceeded): - return "", fmt.Errorf("hashFiles('%s') couldn't finish within 120 seconds", quotedPatterns) + return "", fmt.Errorf("hashFiles('%s') couldn't finish within 120 seconds", expressionStringEscape(strings.Join(patterns, ", "))) case hashFilesNodeMissing(err): common.Logger(ctx).With(rawOutputField, true).Warnf("##[warning]hashFiles could not run because node is unavailable in the job environment. Returning an empty string.") return "", nil default: - return "", fmt.Errorf("hashFiles('%s') failed. Fail to hash files under directory '%s'", quotedPatterns, rc.githubWorkspace()) + return "", fmt.Errorf("hashFiles('%s') failed. Fail to hash files under directory '%s'", expressionStringEscape(strings.Join(patterns, ", ")), rc.githubWorkspace()) } for line := range strings.Lines(hout.String() + "\n" + herr.String()) { if hash, ok := strings.CutPrefix(strings.TrimRight(line, "\r\n"), "__OUTPUT__"); ok { @@ -253,9 +210,12 @@ func inputsFromEnv(env map[string]string) map[string]any { return inputs } -func getEvaluatorInputs(rc *RunContext, stepInputs map[string]any, ghc *model.GithubContext) map[string]any { - if stepInputs != nil { // an action's own inputs, which workflow inputs must not shadow - return maps.Clone(stepInputs) +func (rc *RunContext) getEvaluatorInputs(ghc *model.GithubContext) map[string]any { + if rc.actionInputs != nil { + return maps.Clone(rc.actionInputs) + } + if rc.caller != nil { + return maps.Clone(rc.caller.inputs) } // only a called workflow's job itself takes the inputs Gitea resolved, // composite actions copy its Config but have their own `inputs` @@ -264,7 +224,6 @@ func getEvaluatorInputs(rc *RunContext, stepInputs map[string]any, ghc *model.Gi } inputs := map[string]any{} - maps.Copy(inputs, rc.workflowCallInputs) switch ghc.EventName { case "workflow_dispatch": @@ -292,36 +251,39 @@ func setEvaluatorInput(inputs map[string]any, ghc *model.GithubContext, name str inputs[name] = model.CoerceInputValue(value, input.Type) } -// resolveWorkflowCall evaluates the caller's with: and secrets: once, as the server does before dispatching a called workflow. +func (c *caller) resolveInputs(ctx context.Context, workflow *model.Workflow) error { + rc := c.runContext + callerEval := rc.ExprEval.shared(ctx) + var callerWith map[string]any + if err := model.DecodeEvaluated("workflow inputs", rc.Run.Job().RawWith, callerEval.EvaluateYamlNode, &callerWith); err != nil { + return err + } + c.workflowCallConfig = workflow.WorkflowCallConfig() + var err error + if c.inputs, err = callerEval.ResolveWorkflowCallInputs(c.workflowCallConfig, callerWith); err != nil { + common.Logger(ctx).Warn(err) + } + return nil +} + func (rc *RunContext) resolveWorkflowCall(ctx context.Context) error { if rc.caller == nil { return nil } logger := common.Logger(ctx) - callerJob := rc.caller.runContext.Run.Job() - callerEval := rc.caller.runContext.ExprEval.shared(ctx) - var callerWith map[string]any - if err := model.DecodeEvaluated("workflow inputs", callerJob.RawWith, callerEval.EvaluateYamlNode, &callerWith); err != nil { - return err - } - if !rc.Run.Workflow.IsWorkflowCall() { - logger.Warn("workflow_call key is not defined in the referenced workflow") - } - config := rc.Run.Workflow.WorkflowCallConfig() - var err error - if rc.workflowCallInputs, err = callerEval.ResolveWorkflowCallInputs(config, callerWith); err != nil { - logger.Warn(err) - } + caller := rc.caller.runContext + callerJob := caller.Run.Job() if callerJob.InheritSecrets() { - rc.workflowCallSecrets = getWorkflowSecrets(rc.caller.runContext) + rc.workflowCallSecrets = getWorkflowSecrets(caller) return nil } secrets := callerJob.Secrets() - if err := config.ValidateSecrets(secrets); err != nil { + if err := rc.caller.workflowCallConfig.ValidateSecrets(secrets); err != nil { logger.Warn(err) } - if rc.workflowCallSecrets, err = callerEval.EvaluateCallerSecrets(secrets); err != nil { + var err error + if rc.workflowCallSecrets, err = caller.ExprEval.shared(ctx).EvaluateCallerSecrets(secrets); err != nil { return fmt.Errorf("unable to interpolate %w", err) } for _, name := range []string{"GITHUB_TOKEN", "GITEA_TOKEN"} { diff --git a/act/runner/expression_test.go b/act/runner/expression_test.go index 642b2cb6..82a8bdd3 100644 --- a/act/runner/expression_test.go +++ b/act/runner/expression_test.go @@ -10,9 +10,9 @@ import ( "errors" "fmt" "io" + "os/exec" "reflect" "strings" - "sync" "testing" "time" @@ -178,6 +178,15 @@ func (c *hashFilesContainer) ReplaceLogWriter(stdout, stderr io.Writer) (io.Writ } func TestGetHashFilesFunction(t *testing.T) { + t.Run("regular file with trailing slash", func(t *testing.T) { + requireHostTools(t, "node") + cmd := exec.CommandContext(t.Context(), "node", "hashfiles/index.js") + cmd.Env = []string{"patterns=hashfiles/index.js/"} + output, err := cmd.CombinedOutput() + require.NoError(t, err) + assert.Contains(t, string(output), "__OUTPUT____OUTPUT__") + }) + const failureMessage = "hashFiles('dir''file, *.sum, 123, true, ') failed. Fail to hash files under directory '/workspace'" for _, test := range []struct { name string @@ -422,7 +431,7 @@ func TestGetEvaluatorInputsBoolean(t *testing.T) { } ghc := &model.GithubContext{EventName: eventName, Event: table.event} - inputs := getEvaluatorInputs(rc, nil, ghc) + inputs := rc.getEvaluatorInputs(ghc) assert.Equal(t, table.flag, inputs["flag"]) assert.Equal(t, "gitea", inputs["name"]) assert.Equal(t, false, inputs["unset"]) @@ -432,6 +441,7 @@ func TestGetEvaluatorInputsBoolean(t *testing.T) { t.Run("deferred workflow call inputs", func(t *testing.T) { workflow, err := model.ReadWorkflow(strings.NewReader(workflow("workflow_call") + ` + workflow_dispatch: {inputs: {name: {type: string, default: dispatch}}} jobs: test: {} call: @@ -447,9 +457,11 @@ jobs: t.Parallel() parent, err := (&runnerImpl{config: &Config{PresetGitHubContext: &model.GithubContext{}}}).newRunContext(t.Context(), &model.Run{Workflow: workflow, JobID: "call"}, map[string]any{"args": `{"flag":` + value + `,"name":"${{ 'runner' }}"}`}) require.NoError(t, err) - child, err := (&runnerImpl{config: &Config{PresetGitHubContext: &model.GithubContext{}}, caller: &caller{runContext: parent}}).newRunContext(t.Context(), &model.Run{Workflow: workflow, JobID: "test"}, nil) + call := &caller{runContext: parent} + require.NoError(t, call.resolveInputs(t.Context(), workflow)) + child, err := (&runnerImpl{config: parent.Config, caller: call}).newRunContext(t.Context(), &model.Run{Workflow: workflow, JobID: "test"}, nil) require.NoError(t, err) - assert.Equal(t, map[string]any{"flag": value == "true", "name": "${{ 'runner' }}", "unset": false}, child.workflowCallInputs) + assert.Equal(t, map[string]any{"flag": value == "true", "name": "${{ 'runner' }}", "unset": false}, child.getEvaluatorInputs(&model.GithubContext{EventName: "workflow_dispatch"})) assert.Equal(t, rawWith, job.RawWith) assert.Nil(t, job.With) }) @@ -472,10 +484,10 @@ on: ghc := &model.GithubContext{EventName: "workflow_dispatch", Event: map[string]any{"inputs": map[string]any{"name": "dispatch"}}} job := &RunContext{Config: config, Run: &model.Run{JobID: "job1", Workflow: wf}} - assert.Equal(t, map[string]any{"name": "caller", "target": "dispatch"}, getEvaluatorInputs(job, nil, ghc)) + assert.Equal(t, map[string]any{"name": "caller", "target": "dispatch"}, job.getEvaluatorInputs(ghc)) - composite := &RunContext{Config: config, Run: &model.Run{JobID: "job1", Workflow: &model.Workflow{}}, Parent: job} - assert.Equal(t, map[string]any{"arg": "x"}, getEvaluatorInputs(composite, map[string]any{"arg": "x"}, ghc)) + composite := &RunContext{Config: config, Parent: job, actionInputs: map[string]any{"arg": "x"}} + assert.Equal(t, map[string]any{"arg": "x"}, composite.getEvaluatorInputs(ghc)) } func TestActionInputsShadowDispatchInputs(t *testing.T) { @@ -491,16 +503,16 @@ jobs: rc := newTestRC(wf, nil) rc.Config.EventName = "workflow_dispatch" rc.EventJSON = `{"inputs":{"message":"workflow"}}` - step := &stepActionRemote{RunContext: rc, env: map[string]string{"INPUT_MESSAGE": "step"}} - assert.Equal(t, "step", rc.NewActionInputsExpressionEvaluator(t.Context(), step).InterpolateName(t.Context(), "${{ inputs.message }}")) - assert.Equal(t, "workflow", rc.NewStepExpressionEvaluator(t.Context(), step).InterpolateName(t.Context(), "${{ inputs.message }}")) + step := &stepActionRemote{RunContext: rc, Step: &model.Step{}, env: map[string]string{"INPUT_EXTRA": "inherited"}} + inputs, err := rc.resolveActionInputs(t.Context(), step, &model.Action{Inputs: map[string]model.Input{ + "message": {Default: "${{ env.INPUT_EXTRA || gitea.event_name }}"}, + }}) + require.NoError(t, err) + applyActionInputs(step, inputs) + assert.Equal(t, "workflow_dispatch|", newActionInputsExpressionEvaluator(inputs).InterpolateName(t.Context(), "${{ inputs.message }}|${{ inputs.extra || gitea.event_name }}")) enabled, err := isStepEnabled(t.Context(), "inputs.message == 'workflow'", step, stepStageMain) require.NoError(t, err) assert.True(t, enabled) - step.Step, step.action = &model.Step{}, &model.Action{Inputs: map[string]model.Input{"fallback": {Default: "${{ inputs.message }}"}}} - env, err := evaluateCompositeInputAndEnv(t.Context(), rc, step) - require.NoError(t, err) - assert.Equal(t, "workflow", env["INPUT_FALLBACK"]) } func TestResolveWorkflowCallToleratesMismatchesAndPassesSecretsAndTokens(t *testing.T) { @@ -534,26 +546,30 @@ jobs: PresetGitHubContext: &model.GithubContext{}, RuntimeTokens: map[*model.Workflow]string{callerWorkflow: "caller-run"}, } - resolve := func(callerJobID string, workflow *model.Workflow) *RunContext { - parent, err := (&runnerImpl{config: config}).newRunContext(t.Context(), &model.Run{Workflow: callerWorkflow, JobID: callerJobID}, nil) - require.NoError(t, err) - child, err := (&runnerImpl{config: config, caller: &caller{runContext: parent}}).newRunContext(t.Context(), &model.Run{Workflow: workflow, JobID: "test"}, nil) + call := func(parent *RunContext, workflow *model.Workflow) *RunContext { + state := &caller{runContext: parent} + require.NoError(t, state.resolveInputs(t.Context(), workflow)) + child, err := (&runnerImpl{config: config, caller: state}).newRunContext(t.Context(), &model.Run{Workflow: workflow, JobID: "test"}, nil) require.NoError(t, err) return child } + resolve := func(callerJobID string, workflow *model.Workflow) *RunContext { + parent, err := (&runnerImpl{config: config}).newRunContext(t.Context(), &model.Run{Workflow: callerWorkflow, JobID: callerJobID}, nil) + require.NoError(t, err) + return call(parent, workflow) + } called := resolve("call", callee) - assert.Equal(t, map[string]any{"flag": true}, called.workflowCallInputs) + assert.Equal(t, map[string]any{"flag": true}, called.caller.inputs) assert.Equal(t, map[string]string{"undeclared": "${{ github.token }}", "GITHUB_TOKEN": "github-token", "GITEA_TOKEN": "gitea-token"}, called.workflowCallSecrets) assert.Equal(t, "caller-run", called.GetEnv()["ACTIONS_RUNTIME_TOKEN"]) inherited := resolve("inherit", notCallable) - assert.Empty(t, inherited.workflowCallInputs) + assert.Empty(t, inherited.caller.inputs) assert.Equal(t, map[string]string{"token": "${{ github.token }}", "GITHUB_TOKEN": "github-token", "GITEA_TOKEN": "gitea-token", "ACTIONS_RUNTIME_TOKEN": "caller-run"}, inherited.workflowCallSecrets) assert.Equal(t, "${{ github.token }}:", resolve("override", callee).ExprEval.InterpolateName(t.Context(), "${{ secrets.GITHUB_TOKEN }}:${{ secrets.GITEA_TOKEN }}")) middle, err := model.ReadWorkflow(strings.NewReader("on: workflow_call\njobs:\n test: {uses: ./reuse.yml}\n")) require.NoError(t, err) - nested, err := (&runnerImpl{config: config, caller: &caller{runContext: resolve("override", middle)}}).newRunContext(t.Context(), &model.Run{Workflow: callee, JobID: "test"}, nil) - require.NoError(t, err) + nested := call(resolve("override", middle), callee) assert.Equal(t, "github-token:gitea-token", nested.ExprEval.InterpolateName(t.Context(), "${{ secrets.GITHUB_TOKEN }}:${{ secrets.GITEA_TOKEN }}")) } @@ -579,22 +595,3 @@ jobs: assert.NotContains(t, a, "s3cr3t") assert.NotEqual(t, a, b) } - -func TestNewExpressionEvaluatorReadsJobOutputsWhileCombinationsWriteThem(t *testing.T) { - rc := createRunContext(t) - rc.caller = &caller{runContext: createRunContext(t)} - rc.ExprEval = rc.NewExpressionEvaluator(t.Context()) - job := rc.Run.Job() - var writes sync.WaitGroup - writes.Go(func() { - for range 100 { - unlock := lockJob(job) - job.Outputs = map[string]string{"out": "value"} - unlock() - } - }) - for range 100 { - rc.NewExpressionEvaluator(t.Context()) - } - writes.Wait() -} diff --git a/act/runner/hashfiles/index.js b/act/runner/hashfiles/index.js index c26f783f..e912953f 100644 --- a/act/runner/hashfiles/index.js +++ b/act/runner/hashfiles/index.js @@ -1,11 +1,44 @@ /******/ (() => { // webpackBootstrap /******/ var __webpack_modules__ = ({ -/***/ 2627: +/***/ 4711: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { @@ -22,23 +55,16 @@ var __asyncValues = (this && this.__asyncValues) || function (o) { function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } }; -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; Object.defineProperty(exports, "__esModule", ({ value: true })); -const crypto = __importStar(__nccwpck_require__(6113)); -const fs = __importStar(__nccwpck_require__(7147)); -const glob = __importStar(__nccwpck_require__(8090)); -const path = __importStar(__nccwpck_require__(1017)); -const stream = __importStar(__nccwpck_require__(2781)); -const util = __importStar(__nccwpck_require__(3837)); +const crypto = __importStar(__nccwpck_require__(6982)); +const fs = __importStar(__nccwpck_require__(9896)); +const glob = __importStar(__nccwpck_require__(7206)); +const path = __importStar(__nccwpck_require__(6928)); +const stream = __importStar(__nccwpck_require__(2203)); +const util = __importStar(__nccwpck_require__(9023)); function run() { - var e_1, _a; return __awaiter(this, void 0, void 0, function* () { + var _a, e_1, _b, _c; // arg0 -> node // arg1 -> hashFiles.js // env[followSymbolicLinks] = true/null @@ -56,8 +82,10 @@ function run() { let count = 0; const globber = yield glob.create(matchPatterns, { followSymbolicLinks }); try { - for (var _b = __asyncValues(globber.globGenerator()), _c; _c = yield _b.next(), !_c.done;) { - const file = _c.value; + for (var _d = true, _e = __asyncValues(globber.globGenerator()), _f; _f = yield _e.next(), _a = _f.done, !_a; _d = true) { + _c = _f.value; + _d = false; + const file = _c; console.log(file); if (!file.startsWith(`${githubWorkspace}${path.sep}`)) { console.log(`Ignore '${file}' since it is not under GITHUB_WORKSPACE.`); @@ -80,7 +108,7 @@ function run() { catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { - if (_c && !_c.done && (_a = _b.return)) yield _a.call(_b); + if (!_d && !_a && (_b = _e.return)) yield _b.call(_e); } finally { if (e_1) throw e_1.error; } } @@ -94,20 +122,23 @@ function run() { } }); } -run() - .then(out => { - console.log(out); - process.exit(0); -}) - .catch(err => { - console.error(err); - process.exit(1); -}); +; +(() => __awaiter(void 0, void 0, void 0, function* () { + try { + const out = yield run(); + console.log(out); + process.exit(0); + } + catch (err) { + console.error(err); + process.exit(1); + } +}))(); /***/ }), -/***/ 7351: +/***/ 4914: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -133,8 +164,8 @@ var __importStar = (this && this.__importStar) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.issue = exports.issueCommand = void 0; -const os = __importStar(__nccwpck_require__(2037)); -const utils_1 = __nccwpck_require__(5278); +const os = __importStar(__nccwpck_require__(857)); +const utils_1 = __nccwpck_require__(302); /** * Commands * @@ -206,7 +237,7 @@ function escapeProperty(s) { /***/ }), -/***/ 2186: +/***/ 7484: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -241,13 +272,12 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getIDToken = exports.getState = exports.saveState = exports.group = exports.endGroup = exports.startGroup = exports.info = exports.notice = exports.warning = exports.error = exports.debug = exports.isDebug = exports.setFailed = exports.setCommandEcho = exports.setOutput = exports.getBooleanInput = exports.getMultilineInput = exports.getInput = exports.addPath = exports.setSecret = exports.exportVariable = exports.ExitCode = void 0; -const command_1 = __nccwpck_require__(7351); -const file_command_1 = __nccwpck_require__(717); -const utils_1 = __nccwpck_require__(5278); -const os = __importStar(__nccwpck_require__(2037)); -const path = __importStar(__nccwpck_require__(1017)); -const uuid_1 = __nccwpck_require__(5840); -const oidc_utils_1 = __nccwpck_require__(8041); +const command_1 = __nccwpck_require__(4914); +const file_command_1 = __nccwpck_require__(4753); +const utils_1 = __nccwpck_require__(302); +const os = __importStar(__nccwpck_require__(857)); +const path = __importStar(__nccwpck_require__(6928)); +const oidc_utils_1 = __nccwpck_require__(5306); /** * The code to exit an action */ @@ -276,20 +306,9 @@ function exportVariable(name, val) { process.env[name] = convertedVal; const filePath = process.env['GITHUB_ENV'] || ''; if (filePath) { - const delimiter = `ghadelimiter_${uuid_1.v4()}`; - // These should realistically never happen, but just in case someone finds a way to exploit uuid generation let's not allow keys or values that contain the delimiter. - if (name.includes(delimiter)) { - throw new Error(`Unexpected input: name should not contain the delimiter "${delimiter}"`); - } - if (convertedVal.includes(delimiter)) { - throw new Error(`Unexpected input: value should not contain the delimiter "${delimiter}"`); - } - const commandValue = `${name}<<${delimiter}${os.EOL}${convertedVal}${os.EOL}${delimiter}`; - file_command_1.issueCommand('ENV', commandValue); - } - else { - command_1.issueCommand('set-env', { name }, convertedVal); + return file_command_1.issueFileCommand('ENV', file_command_1.prepareKeyValueMessage(name, val)); } + command_1.issueCommand('set-env', { name }, convertedVal); } exports.exportVariable = exportVariable; /** @@ -307,7 +326,7 @@ exports.setSecret = setSecret; function addPath(inputPath) { const filePath = process.env['GITHUB_PATH'] || ''; if (filePath) { - file_command_1.issueCommand('PATH', inputPath); + file_command_1.issueFileCommand('PATH', inputPath); } else { command_1.issueCommand('add-path', {}, inputPath); @@ -347,7 +366,10 @@ function getMultilineInput(name, options) { const inputs = getInput(name, options) .split('\n') .filter(x => x !== ''); - return inputs; + if (options && options.trimWhitespace === false) { + return inputs; + } + return inputs.map(input => input.trim()); } exports.getMultilineInput = getMultilineInput; /** @@ -380,8 +402,12 @@ exports.getBooleanInput = getBooleanInput; */ // eslint-disable-next-line @typescript-eslint/no-explicit-any function setOutput(name, value) { + const filePath = process.env['GITHUB_OUTPUT'] || ''; + if (filePath) { + return file_command_1.issueFileCommand('OUTPUT', file_command_1.prepareKeyValueMessage(name, value)); + } process.stdout.write(os.EOL); - command_1.issueCommand('set-output', { name }, value); + command_1.issueCommand('set-output', { name }, utils_1.toCommandValue(value)); } exports.setOutput = setOutput; /** @@ -510,7 +536,11 @@ exports.group = group; */ // eslint-disable-next-line @typescript-eslint/no-explicit-any function saveState(name, value) { - command_1.issueCommand('save-state', { name }, value); + const filePath = process.env['GITHUB_STATE'] || ''; + if (filePath) { + return file_command_1.issueFileCommand('STATE', file_command_1.prepareKeyValueMessage(name, value)); + } + command_1.issueCommand('save-state', { name }, utils_1.toCommandValue(value)); } exports.saveState = saveState; /** @@ -532,17 +562,17 @@ exports.getIDToken = getIDToken; /** * Summary exports */ -var summary_1 = __nccwpck_require__(1327); +var summary_1 = __nccwpck_require__(1847); Object.defineProperty(exports, "summary", ({ enumerable: true, get: function () { return summary_1.summary; } })); /** * @deprecated use core.summary */ -var summary_2 = __nccwpck_require__(1327); +var summary_2 = __nccwpck_require__(1847); Object.defineProperty(exports, "markdownSummary", ({ enumerable: true, get: function () { return summary_2.markdownSummary; } })); /** * Path exports */ -var path_utils_1 = __nccwpck_require__(2981); +var path_utils_1 = __nccwpck_require__(1976); Object.defineProperty(exports, "toPosixPath", ({ enumerable: true, get: function () { return path_utils_1.toPosixPath; } })); Object.defineProperty(exports, "toWin32Path", ({ enumerable: true, get: function () { return path_utils_1.toWin32Path; } })); Object.defineProperty(exports, "toPlatformPath", ({ enumerable: true, get: function () { return path_utils_1.toPlatformPath; } })); @@ -550,7 +580,7 @@ Object.defineProperty(exports, "toPlatformPath", ({ enumerable: true, get: funct /***/ }), -/***/ 717: +/***/ 4753: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -576,13 +606,14 @@ var __importStar = (this && this.__importStar) || function (mod) { return result; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.issueCommand = void 0; +exports.prepareKeyValueMessage = exports.issueFileCommand = void 0; // We use any as a valid input type /* eslint-disable @typescript-eslint/no-explicit-any */ -const fs = __importStar(__nccwpck_require__(7147)); -const os = __importStar(__nccwpck_require__(2037)); -const utils_1 = __nccwpck_require__(5278); -function issueCommand(command, message) { +const fs = __importStar(__nccwpck_require__(9896)); +const os = __importStar(__nccwpck_require__(857)); +const uuid_1 = __nccwpck_require__(2048); +const utils_1 = __nccwpck_require__(302); +function issueFileCommand(command, message) { const filePath = process.env[`GITHUB_${command}`]; if (!filePath) { throw new Error(`Unable to find environment variable for file command ${command}`); @@ -594,12 +625,27 @@ function issueCommand(command, message) { encoding: 'utf8' }); } -exports.issueCommand = issueCommand; +exports.issueFileCommand = issueFileCommand; +function prepareKeyValueMessage(key, value) { + const delimiter = `ghadelimiter_${uuid_1.v4()}`; + const convertedValue = utils_1.toCommandValue(value); + // These should realistically never happen, but just in case someone finds a + // way to exploit uuid generation let's not allow keys or values that contain + // the delimiter. + if (key.includes(delimiter)) { + throw new Error(`Unexpected input: name should not contain the delimiter "${delimiter}"`); + } + if (convertedValue.includes(delimiter)) { + throw new Error(`Unexpected input: value should not contain the delimiter "${delimiter}"`); + } + return `${key}<<${delimiter}${os.EOL}${convertedValue}${os.EOL}${delimiter}`; +} +exports.prepareKeyValueMessage = prepareKeyValueMessage; //# sourceMappingURL=file-command.js.map /***/ }), -/***/ 8041: +/***/ 5306: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -615,9 +661,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.OidcClient = void 0; -const http_client_1 = __nccwpck_require__(6255); -const auth_1 = __nccwpck_require__(5526); -const core_1 = __nccwpck_require__(2186); +const http_client_1 = __nccwpck_require__(4844); +const auth_1 = __nccwpck_require__(4552); +const core_1 = __nccwpck_require__(7484); class OidcClient { static createHttpClient(allowRetry = true, maxRetry = 10) { const requestOptions = { @@ -683,7 +729,7 @@ exports.OidcClient = OidcClient; /***/ }), -/***/ 2981: +/***/ 1976: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -709,7 +755,7 @@ var __importStar = (this && this.__importStar) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.toPlatformPath = exports.toWin32Path = exports.toPosixPath = void 0; -const path = __importStar(__nccwpck_require__(1017)); +const path = __importStar(__nccwpck_require__(6928)); /** * toPosixPath converts the given path to the posix form. On Windows, \\ will be * replaced with /. @@ -748,7 +794,7 @@ exports.toPlatformPath = toPlatformPath; /***/ }), -/***/ 1327: +/***/ 1847: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -764,8 +810,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.summary = exports.markdownSummary = exports.SUMMARY_DOCS_URL = exports.SUMMARY_ENV_VAR = void 0; -const os_1 = __nccwpck_require__(2037); -const fs_1 = __nccwpck_require__(7147); +const os_1 = __nccwpck_require__(857); +const fs_1 = __nccwpck_require__(9896); const { access, appendFile, writeFile } = fs_1.promises; exports.SUMMARY_ENV_VAR = 'GITHUB_STEP_SUMMARY'; exports.SUMMARY_DOCS_URL = 'https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#adding-a-job-summary'; @@ -1038,7 +1084,7 @@ exports.summary = _summary; /***/ }), -/***/ 5278: +/***/ 302: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -1085,7 +1131,7 @@ exports.toCommandProperties = toCommandProperties; /***/ }), -/***/ 8090: +/***/ 7206: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -1100,7 +1146,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); -const internal_globber_1 = __nccwpck_require__(8298); +exports.hashFiles = exports.create = void 0; +const internal_globber_1 = __nccwpck_require__(103); +const internal_hash_files_1 = __nccwpck_require__(3608); /** * Constructs a globber * @@ -1113,17 +1161,56 @@ function create(patterns, options) { }); } exports.create = create; +/** + * Computes the sha256 hash of a glob + * + * @param patterns Patterns separated by newlines + * @param currentWorkspace Workspace used when matching files + * @param options Glob options + * @param verbose Enables verbose logging + */ +function hashFiles(patterns, currentWorkspace = '', options, verbose = false) { + return __awaiter(this, void 0, void 0, function* () { + let followSymbolicLinks = true; + if (options && typeof options.followSymbolicLinks === 'boolean') { + followSymbolicLinks = options.followSymbolicLinks; + } + const globber = yield create(patterns, { followSymbolicLinks }); + return internal_hash_files_1.hashFiles(globber, currentWorkspace, verbose); + }); +} +exports.hashFiles = hashFiles; //# sourceMappingURL=glob.js.map /***/ }), -/***/ 1026: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 8164: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; Object.defineProperty(exports, "__esModule", ({ value: true })); -const core = __nccwpck_require__(2186); +exports.getOptions = void 0; +const core = __importStar(__nccwpck_require__(7484)); /** * Returns a copy with defaults filled in. */ @@ -1131,6 +1218,7 @@ function getOptions(copy) { const result = { followSymbolicLinks: true, implicitDescendants: true, + matchDirectories: true, omitBrokenSymbolicLinks: true }; if (copy) { @@ -1142,6 +1230,10 @@ function getOptions(copy) { result.implicitDescendants = copy.implicitDescendants; core.debug(`implicitDescendants '${result.implicitDescendants}'`); } + if (typeof copy.matchDirectories === 'boolean') { + result.matchDirectories = copy.matchDirectories; + core.debug(`matchDirectories '${result.matchDirectories}'`); + } if (typeof copy.omitBrokenSymbolicLinks === 'boolean') { result.omitBrokenSymbolicLinks = copy.omitBrokenSymbolicLinks; core.debug(`omitBrokenSymbolicLinks '${result.omitBrokenSymbolicLinks}'`); @@ -1154,11 +1246,30 @@ exports.getOptions = getOptions; /***/ }), -/***/ 8298: +/***/ 103: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { @@ -1188,14 +1299,15 @@ var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _ar function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; Object.defineProperty(exports, "__esModule", ({ value: true })); -const core = __nccwpck_require__(2186); -const fs = __nccwpck_require__(7147); -const globOptionsHelper = __nccwpck_require__(1026); -const path = __nccwpck_require__(1017); -const patternHelper = __nccwpck_require__(9005); -const internal_match_kind_1 = __nccwpck_require__(1063); -const internal_pattern_1 = __nccwpck_require__(4536); -const internal_search_state_1 = __nccwpck_require__(9117); +exports.DefaultGlobber = void 0; +const core = __importStar(__nccwpck_require__(7484)); +const fs = __importStar(__nccwpck_require__(9896)); +const globOptionsHelper = __importStar(__nccwpck_require__(8164)); +const path = __importStar(__nccwpck_require__(6928)); +const patternHelper = __importStar(__nccwpck_require__(8891)); +const internal_match_kind_1 = __nccwpck_require__(2644); +const internal_pattern_1 = __nccwpck_require__(5370); +const internal_search_state_1 = __nccwpck_require__(9890); const IS_WINDOWS = process.platform === 'win32'; class DefaultGlobber { constructor(options) { @@ -1238,7 +1350,7 @@ class DefaultGlobber { if (options.implicitDescendants && (pattern.trailingSeparator || pattern.segments[pattern.segments.length - 1] !== '**')) { - patterns.push(new internal_pattern_1.Pattern(pattern.negate, pattern.segments.concat('**'))); + patterns.push(new internal_pattern_1.Pattern(pattern.negate, true, pattern.segments.concat('**'))); } } // Push the search paths @@ -1281,7 +1393,7 @@ class DefaultGlobber { // Directory if (stats.isDirectory()) { // Matched - if (match & internal_match_kind_1.MatchKind.Directory) { + if (match & internal_match_kind_1.MatchKind.Directory && options.matchDirectories) { yield yield __await(item.path); } // Descend? @@ -1376,12 +1488,117 @@ exports.DefaultGlobber = DefaultGlobber; /***/ }), -/***/ 1063: +/***/ 3608: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __asyncValues = (this && this.__asyncValues) || function (o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.hashFiles = void 0; +const crypto = __importStar(__nccwpck_require__(6982)); +const core = __importStar(__nccwpck_require__(7484)); +const fs = __importStar(__nccwpck_require__(9896)); +const stream = __importStar(__nccwpck_require__(2203)); +const util = __importStar(__nccwpck_require__(9023)); +const path = __importStar(__nccwpck_require__(6928)); +function hashFiles(globber, currentWorkspace, verbose = false) { + var e_1, _a; + var _b; + return __awaiter(this, void 0, void 0, function* () { + const writeDelegate = verbose ? core.info : core.debug; + let hasMatch = false; + const githubWorkspace = currentWorkspace + ? currentWorkspace + : (_b = process.env['GITHUB_WORKSPACE']) !== null && _b !== void 0 ? _b : process.cwd(); + const result = crypto.createHash('sha256'); + let count = 0; + try { + for (var _c = __asyncValues(globber.globGenerator()), _d; _d = yield _c.next(), !_d.done;) { + const file = _d.value; + writeDelegate(file); + if (!file.startsWith(`${githubWorkspace}${path.sep}`)) { + writeDelegate(`Ignore '${file}' since it is not under GITHUB_WORKSPACE.`); + continue; + } + if (fs.statSync(file).isDirectory()) { + writeDelegate(`Skip directory '${file}'.`); + continue; + } + const hash = crypto.createHash('sha256'); + const pipeline = util.promisify(stream.pipeline); + yield pipeline(fs.createReadStream(file), hash); + result.write(hash.digest()); + count++; + if (!hasMatch) { + hasMatch = true; + } + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (_d && !_d.done && (_a = _c.return)) yield _a.call(_c); + } + finally { if (e_1) throw e_1.error; } + } + result.end(); + if (hasMatch) { + writeDelegate(`Found ${count} files to hash.`); + return result.digest('hex'); + } + else { + writeDelegate(`No matches found for glob`); + return ''; + } + }); +} +exports.hashFiles = hashFiles; +//# sourceMappingURL=internal-hash-files.js.map + +/***/ }), + +/***/ 2644: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.MatchKind = void 0; /** * Indicates whether a pattern matches a path */ @@ -1400,14 +1617,37 @@ var MatchKind; /***/ }), -/***/ 1849: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 4138: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; Object.defineProperty(exports, "__esModule", ({ value: true })); -const assert = __nccwpck_require__(9491); -const path = __nccwpck_require__(1017); +exports.safeTrimTrailingSeparator = exports.normalizeSeparators = exports.hasRoot = exports.hasAbsoluteRoot = exports.ensureAbsoluteRoot = exports.dirname = void 0; +const path = __importStar(__nccwpck_require__(6928)); +const assert_1 = __importDefault(__nccwpck_require__(2613)); const IS_WINDOWS = process.platform === 'win32'; /** * Similar to path.dirname except normalizes the path separators and slightly better handling for Windows UNC paths. @@ -1447,8 +1687,8 @@ exports.dirname = dirname; * or `C:` are expanded based on the current working directory. */ function ensureAbsoluteRoot(root, itemPath) { - assert(root, `ensureAbsoluteRoot parameter 'root' must not be empty`); - assert(itemPath, `ensureAbsoluteRoot parameter 'itemPath' must not be empty`); + assert_1.default(root, `ensureAbsoluteRoot parameter 'root' must not be empty`); + assert_1.default(itemPath, `ensureAbsoluteRoot parameter 'itemPath' must not be empty`); // Already rooted if (hasAbsoluteRoot(itemPath)) { return itemPath; @@ -1458,7 +1698,7 @@ function ensureAbsoluteRoot(root, itemPath) { // Check for itemPath like C: or C:foo if (itemPath.match(/^[A-Z]:[^\\/]|^[A-Z]:$/i)) { let cwd = process.cwd(); - assert(cwd.match(/^[A-Z]:\\/i), `Expected current directory to start with an absolute drive root. Actual '${cwd}'`); + assert_1.default(cwd.match(/^[A-Z]:\\/i), `Expected current directory to start with an absolute drive root. Actual '${cwd}'`); // Drive letter matches cwd? Expand to cwd if (itemPath[0].toUpperCase() === cwd[0].toUpperCase()) { // Drive only, e.g. C: @@ -1483,11 +1723,11 @@ function ensureAbsoluteRoot(root, itemPath) { // Check for itemPath like \ or \foo else if (normalizeSeparators(itemPath).match(/^\\$|^\\[^\\]/)) { const cwd = process.cwd(); - assert(cwd.match(/^[A-Z]:\\/i), `Expected current directory to start with an absolute drive root. Actual '${cwd}'`); + assert_1.default(cwd.match(/^[A-Z]:\\/i), `Expected current directory to start with an absolute drive root. Actual '${cwd}'`); return `${cwd[0]}:\\${itemPath.substr(1)}`; } } - assert(hasAbsoluteRoot(root), `ensureAbsoluteRoot parameter 'root' must have an absolute root`); + assert_1.default(hasAbsoluteRoot(root), `ensureAbsoluteRoot parameter 'root' must have an absolute root`); // Otherwise ensure root ends with a separator if (root.endsWith('/') || (IS_WINDOWS && root.endsWith('\\'))) { // Intentionally empty @@ -1504,7 +1744,7 @@ exports.ensureAbsoluteRoot = ensureAbsoluteRoot; * `\\hello\share` and `C:\hello` (and using alternate separator). */ function hasAbsoluteRoot(itemPath) { - assert(itemPath, `hasAbsoluteRoot parameter 'itemPath' must not be empty`); + assert_1.default(itemPath, `hasAbsoluteRoot parameter 'itemPath' must not be empty`); // Normalize separators itemPath = normalizeSeparators(itemPath); // Windows @@ -1521,7 +1761,7 @@ exports.hasAbsoluteRoot = hasAbsoluteRoot; * `\`, `\hello`, `\\hello\share`, `C:`, and `C:\hello` (and using alternate separator). */ function hasRoot(itemPath) { - assert(itemPath, `isRooted parameter 'itemPath' must not be empty`); + assert_1.default(itemPath, `isRooted parameter 'itemPath' must not be empty`); // Normalize separators itemPath = normalizeSeparators(itemPath); // Windows @@ -1582,15 +1822,38 @@ exports.safeTrimTrailingSeparator = safeTrimTrailingSeparator; /***/ }), -/***/ 6836: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 6617: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; Object.defineProperty(exports, "__esModule", ({ value: true })); -const assert = __nccwpck_require__(9491); -const path = __nccwpck_require__(1017); -const pathHelper = __nccwpck_require__(1849); +exports.Path = void 0; +const path = __importStar(__nccwpck_require__(6928)); +const pathHelper = __importStar(__nccwpck_require__(4138)); +const assert_1 = __importDefault(__nccwpck_require__(2613)); const IS_WINDOWS = process.platform === 'win32'; /** * Helper class for parsing paths into segments @@ -1604,7 +1867,7 @@ class Path { this.segments = []; // String if (typeof itemPath === 'string') { - assert(itemPath, `Parameter 'itemPath' must not be empty`); + assert_1.default(itemPath, `Parameter 'itemPath' must not be empty`); // Normalize slashes and trim unnecessary trailing slash itemPath = pathHelper.safeTrimTrailingSeparator(itemPath); // Not rooted @@ -1631,24 +1894,24 @@ class Path { // Array else { // Must not be empty - assert(itemPath.length > 0, `Parameter 'itemPath' must not be an empty array`); + assert_1.default(itemPath.length > 0, `Parameter 'itemPath' must not be an empty array`); // Each segment for (let i = 0; i < itemPath.length; i++) { let segment = itemPath[i]; // Must not be empty - assert(segment, `Parameter 'itemPath' must not contain any empty segments`); + assert_1.default(segment, `Parameter 'itemPath' must not contain any empty segments`); // Normalize slashes segment = pathHelper.normalizeSeparators(itemPath[i]); // Root segment if (i === 0 && pathHelper.hasRoot(segment)) { segment = pathHelper.safeTrimTrailingSeparator(segment); - assert(segment === pathHelper.dirname(segment), `Parameter 'itemPath' root segment contains information for multiple segments`); + assert_1.default(segment === pathHelper.dirname(segment), `Parameter 'itemPath' root segment contains information for multiple segments`); this.segments.push(segment); } // All other segments else { // Must not contain slash - assert(!segment.includes(path.sep), `Parameter 'itemPath' contains unexpected path separators`); + assert_1.default(!segment.includes(path.sep), `Parameter 'itemPath' contains unexpected path separators`); this.segments.push(segment); } } @@ -1679,14 +1942,34 @@ exports.Path = Path; /***/ }), -/***/ 9005: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 8891: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; Object.defineProperty(exports, "__esModule", ({ value: true })); -const pathHelper = __nccwpck_require__(1849); -const internal_match_kind_1 = __nccwpck_require__(1063); +exports.partialMatch = exports.match = exports.getSearchPaths = void 0; +const pathHelper = __importStar(__nccwpck_require__(4138)); +const internal_match_kind_1 = __nccwpck_require__(2644); const IS_WINDOWS = process.platform === 'win32'; /** * Given an array of patterns, returns an array of paths to search. @@ -1760,22 +2043,45 @@ exports.partialMatch = partialMatch; /***/ }), -/***/ 4536: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 5370: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; Object.defineProperty(exports, "__esModule", ({ value: true })); -const assert = __nccwpck_require__(9491); -const os = __nccwpck_require__(2037); -const path = __nccwpck_require__(1017); -const pathHelper = __nccwpck_require__(1849); -const minimatch_1 = __nccwpck_require__(3973); -const internal_match_kind_1 = __nccwpck_require__(1063); -const internal_path_1 = __nccwpck_require__(6836); +exports.Pattern = void 0; +const os = __importStar(__nccwpck_require__(857)); +const path = __importStar(__nccwpck_require__(6928)); +const pathHelper = __importStar(__nccwpck_require__(4138)); +const assert_1 = __importDefault(__nccwpck_require__(2613)); +const minimatch_1 = __nccwpck_require__(3772); +const internal_match_kind_1 = __nccwpck_require__(2644); +const internal_path_1 = __nccwpck_require__(6617); const IS_WINDOWS = process.platform === 'win32'; class Pattern { - constructor(patternOrNegate, segments) { + constructor(patternOrNegate, isImplicitPattern = false, segments, homedir) { /** * Indicates whether matches should be excluded from the result set */ @@ -1789,9 +2095,9 @@ class Pattern { else { // Convert to pattern segments = segments || []; - assert(segments.length, `Parameter 'segments' must not empty`); + assert_1.default(segments.length, `Parameter 'segments' must not empty`); const root = Pattern.getLiteral(segments[0]); - assert(root && pathHelper.hasAbsoluteRoot(root), `Parameter 'segments' first element must be a root path`); + assert_1.default(root && pathHelper.hasAbsoluteRoot(root), `Parameter 'segments' first element must be a root path`); pattern = new internal_path_1.Path(segments).toString().trim(); if (patternOrNegate) { pattern = `!${pattern}`; @@ -1803,7 +2109,7 @@ class Pattern { pattern = pattern.substr(1).trim(); } // Normalize slashes and ensures absolute root - pattern = Pattern.fixupPattern(pattern); + pattern = Pattern.fixupPattern(pattern, homedir); // Segments this.segments = new internal_path_1.Path(pattern).segments; // Trailing slash indicates the pattern should only match directories, not regular files @@ -1819,6 +2125,7 @@ class Pattern { this.searchPath = new internal_path_1.Path(searchSegments).toString(); // Root RegExp (required when determining partial match) this.rootRegExp = new RegExp(Pattern.regExpEscape(searchSegments[0]), IS_WINDOWS ? 'i' : ''); + this.isImplicitPattern = isImplicitPattern; // Create minimatch const minimatchOptions = { dot: true, @@ -1840,11 +2147,11 @@ class Pattern { // Normalize slashes itemPath = pathHelper.normalizeSeparators(itemPath); // Append a trailing slash. Otherwise Minimatch will not match the directory immediately - // preceeding the globstar. For example, given the pattern `/foo/**`, Minimatch returns + // preceding the globstar. For example, given the pattern `/foo/**`, Minimatch returns // false for `/foo` but returns true for `/foo/`. Append a trailing slash to handle that quirk. - if (!itemPath.endsWith(path.sep)) { + if (!itemPath.endsWith(path.sep) && this.isImplicitPattern === false) { // Note, this is safe because the constructor ensures the pattern has an absolute root. - // For example, formats like C: and C:foo on Windows are resolved to an aboslute root. + // For example, formats like C: and C:foo on Windows are resolved to an absolute root. itemPath = `${itemPath}${path.sep}`; } } @@ -1882,15 +2189,15 @@ class Pattern { /** * Normalizes slashes and ensures absolute root */ - static fixupPattern(pattern) { + static fixupPattern(pattern, homedir) { // Empty - assert(pattern, 'pattern cannot be empty'); + assert_1.default(pattern, 'pattern cannot be empty'); // Must not contain `.` segment, unless first segment // Must not contain `..` segment const literalSegments = new internal_path_1.Path(pattern).segments.map(x => Pattern.getLiteral(x)); - assert(literalSegments.every((x, i) => (x !== '.' || i === 0) && x !== '..'), `Invalid pattern '${pattern}'. Relative pathing '.' and '..' is not allowed.`); + assert_1.default(literalSegments.every((x, i) => (x !== '.' || i === 0) && x !== '..'), `Invalid pattern '${pattern}'. Relative pathing '.' and '..' is not allowed.`); // Must not contain globs in root, e.g. Windows UNC path \\foo\b*r - assert(!pathHelper.hasRoot(pattern) || literalSegments[0], `Invalid pattern '${pattern}'. Root segment must not contain globs.`); + assert_1.default(!pathHelper.hasRoot(pattern) || literalSegments[0], `Invalid pattern '${pattern}'. Root segment must not contain globs.`); // Normalize slashes pattern = pathHelper.normalizeSeparators(pattern); // Replace leading `.` segment @@ -1899,9 +2206,9 @@ class Pattern { } // Replace leading `~` segment else if (pattern === '~' || pattern.startsWith(`~${path.sep}`)) { - const homedir = os.homedir(); - assert(homedir, 'Unable to determine HOME directory'); - assert(pathHelper.hasAbsoluteRoot(homedir), `Expected HOME directory to be a rooted path. Actual '${homedir}'`); + homedir = homedir || os.homedir(); + assert_1.default(homedir, 'Unable to determine HOME directory'); + assert_1.default(pathHelper.hasAbsoluteRoot(homedir), `Expected HOME directory to be a rooted path. Actual '${homedir}'`); pattern = Pattern.globEscape(homedir) + pattern.substr(1); } // Replace relative drive root, e.g. pattern is C: or C:foo @@ -1998,12 +2305,13 @@ exports.Pattern = Pattern; /***/ }), -/***/ 9117: +/***/ 9890: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SearchState = void 0; class SearchState { constructor(path, level) { this.path = path; @@ -2015,7 +2323,7 @@ exports.SearchState = SearchState; /***/ }), -/***/ 5526: +/***/ 4552: /***/ (function(__unused_webpack_module, exports) { "use strict"; @@ -2103,7 +2411,7 @@ exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHand /***/ }), -/***/ 6255: +/***/ 4844: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -2139,10 +2447,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.HttpClient = exports.isHttps = exports.HttpClientResponse = exports.HttpClientError = exports.getProxyUrl = exports.MediaTypes = exports.Headers = exports.HttpCodes = void 0; -const http = __importStar(__nccwpck_require__(3685)); -const https = __importStar(__nccwpck_require__(5687)); -const pm = __importStar(__nccwpck_require__(9835)); -const tunnel = __importStar(__nccwpck_require__(4294)); +const http = __importStar(__nccwpck_require__(8611)); +const https = __importStar(__nccwpck_require__(5692)); +const pm = __importStar(__nccwpck_require__(4988)); +const tunnel = __importStar(__nccwpck_require__(770)); var HttpCodes; (function (HttpCodes) { HttpCodes[HttpCodes["OK"] = 200] = "OK"; @@ -2232,6 +2540,19 @@ class HttpClientResponse { })); }); } + readBodyBuffer() { + return __awaiter(this, void 0, void 0, function* () { + return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () { + const chunks = []; + this.message.on('data', (chunk) => { + chunks.push(chunk); + }); + this.message.on('end', () => { + resolve(Buffer.concat(chunks)); + }); + })); + }); + } } exports.HttpClientResponse = HttpClientResponse; function isHttps(requestUrl) { @@ -2715,7 +3036,7 @@ const lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCa /***/ }), -/***/ 9835: +/***/ 4988: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -2736,7 +3057,13 @@ function getProxyUrl(reqUrl) { } })(); if (proxyVar) { - return new URL(proxyVar); + try { + return new URL(proxyVar); + } + catch (_a) { + if (!proxyVar.startsWith('http://') && !proxyVar.startsWith('https://')) + return new URL(`http://${proxyVar}`); + } } else { return undefined; @@ -2747,6 +3074,10 @@ function checkBypass(reqUrl) { if (!reqUrl.hostname) { return false; } + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { + return true; + } const noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || ''; if (!noProxy) { return false; @@ -2772,18 +3103,29 @@ function checkBypass(reqUrl) { .split(',') .map(x => x.trim().toUpperCase()) .filter(x => x)) { - if (upperReqHosts.some(x => x === upperNoProxyItem)) { + if (upperNoProxyItem === '*' || + upperReqHosts.some(x => x === upperNoProxyItem || + x.endsWith(`.${upperNoProxyItem}`) || + (upperNoProxyItem.startsWith('.') && + x.endsWith(`${upperNoProxyItem}`)))) { return true; } } return false; } exports.checkBypass = checkBypass; +function isLoopbackAddress(host) { + const hostLower = host.toLowerCase(); + return (hostLower === 'localhost' || + hostLower.startsWith('127.') || + hostLower.startsWith('[::1]') || + hostLower.startsWith('[0:0:0:0:0:0:0:1]')); +} //# sourceMappingURL=proxy.js.map /***/ }), -/***/ 9417: +/***/ 9380: /***/ ((module) => { "use strict"; @@ -2817,6 +3159,9 @@ function range(a, b, str) { var i = ai; if (ai >= 0 && bi > 0) { + if(a===b) { + return [ai, bi]; + } begs = []; left = str.length; @@ -2850,11 +3195,11 @@ function range(a, b, str) { /***/ }), -/***/ 3717: +/***/ 4691: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var concatMap = __nccwpck_require__(6891); -var balanced = __nccwpck_require__(9417); +var concatMap = __nccwpck_require__(7087); +var balanced = __nccwpck_require__(9380); module.exports = expandTop; @@ -2964,7 +3309,7 @@ function expand(str, isTop) { var isOptions = m.body.indexOf(',') >= 0; if (!isSequence && !isOptions) { // {a},b} - if (m.post.match(/,.*\}/)) { + if (m.post.match(/,(?!,).*\}/)) { str = m.pre + '{' + m.body + escClose + m.post; return expand(str); } @@ -3058,7 +3403,7 @@ function expand(str, isTop) { /***/ }), -/***/ 6891: +/***/ 7087: /***/ ((module) => { module.exports = function (xs, fn) { @@ -3078,19 +3423,19 @@ var isArray = Array.isArray || function (xs) { /***/ }), -/***/ 3973: +/***/ 3772: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { module.exports = minimatch minimatch.Minimatch = Minimatch -var path = (function () { try { return __nccwpck_require__(1017) } catch (e) {}}()) || { +var path = (function () { try { return __nccwpck_require__(6928) } catch (e) {}}()) || { sep: '/' } minimatch.sep = path.sep var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {} -var expand = __nccwpck_require__(3717) +var expand = __nccwpck_require__(4691) var plTypes = { '!': { open: '(?:(?!(?:', close: '))[^/]*?)'}, @@ -4032,27 +4377,27 @@ function regExpEscape (s) { /***/ }), -/***/ 4294: +/***/ 770: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -module.exports = __nccwpck_require__(4219); +module.exports = __nccwpck_require__(218); /***/ }), -/***/ 4219: +/***/ 218: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -var net = __nccwpck_require__(1808); -var tls = __nccwpck_require__(4404); -var http = __nccwpck_require__(3685); -var https = __nccwpck_require__(5687); -var events = __nccwpck_require__(2361); -var assert = __nccwpck_require__(9491); -var util = __nccwpck_require__(3837); +var net = __nccwpck_require__(9278); +var tls = __nccwpck_require__(4756); +var http = __nccwpck_require__(8611); +var https = __nccwpck_require__(5692); +var events = __nccwpck_require__(4434); +var assert = __nccwpck_require__(2613); +var util = __nccwpck_require__(9023); exports.httpOverHttp = httpOverHttp; @@ -4312,7 +4657,7 @@ exports.debug = debug; // for test /***/ }), -/***/ 5840: +/***/ 2048: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -4376,29 +4721,29 @@ Object.defineProperty(exports, "parse", ({ } })); -var _v = _interopRequireDefault(__nccwpck_require__(8628)); +var _v = _interopRequireDefault(__nccwpck_require__(6415)); -var _v2 = _interopRequireDefault(__nccwpck_require__(6409)); +var _v2 = _interopRequireDefault(__nccwpck_require__(1697)); -var _v3 = _interopRequireDefault(__nccwpck_require__(5122)); +var _v3 = _interopRequireDefault(__nccwpck_require__(4676)); -var _v4 = _interopRequireDefault(__nccwpck_require__(9120)); +var _v4 = _interopRequireDefault(__nccwpck_require__(9771)); -var _nil = _interopRequireDefault(__nccwpck_require__(5332)); +var _nil = _interopRequireDefault(__nccwpck_require__(7723)); -var _version = _interopRequireDefault(__nccwpck_require__(1595)); +var _version = _interopRequireDefault(__nccwpck_require__(5868)); -var _validate = _interopRequireDefault(__nccwpck_require__(6900)); +var _validate = _interopRequireDefault(__nccwpck_require__(6200)); -var _stringify = _interopRequireDefault(__nccwpck_require__(8950)); +var _stringify = _interopRequireDefault(__nccwpck_require__(7597)); -var _parse = _interopRequireDefault(__nccwpck_require__(2746)); +var _parse = _interopRequireDefault(__nccwpck_require__(7267)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /***/ }), -/***/ 4569: +/***/ 216: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -4409,7 +4754,7 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = void 0; -var _crypto = _interopRequireDefault(__nccwpck_require__(6113)); +var _crypto = _interopRequireDefault(__nccwpck_require__(6982)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -4428,7 +4773,7 @@ exports["default"] = _default; /***/ }), -/***/ 5332: +/***/ 7723: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -4443,7 +4788,7 @@ exports["default"] = _default; /***/ }), -/***/ 2746: +/***/ 7267: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -4454,7 +4799,7 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = void 0; -var _validate = _interopRequireDefault(__nccwpck_require__(6900)); +var _validate = _interopRequireDefault(__nccwpck_require__(6200)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -4495,7 +4840,7 @@ exports["default"] = _default; /***/ }), -/***/ 814: +/***/ 7879: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -4510,7 +4855,7 @@ exports["default"] = _default; /***/ }), -/***/ 807: +/***/ 2973: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -4521,7 +4866,7 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = rng; -var _crypto = _interopRequireDefault(__nccwpck_require__(6113)); +var _crypto = _interopRequireDefault(__nccwpck_require__(6982)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -4541,7 +4886,7 @@ function rng() { /***/ }), -/***/ 5274: +/***/ 507: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -4552,7 +4897,7 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = void 0; -var _crypto = _interopRequireDefault(__nccwpck_require__(6113)); +var _crypto = _interopRequireDefault(__nccwpck_require__(6982)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -4571,7 +4916,7 @@ exports["default"] = _default; /***/ }), -/***/ 8950: +/***/ 7597: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -4582,7 +4927,7 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = void 0; -var _validate = _interopRequireDefault(__nccwpck_require__(6900)); +var _validate = _interopRequireDefault(__nccwpck_require__(6200)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -4617,7 +4962,7 @@ exports["default"] = _default; /***/ }), -/***/ 8628: +/***/ 6415: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -4628,9 +4973,9 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = void 0; -var _rng = _interopRequireDefault(__nccwpck_require__(807)); +var _rng = _interopRequireDefault(__nccwpck_require__(2973)); -var _stringify = _interopRequireDefault(__nccwpck_require__(8950)); +var _stringify = _interopRequireDefault(__nccwpck_require__(7597)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -4731,7 +5076,7 @@ exports["default"] = _default; /***/ }), -/***/ 6409: +/***/ 1697: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -4742,9 +5087,9 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = void 0; -var _v = _interopRequireDefault(__nccwpck_require__(5998)); +var _v = _interopRequireDefault(__nccwpck_require__(2930)); -var _md = _interopRequireDefault(__nccwpck_require__(4569)); +var _md = _interopRequireDefault(__nccwpck_require__(216)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -4754,7 +5099,7 @@ exports["default"] = _default; /***/ }), -/***/ 5998: +/***/ 2930: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -4766,9 +5111,9 @@ Object.defineProperty(exports, "__esModule", ({ exports["default"] = _default; exports.URL = exports.DNS = void 0; -var _stringify = _interopRequireDefault(__nccwpck_require__(8950)); +var _stringify = _interopRequireDefault(__nccwpck_require__(7597)); -var _parse = _interopRequireDefault(__nccwpck_require__(2746)); +var _parse = _interopRequireDefault(__nccwpck_require__(7267)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -4839,7 +5184,7 @@ function _default(name, version, hashfunc) { /***/ }), -/***/ 5122: +/***/ 4676: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -4850,9 +5195,9 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = void 0; -var _rng = _interopRequireDefault(__nccwpck_require__(807)); +var _rng = _interopRequireDefault(__nccwpck_require__(2973)); -var _stringify = _interopRequireDefault(__nccwpck_require__(8950)); +var _stringify = _interopRequireDefault(__nccwpck_require__(7597)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -4883,7 +5228,7 @@ exports["default"] = _default; /***/ }), -/***/ 9120: +/***/ 9771: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -4894,9 +5239,9 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = void 0; -var _v = _interopRequireDefault(__nccwpck_require__(5998)); +var _v = _interopRequireDefault(__nccwpck_require__(2930)); -var _sha = _interopRequireDefault(__nccwpck_require__(5274)); +var _sha = _interopRequireDefault(__nccwpck_require__(507)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -4906,7 +5251,7 @@ exports["default"] = _default; /***/ }), -/***/ 6900: +/***/ 6200: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -4917,7 +5262,7 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = void 0; -var _regex = _interopRequireDefault(__nccwpck_require__(814)); +var _regex = _interopRequireDefault(__nccwpck_require__(7879)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -4930,7 +5275,7 @@ exports["default"] = _default; /***/ }), -/***/ 1595: +/***/ 5868: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -4941,7 +5286,7 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = void 0; -var _validate = _interopRequireDefault(__nccwpck_require__(6900)); +var _validate = _interopRequireDefault(__nccwpck_require__(6200)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -4958,7 +5303,7 @@ exports["default"] = _default; /***/ }), -/***/ 9491: +/***/ 2613: /***/ ((module) => { "use strict"; @@ -4966,7 +5311,7 @@ module.exports = require("assert"); /***/ }), -/***/ 6113: +/***/ 6982: /***/ ((module) => { "use strict"; @@ -4974,7 +5319,7 @@ module.exports = require("crypto"); /***/ }), -/***/ 2361: +/***/ 4434: /***/ ((module) => { "use strict"; @@ -4982,7 +5327,7 @@ module.exports = require("events"); /***/ }), -/***/ 7147: +/***/ 9896: /***/ ((module) => { "use strict"; @@ -4990,7 +5335,7 @@ module.exports = require("fs"); /***/ }), -/***/ 3685: +/***/ 8611: /***/ ((module) => { "use strict"; @@ -4998,7 +5343,7 @@ module.exports = require("http"); /***/ }), -/***/ 5687: +/***/ 5692: /***/ ((module) => { "use strict"; @@ -5006,7 +5351,7 @@ module.exports = require("https"); /***/ }), -/***/ 1808: +/***/ 9278: /***/ ((module) => { "use strict"; @@ -5014,7 +5359,7 @@ module.exports = require("net"); /***/ }), -/***/ 2037: +/***/ 857: /***/ ((module) => { "use strict"; @@ -5022,7 +5367,7 @@ module.exports = require("os"); /***/ }), -/***/ 1017: +/***/ 6928: /***/ ((module) => { "use strict"; @@ -5030,7 +5375,7 @@ module.exports = require("path"); /***/ }), -/***/ 2781: +/***/ 2203: /***/ ((module) => { "use strict"; @@ -5038,7 +5383,7 @@ module.exports = require("stream"); /***/ }), -/***/ 4404: +/***/ 4756: /***/ ((module) => { "use strict"; @@ -5046,7 +5391,7 @@ module.exports = require("tls"); /***/ }), -/***/ 3837: +/***/ 9023: /***/ ((module) => { "use strict"; @@ -5096,8 +5441,8 @@ module.exports = require("util"); /******/ // startup /******/ // Load entry module and return exports /******/ // This entry module is referenced by other modules so it can't be inlined -/******/ var __webpack_exports__ = __nccwpck_require__(2627); +/******/ var __webpack_exports__ = __nccwpck_require__(4711); /******/ module.exports = __webpack_exports__; /******/ /******/ })() -; +; \ No newline at end of file diff --git a/act/runner/job_executor.go b/act/runner/job_executor.go index cfa7d01b..091f4899 100644 --- a/act/runner/job_executor.go +++ b/act/runner/job_executor.go @@ -31,55 +31,36 @@ import ( "gitea.dev/actionslib/pkg/exprparser" "gitea.dev/actionslib/pkg/model" + "gitea.dev/actionslib/pkg/protocol" unicodeencoding "golang.org/x/text/encoding/unicode" "golang.org/x/text/transform" ) const ( - jobCleanupTimeout = time.Minute - maxJobSummaryBytes = 1024 * 1024 + jobCleanupTimeout = time.Minute + jobSummaryUploadPhaseTimeout = 15 * time.Second ) // jobSummaryTruncationMarker is appended to a summary that exceeded the size limit // so the rendered output makes the truncation visible instead of silently cutting off. const jobSummaryTruncationMarker = "\n\n---\n\n*Job summary truncated: it exceeded the maximum allowed size.*\n" -var ( - jobSummaryUploadRetryDelay = time.Second - // jobSummaryUploadRequestTimeout bounds a single step upload request. It is kept - // below jobSummaryUploadPhaseTimeout so one slow or unreachable request times out - // and lets the remaining steps still upload within the phase budget, instead of a - // single stuck request consuming the whole phase. - jobSummaryUploadRequestTimeout = 5 * time.Second - // jobSummaryUploadPhaseTimeout bounds the total time spent uploading all step - // summaries. The uploads run inside the job cleanup budget that is also used to - // stop and remove the container, so a slow or unreachable endpoint must not be - // allowed to consume it; this keeps the remaining budget available for teardown. - jobSummaryUploadPhaseTimeout = 15 * time.Second -) - type jobInfo interface { - matrix() map[string]any steps() []*model.Step startContainer() common.Executor stopContainer() common.Executor closeContainer() common.Executor interpolateOutputs() common.Executor - result(result string) } -// reportStepError records a step error so the job is reported failed — except a -// cancellation, which is an interruption, not a failure. func reportStepError(ctx context.Context, rc *RunContext, err error) { - if errors.Is(err, context.Canceled) { - // Defer to the job context: a genuine cancel reports cancelled, a stray teardown - // cancellation on a live ctx is ignored — never a step FAILURE. - rc.markInterrupted(ctx.Err()) - return + if ctx.Err() != nil { + rc.markJobInterrupted(ctx) + } else if err != nil && !errors.Is(err, context.Canceled) { // A live job can receive cancellation from step teardown. + common.Logger(ctx).Errorf("##[error]%s", EscapeCommandData(err.Error())) + common.SetJobError(ctx, err) + rc.markFailed() } - common.Logger(ctx).Errorf("##[error]%s", EscapeCommandData(err.Error())) - common.SetJobError(ctx, err) - rc.markFailed() } // actionPreparer is implemented by steps that download an action before they run, so the job @@ -158,22 +139,14 @@ func (e setupError) Unwrap() error { return e.error } // printCompleteJobName closes the setup section the way actions/runner ends its "Set up job" step. func printCompleteJobName(rc *RunContext) common.Executor { return func(ctx context.Context) error { - // Name holds a matrix combination; JobName is the shared name GitHub reports. - name := cmp.Or(rc.JobName, rc.Name) - if name == "" && rc.Run != nil { - name = rc.Run.JobID - } - common.Logger(ctx).With(rawOutputField, true).Infof("Complete job name: %s", name) + common.Logger(ctx).With(rawOutputField, true).Infof("Complete job name: %s", cmp.Or(rc.JobName, rc.Name, rc.Run.JobID)) // Name holds a matrix combination; JobName is the shared name GitHub reports. return nil } } func newJobExecutor(info jobInfo, sf stepFactory, rc *RunContext) common.Executor { - steps := make([]common.Executor, 0) - preSteps := make([]common.Executor, 0) - // Collected separately: every action is downloaded before the first pre step runs. - stepPreSteps := make([]common.Executor, 0) - preparers := make([]actionPreparer, 0) + var steps, preSteps, stepPreSteps []common.Executor // Collected separately: every action is downloaded before the first pre step runs. + var preparers []actionPreparer var postExecutor common.Executor infoSteps := info.steps() @@ -183,16 +156,12 @@ func newJobExecutor(info jobInfo, sf stepFactory, rc *RunContext) common.Executo } preSteps = append(preSteps, func(ctx context.Context) error { - if len(info.matrix()) > 0 { - common.Logger(ctx).Infof("Matrix: %v", info.matrix()) + if len(rc.Matrix) > 0 { + common.Logger(ctx).Infof("Matrix: %v", rc.Matrix) } return nil }) preSteps = append(preSteps, func(ctx context.Context) error { - // Have to be skipped for some Tests - if rc.Run == nil { - return nil - } if err := evaluateJobEnvAndDefaults(ctx, rc); err != nil { reportStepError(ctx, rc, err) return err @@ -202,9 +171,7 @@ func newJobExecutor(info jobInfo, sf stepFactory, rc *RunContext) common.Executo for i, stepModel := range infoSteps { if stepModel == nil { - return func(ctx context.Context) error { - return fmt.Errorf("invalid Step %v: missing run or uses key", i) - } + return common.NewErrorExecutor(fmt.Errorf("invalid Step %v: missing run or uses key", i)) } if stepModel.ID == "" { stepModel.ID = strconv.Itoa(i) @@ -220,42 +187,17 @@ func newJobExecutor(info jobInfo, sf stepFactory, rc *RunContext) common.Executo preparers = append(preparers, preparer) } - stepIdx := stepModel.Number - preExec := step.pre() - stepPreSteps = append(stepPreSteps, useStepLogger(rc, stepModel, stepStagePre, func(ctx context.Context) error { - rc.CurrentStepIndex = stepIdx - preErr := preExec(ctx) - if preErr != nil { - reportStepError(ctx, rc, preErr) - } else if ctx.Err() != nil { - reportStepError(ctx, rc, ctx.Err()) - } - return preErr - })) - - stepExec := step.main() - steps = append(steps, useStepLogger(rc, stepModel, stepStageMain, func(ctx context.Context) error { - rc.CurrentStepIndex = stepIdx - err := stepExec(ctx) - if err != nil { + runPhase := func(stage stepStage, executor common.Executor) common.Executor { + return useStepLogger(rc, stepModel, stage, func(ctx context.Context) error { + rc.CurrentStepIndex = i + err := executor(ctx) reportStepError(ctx, rc, err) - } else if ctx.Err() != nil { - reportStepError(ctx, rc, ctx.Err()) - } - return nil - })) - - postFn := step.post() - postExec := useStepLogger(rc, stepModel, stepStagePost, func(ctx context.Context) error { - rc.CurrentStepIndex = stepIdx - err := postFn(ctx) - if err != nil { - reportStepError(ctx, rc, err) - } else if ctx.Err() != nil { - reportStepError(ctx, rc, ctx.Err()) - } - return err - }) + return err + }) + } + stepPreSteps = append(stepPreSteps, runPhase(stepStagePre, step.pre())) + steps = append(steps, runPhase(stepStageMain, step.main())) + postExec := runPhase(stepStagePost, step.post()) if postExecutor != nil { // run the post executor in reverse order postExecutor = postExec.Finally(postExecutor) @@ -267,37 +209,23 @@ func newJobExecutor(info jobInfo, sf stepFactory, rc *RunContext) common.Executo // The setup section of the job log. The started hook goes first, so what it sets up is // in place for the first action download and the first step. // The pre steps come after it, as steps of their own. - preSteps = append(preSteps, rc.runJobStartedHook) - preSteps = append(preSteps, printPrepareActions(rc, preparers)) - preSteps = append(preSteps, printCompleteJobName(rc)) - preSteps = append(preSteps, stepPreSteps...) + preSteps = append(preSteps, rc.runJobStartedHook, printPrepareActions(rc, preparers), printCompleteJobName(rc)) + runSteps := newStepsExecutor(rc, append(preSteps, stepPreSteps...), steps) // Ahead of the teardown below, while the job environment is still up. postExecutor = postExecutor.Finally(useJobStageLogger(StageComplete, rc.runJobCompletedHook)) postExecutor = postExecutor.Finally(useJobStageLogger(StageComplete, func(ctx context.Context) error { - // swallowed: a bad output fails this job, it must not abandon the rest of the plan - if err := info.interpolateOutputs()(ctx); err != nil { - reportStepError(ctx, rc, err) - } else if err := setJobOutputs(ctx, rc); err != nil { - reportStepError(ctx, rc, err) - } - return nil - })) - - postExecutor = postExecutor.Finally(useJobStageLogger(StageComplete, func(ctx context.Context) error { - jobError := common.JobError(ctx) - var err error - // always allow 1 min for stopping and removing the runner, even if we were cancelled - ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), jobCleanupTimeout) + reportStepError(ctx, rc, info.interpolateOutputs()(ctx)) // A bad output fails the job without abandoning the plan. + ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), jobCleanupTimeout) // Teardown needs time even after cancellation. defer cancel() + rc.summaryUploads.wait(ctx) logger := common.Logger(ctx) - tryUploadJobSummary(ctx, rc) logger.Infof("Cleaning up container for job %s", rc.JobName) - if err = info.stopContainer()(ctx); err != nil { + err := info.stopContainer()(ctx) + if err != nil { logger.Errorf("##[error]%s", EscapeCommandData("Error while stop job container: "+err.Error())) } - setJobResult(ctx, info, rc, jobError == nil) rc.removeDockerActionImages(ctx) return err @@ -305,33 +233,27 @@ func newJobExecutor(info jobInfo, sf stepFactory, rc *RunContext) common.Executo return common.Executor(func(ctx context.Context) error { if err := info.startContainer()(ctx); err != nil { + rc.markFailed() return err } - return newStepsExecutor(rc, preSteps, steps).Finally(func(ctx context.Context) error { - // Record an interrupt (backstop for interrupts that land outside the main - // step loop) so the post steps observe the cancelled/failed job status. - rc.markInterrupted(ctx.Err()) + rc.summaryUploads = newStepSummaryUploads(ctx) + return runSteps.Finally(func(ctx context.Context) error { + rc.markJobInterrupted(ctx) // Post steps must see interrupts that landed after the last main step. postCtx, cancel := postStepsContext(ctx) defer cancel() return postExecutor(postCtx) })(ctx) - }).Finally(info.closeContainer()) + }).Finally(info.closeContainer()).Finally(useJobStageLogger(StageComplete, func(ctx context.Context) error { + rc.markJobInterrupted(ctx) + rc.setJobResult(ctx, common.JobError(ctx) == nil) + return nil + })) } -// postStepsContext derives the context used to run the job's post/cleanup steps from the -// finished main-pipeline context. Cleanup has to run even when the run was interrupted, so the -// returned context always carries a fresh bounded deadline and is never itself cancelled. -// -// - context.Canceled (server cancel): detach with WithoutCancel under a fresh job-error -// container, so a failing post step cannot turn the cancellation into a failure. -// - context.DeadlineExceeded (job timeout): detach the deadline with WithoutCancel, which -// keeps the original values — including the job-error container — so the timeout failure and -// any post-step error are preserved and the job is still reported as failed. -// - otherwise: run on the live context unchanged. func postStepsContext(ctx context.Context) (context.Context, context.CancelFunc) { switch ctx.Err() { case context.Canceled: - return context.WithTimeout(common.WithJobErrorContainer(context.WithoutCancel(ctx)), 5*time.Minute) + return context.WithTimeout(common.WithJobErrorContainer(context.WithoutCancel(ctx)), 5*time.Minute) // a failed post step cannot replace a server cancellation case context.DeadlineExceeded: return context.WithTimeout(context.WithoutCancel(ctx), 5*time.Minute) default: @@ -339,105 +261,54 @@ func postStepsContext(ctx context.Context) (context.Context, context.CancelFunc) } } -// newStepsExecutor sequences the job's pre steps and main steps. -// -// The pre steps run as a normal pipeline that short-circuits on the first failure or -// cancellation. The main-steps executor then runs unconditionally — even if a pre step failed -// or the job was interrupted — so always()/cancelled()/failure() main steps still run, mirroring -// GitHub Actions. This is safe because each main step re-evaluates its own `if` (a pre-step -// failure flips the expression job status to failure, so success()-default steps skip) and -// newMainStepsExecutor detaches from an interrupted context before running the remaining steps. -// -// A pre-step failure or interrupt is still propagated so the job is reported with the correct -// conclusion; the pre error takes precedence since it happened first. func newStepsExecutor(rc *RunContext, preSteps, steps []common.Executor) common.Executor { preExecutor := common.NewPipelineExecutor(preSteps...) - mainExecutor := newMainStepsExecutor(rc, steps) return func(ctx context.Context) error { preErr := preExecutor(ctx) - if errors.As(preErr, new(setupError)) { + if _, setupFailed := errors.AsType[setupError](preErr); setupFailed { return preErr // as on GitHub, no step runs after the job setup failed } - mainErr := mainExecutor(ctx) - return cmp.Or(preErr, mainErr) - } -} - -// newMainStepsExecutor runs the job's main-stage step executors in order. Unlike a plain -// pipeline, an interruption (context.Canceled from a server cancel, or context.DeadlineExceeded -// from the job timeout) does not abandon the remaining steps: it marks the job cancelled when -// appropriate and keeps iterating under a fresh, bounded context so steps whose `if` still -// evaluates true — always() and cancelled() — run for cleanup, mirroring GitHub Actions. Steps -// that default to success() skip themselves because success() is false once the job is no longer -// successful. The main-step wrappers report their own errors and return nil, so the loop drives -// step ordering off the context, not return values. -func newMainStepsExecutor(rc *RunContext, steps []common.Executor) common.Executor { - return func(ctx context.Context) error { for i, step := range steps { - if ctx.Err() != nil { - return runMainStepsAfterInterrupt(ctx, rc, steps[i:]) + if err := ctx.Err(); err != nil { + rc.markJobInterrupted(ctx) + freshCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Minute) + defer cancel() + for _, remaining := range steps[i:] { + _ = remaining(freshCtx) + } + return cmp.Or(preErr, err) } _ = step(ctx) } - // An interrupt can land during the final step, after the loop's last context - // check; record it so the post steps still observe the cancelled/failed status. - rc.markInterrupted(ctx.Err()) - return nil + rc.markJobInterrupted(ctx) + return preErr } } -// runMainStepsAfterInterrupt runs the remaining main steps after the job context was cancelled or -// timed out. It detaches from the interrupted context (keeping its values: logger and job error) -// and applies a fresh deadline so always()/cancelled() steps run to completion. The original -// interrupt error is returned so callers up the chain still see the job as cancelled/timed out. -func runMainStepsAfterInterrupt(ctx context.Context, rc *RunContext, steps []common.Executor) error { - interruptErr := ctx.Err() - rc.markInterrupted(interruptErr) - freshCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Minute) - defer cancel() - for _, step := range steps { - _ = step(freshCtx) - } - return interruptErr -} - -func setJobResult(ctx context.Context, info jobInfo, rc *RunContext, success bool) { - logger := common.Logger(ctx) +func (rc *RunContext) setJobResult(ctx context.Context, success bool) { success = success && !rc.jobFailed - // Matrix combinations share one *model.Job and run in parallel; serialize the - // read-modify-write of the job result so a failing combination is not lost-updated by a - // concurrent succeeding one. job := rc.Run.Job() var continueOnError bool if !success && !rc.jobCancelled { - // Use a fresh context so an expired job timeout cannot block expression evaluation. - evalCtx := common.WithLogger(context.Background(), common.Logger(ctx)) - continueOnError = evaluateJobContinueOnError(evalCtx, rc, job) + continueOnError = evaluateJobContinueOnError(context.WithoutCancel(ctx), rc, job) } - jobResult := func() string { - defer lockJob(job)() - result := "success" - // we have only one result for a whole matrix build, so we need - // to keep an existing result state if we run a matrix - if len(info.matrix()) > 0 && job.Result != "" { - result = job.Result - } - // cancelled is sticky, so a sibling combination finishing last cannot mask it - switch { - case rc.jobCancelled: - result = "cancelled" - case !success && result != "cancelled": - result = "failure" - job.SetContinueOnError(continueOnError) - } - info.result(result) - return result - }() + defer lockJob(job)() // matrix combinations share this result and its caller notification + jobResult := "success" + if rc.jobTotal != 1 && job.Result != "" && job.Result != "skipped" { + jobResult = job.Result + } + switch { + case rc.jobCancelled: + jobResult = "cancelled" + case !success && jobResult != "cancelled": + jobResult = "failure" + job.SetContinueOnError(continueOnError) + } + job.Result = jobResult if rc.caller != nil { - // set reusable workflow job result - rc.caller.setReusedWorkflowJobResult(rc.Run.JobID, jobResult) // For Gitea + rc.caller.reportedRuns[rc.callerRunIndex] = rc.Run return } @@ -449,7 +320,7 @@ func setJobResult(ctx context.Context, info jobInfo, rc *RunContext, success boo jobResultMessage = "cancelled" } - logger.With("jobResult", jobResult).Infof("Job %s", jobResultMessage) + common.Logger(ctx).With("jobResult", jobResult).Infof("Job %s", jobResultMessage) } // evaluateJobEnv returns the workflow and job env evaluated, as far as it got on error, leaving rc.Env raw. @@ -492,35 +363,49 @@ func evaluateJobEnvAndDefaults(ctx context.Context, rc *RunContext) error { return model.DecodeEvaluated("container env", rc.containerEnv, rc.ExprEval.shared(ctx).EvaluateYamlNode, &rc.containerSpec.Env) } -func setJobOutputs(ctx context.Context, rc *RunContext) error { - if rc.caller == nil { - return nil - } - callerOutputs, err := rc.NewExpressionEvaluator(ctx).shared(ctx).EvaluateWorkflowCallOutputs(rc.Run.Workflow.WorkflowCallConfig()) - if err != nil { - return fmt.Errorf("unable to interpolate workflow %w", err) - } +type jobTimeout time.Duration - // 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 +func (timeout jobTimeout) Error() string { + return fmt.Sprintf("The job has exceeded the maximum execution time of %s", time.Duration(timeout)) } -// applyJobTimeout applies the job-level timeout-minutes to ctx, mirroring the -// step-level evaluateStepTimeout in step.go. -func applyJobTimeout(ctx context.Context, rc *RunContext, job *model.Job) (context.Context, context.CancelFunc) { - timeout, err := rc.ExprEval.Interpolate(ctx, job.TimeoutMinutes) - 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 && timeoutMinutes > 0 { - return context.WithTimeout(ctx, time.Duration(timeoutMinutes)*time.Minute) +func (jobTimeout) Unwrap() error { return context.DeadlineExceeded } + +type jobTimeoutCancellation struct{} + +func (jobTimeoutCancellation) Error() string { return "The operation was canceled." } +func (jobTimeoutCancellation) Unwrap() error { return context.Canceled } + +func (rc *RunContext) markJobInterrupted(ctx context.Context) { + switch ctx.Err() { + case context.Canceled: + rc.markCancelled() + case context.DeadlineExceeded: + if timeout, ok := context.Cause(ctx).(jobTimeout); ok { + if !rc.jobCancelled { + common.Logger(ctx).Errorf("##[error]%s", timeout) + } + rc.markCancelled() + } else { + rc.jobTimedOut = true + rc.markFailed() } } - return ctx, func() {} +} + +func applyJobTimeout(ctx context.Context, rc *RunContext, job *model.Job) (context.Context, context.CancelFunc, error) { + if raw := job.TimeoutMinutes; raw != "" { + minutes, err := rc.ExprEval.shared(ctx).EvaluateTimeoutMinutes(raw) + if err != nil { + return nil, nil, fmt.Errorf("Error when evaluating 'timeout-minutes' for job '%s'. %w", rc.Run.JobID, err) + } + if minutes > 0 { + timeout := time.Duration(minutes) * time.Minute + ctx, cancel := context.WithTimeoutCause(ctx, timeout, jobTimeout(timeout)) + return ctx, cancel, nil + } + } + return ctx, func() {}, nil } // evaluateJobContinueOnError evaluates the job-level continue-on-error expression. @@ -537,70 +422,127 @@ func evaluateJobContinueOnError(ctx context.Context, rc *RunContext, job *model. return continueOnError } -func tryUploadJobSummary(ctx context.Context, rc *RunContext) { - if rc == nil || rc.JobContainer == nil || rc.Config == nil { +type stepSummaryUpload struct { + done chan struct{} + status int + err error +} + +type stepSummaryUploads struct { + ctx context.Context + cancel context.CancelFunc + steps []*stepSummaryUpload +} + +func newStepSummaryUploads(ctx context.Context) *stepSummaryUploads { + uploadCtx, cancel := context.WithCancel(context.WithoutCancel(ctx)) + return &stepSummaryUploads{ctx: uploadCtx, cancel: cancel} +} + +func (uploads *stepSummaryUploads) wait(ctx context.Context) { + defer uploads.cancel() + if len(uploads.steps) == 0 { return } - // Bound the whole upload phase so a slow or unreachable endpoint cannot consume - // the job cleanup budget reserved for stopping and removing the container. - ctx, cancel := context.WithTimeout(ctx, jobSummaryUploadPhaseTimeout) + ctx, cancel := context.WithTimeout(ctx, jobSummaryUploadPhaseTimeout) // A slow endpoint must leave time for teardown. defer cancel() - env := rc.GetEnv() + logger := common.Logger(ctx) + for _, upload := range uploads.steps { + select { + case <-upload.done: + if upload.err != nil { + logger.WithError(upload.err).Warn("job summary upload failed") + } else if upload.status/100 != 2 { + logger.Warnf("job summary upload failed: status=%d", upload.status) + } + case <-ctx.Done(): + logger.WithError(ctx.Err()).Warn("job summary upload timed out") + return + } + } +} + +func processStepSummary(ctx context.Context, rc *RunContext, summaryPath string) { + job := rc.topLevelRunContext() + uploads := job.summaryUploads + if uploads == nil { + return + } + env := job.GetEnv() if !hasJobSummaryCapability(env["GITEA_ACTIONS_CAPABILITIES"]) { - // Server did not advertise support. Do not attempt upload. + return + } + if rc != job { + job.Masks = appendUniqueMasks(slices.Clip(job.Masks), rc.Masks) // composite masks must survive later writes to the child's slice return } runtimeURL := strings.TrimSpace(env["ACTIONS_RUNTIME_URL"]) runtimeToken := strings.TrimSpace(env["ACTIONS_RUNTIME_TOKEN"]) runID := strings.TrimSpace(env["GITEA_RUN_ID"]) - if runtimeURL == "" || runtimeToken == "" || runID == "" { - return - } - if rc.Run == nil || rc.Run.Job() == nil { - return - } - // The numeric ActionRunJob ID is not exposed in the proto Task message or task context, - // but the server signs it into the ACTIONS_RUNTIME_TOKEN JWT claims. We decode the - // unverified claims to retrieve it; the server re-verifies the token on the request. jobID := extractJobIDFromRuntimeToken(runtimeToken) - if jobID <= 0 { + if runtimeURL == "" || runID == "" || jobID <= 0 { return } - base := strings.TrimRight(runtimeURL, "/") + "/_apis/pipelines/workflows/" + runID + - "/jobs/" + strconv.FormatInt(jobID, 10) + "/steps/" - actPath := rc.JobContainer.GetActPath() - // Reuse a single client across all step uploads so connections can be pooled. - client := &http.Client{Timeout: jobSummaryUploadRequestTimeout, Transport: rc.Config.instanceTransportFor(base)} - maskers := rc.secretMaskers() - longestMask := 0 - for i := 0; i < len(maskers); i += 2 { - longestMask = max(longestMask, len(maskers[i])) + body := readStepSummary(ctx, rc, summaryPath) + if len(body) == 0 { + return + } + url := fmt.Sprintf("%s/_apis/pipelines/workflows/%s/jobs/%d/steps/%d/summary", strings.TrimRight(runtimeURL, "/"), runID, jobID, rc.CurrentStepIndex) + transport := rc.Config.instanceTransportFor(url) + var previousDone <-chan struct{} + if last := len(uploads.steps) - 1; last >= 0 { + previousDone = uploads.steps[last].done + } + upload := &stepSummaryUpload{done: make(chan struct{})} + uploads.steps = append(uploads.steps, upload) + uploadCtx := uploads.ctx + go func() { + defer close(upload.done) + defer common.RecoverPanic(&upload.err) + if previousDone != nil { + select { + case <-previousDone: + case <-uploadCtx.Done(): + return + } + } + if uploadCtx.Err() == nil { + upload.status, upload.err = uploadJobSummary(uploadCtx, &http.Client{Timeout: 5 * time.Second, Transport: transport}, url, runtimeToken, body) + } + }() +} + +func readStepSummary(ctx context.Context, rc *RunContext, summaryPath string) []byte { + ctx, cancel := context.WithTimeout(ctx, jobSummaryUploadPhaseTimeout) + defer cancel() + var maskers []string + limit := protocol.MaxStepSummarySize + body, _ := readContainerFile(ctx, rc.JobContainer, summaryPath, func() int64 { + maskers = rc.secretMaskers() + for i := 0; i < len(maskers); i += 2 { + limit = max(limit, protocol.MaxStepSummarySize+len(maskers[i])) + } + return int64(limit + 1) + }) + if len(body) == 0 { + return nil } masker := NewSecretReplacer(maskers) - limit := maxJobSummaryBytes + longestMask - for i := range rc.Run.Job().Steps { - summaryPath := container.JoinPath(actPath, "workflow", "step-summary-"+strconv.Itoa(i)+".md") - body, ok := readSingleFileFromContainerArchive(ctx, rc.JobContainer, summaryPath, int64(limit+1)) - if !ok || len(body) == 0 { - continue + masked := masker.Replace(string(body)) + split := len(body) > limit + if split { // the read can end inside a secret, so keep only what masks alike without the lookahead + unsplit := masker.Replace(string(body[:protocol.MaxStepSummarySize])) + kept := 0 + for kept < len(unsplit) && kept < len(masked) && unsplit[kept] == masked[kept] { + kept++ } - masked := masker.Replace(string(body)) - split := len(body) > limit - if split { // the read can end inside a secret, so keep only what masks alike without the lookahead - unsplit := masker.Replace(string(body[:maxJobSummaryBytes])) - kept := 0 - for kept < len(unsplit) && kept < len(masked) && unsplit[kept] == masked[kept] { - kept++ - } - for kept > 0 && kept < len(masked) && !utf8.RuneStart(masked[kept]) { - kept-- - } - masked = masked[:kept] + for kept > 0 && kept < len(masked) && !utf8.RuneStart(masked[kept]) { + kept-- } - body = truncateJobSummary(ctx, []byte(masked), summaryPath, maxJobSummaryBytes, split) - uploadJobSummary(ctx, client, base+strconv.Itoa(i)+"/summary", runtimeToken, body) + masked = masked[:kept] } + return truncateJobSummary(ctx, []byte(masked), summaryPath, protocol.MaxStepSummarySize, split) } // For Gitea @@ -638,37 +580,17 @@ func hasJobSummaryCapability(caps string) bool { }), "job-summary") } -func uploadJobSummary(ctx context.Context, client *http.Client, url, runtimeToken string, body []byte) { - logger := common.Logger(ctx) - - var lastStatus int - var lastErr error - for attempt := 0; attempt < 2; attempt++ { - status, err := putJobSummary(ctx, client, url, runtimeToken, body) - if err == nil && status/100 == 2 { - return - } - lastStatus = status - lastErr = err - if attempt == 1 || !isTransientJobSummaryUploadFailure(status, err) { - break - } - timer := time.NewTimer(jobSummaryUploadRetryDelay) - select { - case <-ctx.Done(): - timer.Stop() - lastErr = ctx.Err() - attempt = 1 - case <-timer.C: - } +func uploadJobSummary(ctx context.Context, client *http.Client, url, runtimeToken string, body []byte) (int, error) { + status, err := putJobSummary(ctx, client, url, runtimeToken, body) + if !isTransientJobSummaryUploadFailure(status, err) { + return status, err } - - // Best-effort only; do not fail job, but log because capability was advertised. - if lastErr != nil { - logger.WithError(lastErr).Warn("job summary upload failed") - return + select { + case <-ctx.Done(): + return status, ctx.Err() + case <-time.After(time.Second): + return putJobSummary(ctx, client, url, runtimeToken, body) } - logger.Warnf("job summary upload failed: status=%d", lastStatus) } func putJobSummary(ctx context.Context, client *http.Client, url, runtimeToken string, body []byte) (int, error) { @@ -693,6 +615,10 @@ func isTransientJobSummaryUploadFailure(status int, err error) bool { } func readSingleFileFromContainerArchive(ctx context.Context, env container.ExecutionsEnvironment, p string, maxBytes int64) ([]byte, bool) { + return readContainerFile(ctx, env, p, func() int64 { return maxBytes }) +} + +func readContainerFile(ctx context.Context, env container.ExecutionsEnvironment, p string, limit func() int64) ([]byte, bool) { rc, err := env.GetContainerArchive(ctx, p) if err != nil { return nil, false @@ -713,7 +639,10 @@ func readSingleFileFromContainerArchive(ctx context.Context, env container.Execu if entryName != requestedPath && entryName != path.Base(requestedPath) { continue } - b, err := io.ReadAll(io.LimitReader(transform.NewReader(tr, unicodeencoding.BOMOverride(unicodeencoding.UTF8.NewDecoder())), maxBytes)) + if header.Size == 0 { + return []byte{}, true + } + b, err := io.ReadAll(io.LimitReader(transform.NewReader(tr, unicodeencoding.BOMOverride(unicodeencoding.UTF8.NewDecoder())), limit())) if err != nil { return nil, false } diff --git a/act/runner/job_executor_test.go b/act/runner/job_executor_test.go index 07bfc7e2..f17c12d8 100644 --- a/act/runner/job_executor_test.go +++ b/act/runner/job_executor_test.go @@ -13,11 +13,12 @@ import ( "fmt" "io" "net/http" - "net/http/httptest" + "os" "path/filepath" "slices" "strconv" "strings" + "sync" "sync/atomic" "testing" "testing/synctest" @@ -30,17 +31,15 @@ import ( "gitea.com/gitea/runner/act/container" "gitea.dev/actionslib/pkg/model" + "gitea.dev/actionslib/pkg/protocol" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" yaml "go.yaml.in/yaml/v4" - "golang.org/x/text/encoding" - "golang.org/x/text/encoding/unicode" ) func TestJobExecutor(t *testing.T) { t.Parallel() - // Dryrun only checks syntax/planning; all cases resolve locally, so this runs offline. tables := []TestJobFileInfo{ {workdir, "uses-and-run-in-one-step", "push", "Invalid run/uses syntax for job:test step:Test", platforms, secrets}, {workdir, "uses-github-empty", "push", "Expected format {org}/{repo}[/path]@ref", platforms, secrets}, @@ -49,7 +48,6 @@ func TestJobExecutor(t *testing.T) { {workdir, "uses-docker-url", "push", "", platforms, secrets}, {workdir, "job-nil-step", "push", "invalid Step 0: missing run or uses key", platforms, secrets}, } - // These tests are sufficient to only check syntax. ctx := common.WithDryrun(t.Context(), true) for _, table := range tables { t.Run(table.workflowPath, func(t *testing.T) { @@ -63,11 +61,6 @@ type jobInfoMock struct { mock.Mock } -func (jim *jobInfoMock) matrix() map[string]any { - args := jim.Called() - return args.Get(0).(map[string]any) -} - func (jim *jobInfoMock) steps() []*model.Step { args := jim.Called() @@ -98,10 +91,6 @@ func (jim *jobInfoMock) interpolateOutputs() common.Executor { return args.Get(0).(func(context.Context) error) } -func (jim *jobInfoMock) result(result string) { - jim.Called(result) -} - type jobContainerMock struct { container.Container linuxEnvironment @@ -120,7 +109,6 @@ func (sfm *stepFactoryMock) newStep(model *model.Step, rc *RunContext) (step, er return args.Get(0).(step), args.Error(1) } -// actionPreparerMock stands in for a step whose action is downloaded before the job's first step. type actionPreparerMock struct { reference string sha string @@ -229,34 +217,13 @@ func TestPrintPrepareActionsSkipsWithoutActions(t *testing.T) { assert.Empty(t, buf.String()) } -func TestNewStepsExecutorSkipsStepsAfterSetupFailure(t *testing.T) { - for name, tt := range map[string]struct { - preErr error - mainRan bool - }{ - "setup failure": {preErr: setupError{assert.AnError}}, - "pre step failure": {preErr: assert.AnError, mainRan: true}, // always() steps still run, as on GitHub - } { - t.Run(name, func(t *testing.T) { - ctx := common.WithJobErrorContainer(common.WithLogger(context.Background(), logging.New(logtest.New()))) - mainRan := false - err := newStepsExecutor(&RunContext{}, - []common.Executor{func(context.Context) error { return tt.preErr }}, - []common.Executor{func(context.Context) error { mainRan = true; return nil }}, - )(ctx) - require.ErrorIs(t, err, assert.AnError) - assert.Equal(t, tt.mainRan, mainRan) - }) - } -} - func TestPrintCompleteJobName(t *testing.T) { for name, tt := range map[string]struct { rc *RunContext want string }{ - "job name": {rc: &RunContext{JobName: "lint", Name: "lint-1"}, want: "lint"}, - "falls back to name": {rc: &RunContext{Name: "lint-1"}, want: "lint-1"}, + "job name": {rc: &RunContext{Run: &model.Run{JobID: "id"}, JobName: "lint", Name: "lint-1"}, want: "lint"}, + "falls back to name": {rc: &RunContext{Run: &model.Run{JobID: "id"}, Name: "lint-1"}, want: "lint-1"}, "falls back to jobID": {rc: &RunContext{Run: &model.Run{JobID: "lint"}}, want: "lint"}, } { t.Run(name, func(t *testing.T) { @@ -271,41 +238,26 @@ func TestPrintCompleteJobName(t *testing.T) { } } -// actionStepMock is a step whose action has to be downloaded before it can run. type actionStepMock struct { *stepMock *actionPreparerMock } -// TestNewJobExecutorDownloadsAllActionsBeforeTheFirstStep pins the shape of the setup section: -// every action is downloaded before any step runs, and the job name closes the section. A pre -// step that downloaded its own action would leave the log interleaved with the downloads. func TestNewJobExecutorDownloadsAllActionsBeforeTheFirstStep(t *testing.T) { ctx := common.WithJobErrorContainer(t.Context()) jim := &jobInfoMock{} sfm := &stepFactoryMock{} - rc := &RunContext{ - JobContainer: &jobContainerMock{}, - Run: &model.Run{ - JobID: "test", - Workflow: &model.Workflow{ - Jobs: map[string]*model.Job{"test": {}}, - }, - }, - Config: &Config{PresetGitHubContext: &model.GithubContext{}}, - } - rc.ExprEval = rc.NewExpressionEvaluator(ctx) + rc := makeTestRC(t, "{}") + rc.JobContainer = &jobContainerMock{} steps := []*model.Step{{ID: "1"}, {ID: "2"}} executorOrder := make([]string, 0) jim.On("steps").Return(steps) - jim.On("matrix").Return(map[string]any{}) jim.On("startContainer").Return(func(context.Context) error { return nil }) jim.On("stopContainer").Return(func(context.Context) error { return nil }) jim.On("closeContainer").Return(func(context.Context) error { return nil }) jim.On("interpolateOutputs").Return(func(context.Context) error { return nil }) - jim.On("result", "success") for _, stepModel := range steps { sm := &stepMock{} @@ -330,9 +282,9 @@ func TestNewJobExecutorDownloadsAllActionsBeforeTheFirstStep(t *testing.T) { err := newJobExecutor(jim, sfm, rc)(common.WithLogger(ctx, logger.With("job", "test"))) require.NoError(t, err) + assert.Equal(t, "success", rc.Run.Job().Result) assert.Equal(t, []string{"pre1", "pre2", "step1", "step2"}, executorOrder) - // the setup is logged ahead of the pre steps and the cleanup is tagged, so the reporter can show both as steps of their own setup := make([]string, 0) for _, entry := range hook.AllRecords() { if strings.HasPrefix(entry.Message, "Prepare all required actions") || strings.HasPrefix(entry.Message, "Download action") || @@ -348,181 +300,82 @@ func TestNewJobExecutorDownloadsAllActionsBeforeTheFirstStep(t *testing.T) { "Prepare all required actions", "Download action repository 'actions/checkout@v1' (SHA:sha1)", "Download action repository 'actions/checkout@v2' (SHA:sha2)", - "Complete job name: test", + "Complete job name: job1", "Run Pre 1", "Run Pre 2", }, setup) } func TestNewJobExecutor(t *testing.T) { + completed := []string{"startContainer", "step1", "interpolateOutputs", "stopContainer", "closeContainer"} + completedWithPost := []string{"startContainer", "step1", "post1", "interpolateOutputs", "stopContainer", "closeContainer"} table := []struct { name string - steps []*model.Step - preSteps []bool - postSteps []bool + steps int + preSteps []int + postSteps []int executedSteps []string result string - hasError bool + stepFails bool output string startError error cancelOnStart bool + cancelOnClose bool timeout bool }{ { - name: "zeroSteps", - steps: []*model.Step{}, - preSteps: []bool{}, - postSteps: []bool{}, + name: "no steps leaves the result unset", executedSteps: []string{}, + }, + { + name: "step failure still cleans up", + steps: 1, + executedSteps: completed, + result: "failure", + stepFails: true, + }, + { + name: "post steps run in reverse order", + steps: 3, + preSteps: []int{1, 3}, + postSteps: []int{2, 3}, + executedSteps: []string{"startContainer", "pre1", "pre3", "step1", "step2", "step3", "post3", "post2", "interpolateOutputs", "stopContainer", "closeContainer"}, result: "success", - hasError: false, }, { - name: "stepWithoutPrePost", - steps: []*model.Step{{ - ID: "1", - }}, - preSteps: []bool{false}, - postSteps: []bool{false}, - executedSteps: []string{ - "startContainer", - "step1", - "interpolateOutputs", - "stopContainer", - "closeContainer", - }, - result: "success", - hasError: false, - }, - { - name: "stepWithFailure", - steps: []*model.Step{{ - ID: "1", - }}, - preSteps: []bool{false}, - postSteps: []bool{false}, - executedSteps: []string{ - "startContainer", - "step1", - "interpolateOutputs", - "stopContainer", - "closeContainer", - }, - result: "failure", - hasError: true, - }, - { - name: "stepWithPre", - steps: []*model.Step{{ - ID: "1", - }}, - preSteps: []bool{true}, - postSteps: []bool{false}, - executedSteps: []string{ - "startContainer", - "pre1", - "step1", - "interpolateOutputs", - "stopContainer", - "closeContainer", - }, - result: "success", - hasError: false, - }, - { - name: "stepWithPost", - steps: []*model.Step{{ - ID: "1", - }}, - preSteps: []bool{false}, - postSteps: []bool{true}, - executedSteps: []string{ - "startContainer", - "step1", - "post1", - "interpolateOutputs", - "stopContainer", - "closeContainer", - }, - result: "success", - hasError: false, - }, - { - name: "stepWithPreAndPost", - steps: []*model.Step{{ - ID: "1", - }}, - preSteps: []bool{true}, - postSteps: []bool{true}, - executedSteps: []string{ - "startContainer", - "pre1", - "step1", - "post1", - "interpolateOutputs", - "stopContainer", - "closeContainer", - }, - result: "success", - hasError: false, - }, - { - name: "stepsWithPreAndPost", - steps: []*model.Step{{ - ID: "1", - }, { - ID: "2", - }, { - ID: "3", - }}, - preSteps: []bool{true, false, true}, - postSteps: []bool{false, true, true}, - executedSteps: []string{ - "startContainer", - "pre1", - "pre3", - "step1", - "step2", - "step3", - "post3", - "post2", - "interpolateOutputs", - "stopContainer", - "closeContainer", - }, - result: "success", - hasError: false, - }, - { - name: "jobOutputExpressionFailure", - steps: []*model.Step{{ID: "1"}}, - preSteps: []bool{false}, - postSteps: []bool{false}, - executedSteps: []string{"startContainer", "step1", "interpolateOutputs", "stopContainer", "closeContainer"}, + name: "invalid job output fails the job", + steps: 1, + executedSteps: completed, result: "failure", output: "${{ 'test' != test }}", }, { - name: "start failure", - steps: []*model.Step{{ID: "1"}}, + name: "start failure still closes the container", + steps: 1, executedSteps: []string{"startContainer", "closeContainer"}, startError: errors.New("start failed"), + result: "failure", + }, + { + name: "cancelled while closing the container", + steps: 1, + executedSteps: completed, + cancelOnClose: true, + result: "cancelled", }, { name: "cancelled at startup boundary", - steps: []*model.Step{{ID: "1"}}, - preSteps: []bool{false}, - postSteps: []bool{true}, - executedSteps: []string{"startContainer", "step1", "post1", "interpolateOutputs", "stopContainer", "closeContainer"}, + steps: 1, + postSteps: []int{1}, + executedSteps: completedWithPost, result: "cancelled", cancelOnStart: true, }, { - name: "post steps run after timeout", - steps: []*model.Step{{ID: "1"}}, - preSteps: []bool{false}, - postSteps: []bool{true}, - executedSteps: []string{"startContainer", "step1", "post1", "interpolateOutputs", "stopContainer", "closeContainer"}, + name: "post steps run after the parent deadline", + steps: 1, + postSteps: []int{1}, + executedSteps: completedWithPost, result: "failure", timeout: true, }, @@ -542,27 +395,20 @@ func TestNewJobExecutor(t *testing.T) { defer cancel() jim := &jobInfoMock{} sfm := &stepFactoryMock{} - rc := &RunContext{ - JobContainer: &jobContainerMock{}, - Run: &model.Run{ - JobID: "test", - Workflow: &model.Workflow{ - Jobs: map[string]*model.Job{ - "test": {}, - }, - }, - }, - Config: &Config{PresetGitHubContext: &model.GithubContext{}}, - } + rc := makeTestRC(t, "{}") + rc.JobContainer = &jobContainerMock{} if tt.output != "" { require.NoError(t, rc.Run.Job().RawOutputs.Encode(map[string]string{"bad": tt.output})) } - rc.ExprEval = rc.NewExpressionEvaluator(ctx) executorOrder := make([]string, 0) - jim.On("steps").Return(tt.steps) + steps := make([]*model.Step, tt.steps) + for i := range steps { + steps[i] = &model.Step{ID: strconv.Itoa(i + 1)} + } + jim.On("steps").Return(steps) - if len(tt.steps) > 0 { + if tt.steps > 0 { jim.On("startContainer").Return(func(_ context.Context) error { executorOrder = append(executorOrder, "startContainer") if tt.cancelOnStart { @@ -572,13 +418,13 @@ func TestNewJobExecutor(t *testing.T) { }) } - for i, stepModel := range tt.steps { + for i, stepModel := range steps { sm := &stepMock{} sfm.On("newStep", stepModel, rc).Return(sm, nil) sm.On("pre").Return(func(_ctx context.Context) error { - if tt.preSteps[i] { + if slices.Contains(tt.preSteps, i+1) { executorOrder = append(executorOrder, "pre"+stepModel.ID) } return nil @@ -590,14 +436,14 @@ func TestNewJobExecutor(t *testing.T) { expire() return ctx.Err() } - if tt.hasError { + if tt.stepFails { return errors.New("error") } return nil }) sm.On("post").Return(func(ctx context.Context) error { - if tt.postSteps[i] { + if slices.Contains(tt.postSteps, i+1) { executorOrder = append(executorOrder, "post"+stepModel.ID) } if tt.timeout { @@ -609,9 +455,7 @@ func TestNewJobExecutor(t *testing.T) { defer sm.AssertExpectations(t) } - if len(tt.steps) > 0 && tt.startError == nil { - jim.On("matrix").Return(map[string]any{}) - + if tt.steps > 0 && tt.startError == nil { jim.On("interpolateOutputs").Return(func(ctx context.Context) error { executorOrder = append(executorOrder, "interpolateOutputs") if tt.output != "" { @@ -620,28 +464,26 @@ func TestNewJobExecutor(t *testing.T) { return nil }) - if slices.Contains(tt.executedSteps, "stopContainer") { - jim.On("stopContainer").Return(func(ctx context.Context) error { - executorOrder = append(executorOrder, "stopContainer") - require.NoError(t, ctx.Err()) - _, bounded := ctx.Deadline() - require.True(t, bounded) - return nil - }) - } - - jim.On("result", tt.result) - } - - if len(tt.steps) > 0 { - jim.On("closeContainer").Return(func(_ctx context.Context) error { - executorOrder = append(executorOrder, "closeContainer") + jim.On("stopContainer").Return(func(ctx context.Context) error { + executorOrder = append(executorOrder, "stopContainer") + require.NoError(t, ctx.Err()) + _, bounded := ctx.Deadline() + require.True(t, bounded) return nil }) } - executor := newJobExecutor(jim, sfm, rc) - err := executor(ctx) + if tt.steps > 0 { + jim.On("closeContainer").Return(func(_ctx context.Context) error { + executorOrder = append(executorOrder, "closeContainer") + if tt.cancelOnClose { + cancel() + } + return nil + }) + } + + err := newJobExecutor(jim, sfm, rc)(ctx) switch { case tt.startError != nil: require.ErrorIs(t, err, tt.startError) @@ -650,7 +492,10 @@ func TestNewJobExecutor(t *testing.T) { default: require.NoError(t, err) } - assert.Empty(t, rc.Run.Job().Outputs["bad"]) + assert.Equal(t, tt.result, rc.Run.Job().Result) + if tt.output != "" { + assert.Empty(t, rc.Run.Job().Outputs["bad"]) + } assert.Equal(t, tt.executedSteps, executorOrder) jim.AssertExpectations(t) @@ -688,27 +533,55 @@ func (ctx *controllableDeadlineContext) expire() { func TestSetJobResultMatrixContinueOnError(t *testing.T) { ctx := t.Context() for name, tolerated := range map[string]bool{ - "one tolerated and one firm failure fails the run": false, - "all tolerated failures do not fail the run": true, + "one tolerated and one firm failure fails the run and its caller": false, + "all tolerated failures fail neither the run nor its caller": true, } { t.Run(name, func(t *testing.T) { - var job *model.Job - require.NoError(t, yaml.Unmarshal([]byte("continue-on-error: ${{ matrix.experimental }}\nruns-on: ubuntu-latest"), &job)) - workflow := &model.Workflow{Name: "workflow1", Jobs: map[string]*model.Job{"job1": job}} + run := makeTestRC(t, "continue-on-error: ${{ matrix.experimental }}").Run + job := run.Job() + var siblings sync.WaitGroup for _, experimental := range []bool{true, tolerated} { - rc := newTestRC(workflow, map[string]any{"experimental": experimental}) + rc := newTestRC(run.Workflow, map[string]any{"experimental": experimental}) rc.Config.PresetGitHubContext = &model.GithubContext{} - setJobResult(ctx, rc, rc, false) + rc.jobTotal = 2 + siblings.Go(func() { rc.setJobResult(ctx, false) }) } + siblings.Wait() assert.Equal(t, "failure", job.Result) assert.Equal(t, tolerated, job.ContinueOnError) - err := handleFailure(&model.Plan{Stages: []*model.Stage{{Runs: []*model.Run{{Workflow: workflow, JobID: "job1"}}}}})(ctx) + err := handleFailure(&model.Plan{Stages: []*model.Stage{{Runs: []*model.Run{run}}}})(ctx) if tolerated { require.NoError(t, err) } else { require.Error(t, err) } + callerRC := makeTestRC(t, "{}") + callerRC.Config.PresetGitHubContext = &model.GithubContext{} + (&caller{runContext: callerRC, reportedRuns: []*model.Run{run}}).finishWorkflowCall(ctx, nil) + assert.Equal(t, map[bool]string{true: "success", false: "failure"}[tolerated], callerRC.Run.Job().Result) + }) + } +} + +func TestSkippedMatrixCombinationsPreserveJobResult(t *testing.T) { + for _, test := range []struct{ prior, afterSkip, afterRun string }{ + {"", "skipped", "success"}, + {"failure", "failure", "failure"}, + {"cancelled", "cancelled", "cancelled"}, + } { + t.Run(test.afterSkip, func(t *testing.T) { + rc := makeTestRC(t, "if: false") + rc.jobTotal = 3 + rc.caller = &caller{reportedRuns: []*model.Run{nil}} + rc.Run.Job().Result = test.prior + enabled, err := rc.isEnabled(t.Context()) + require.NoError(t, err) + assert.False(t, enabled) + require.Same(t, rc.Run, rc.caller.reportedRuns[0]) + assert.Equal(t, test.afterSkip, rc.Run.Job().Result) + rc.setJobResult(t.Context(), test.prior != "cancelled") + assert.Equal(t, test.afterRun, rc.Run.Job().Result) }) } } @@ -719,212 +592,144 @@ func TestHasJobSummaryCapability(t *testing.T) { assert.False(t, hasJobSummaryCapability("not-job-summary,job-summary-v2")) } -// fakeRuntimeToken builds a JWT-shaped string whose middle (claims) segment encodes -// the given JobID. The header and signature segments are filler — the runner does not -// verify the signature; the server does. func fakeRuntimeToken(jobID int64) string { - header := base64.RawURLEncoding.EncodeToString([]byte(`{"alg":"HS256","typ":"JWT"}`)) - claims := base64.RawURLEncoding.EncodeToString(fmt.Appendf(nil, `{"JobID":%d}`, jobID)) - sig := base64.RawURLEncoding.EncodeToString([]byte("sig")) - return header + "." + claims + "." + sig + return "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9." + base64.RawURLEncoding.EncodeToString(fmt.Appendf(nil, `{"JobID":%d}`, jobID)) + ".c2ln" } -func newJobSummaryRC(env map[string]string, jobContainer container.ExecutionsEnvironment, stepCount int) *RunContext { - steps := make([]*model.Step, stepCount) - for i := range steps { - steps[i] = &model.Step{ID: strconv.Itoa(i)} - } - return &RunContext{ - Config: &Config{}, - JobContainer: jobContainer, - Env: env, - Run: &model.Run{ - JobID: "test", - Workflow: &model.Workflow{ - Jobs: map[string]*model.Job{ - "test": {Steps: steps}, - }, - }, - }, - } +func newJobSummaryRC(t *testing.T, transport summaryTransport) *RunContext { + t.Helper() + const runtimeURL = "https://runtime.example" + rc := makeTestRC(t, "{}") + rc.JobContainer = &container.HostEnvironment{ActPath: t.TempDir()} + rc.Config.GitHubInstance, rc.Config.InstanceTransport = runtimeURL, transport + rc.Env["GITEA_ACTIONS_CAPABILITIES"] = "job-summary" + rc.Env["ACTIONS_RUNTIME_URL"] = runtimeURL + rc.Env["ACTIONS_RUNTIME_TOKEN"] = fakeRuntimeToken(34) + rc.Env["GITEA_RUN_ID"] = "12" + return rc } -func TestTryUploadJobSummaryRetriesTransientFailure(t *testing.T) { - oldDelay := jobSummaryUploadRetryDelay - jobSummaryUploadRetryDelay = 0 - defer func() { - jobSummaryUploadRetryDelay = oldDelay - }() +type summaryTransport func(*http.Request) (*http.Response, error) - runtimeToken := fakeRuntimeToken(34) +func (transport summaryTransport) RoundTrip(request *http.Request) (*http.Response, error) { + return transport(request) +} - requests := 0 - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - requests++ +func TestStepSummaryRetriesWithinPhaseTimeout(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + start := time.Now() + var attempts []string + started := make(chan struct{}) + var finished time.Time + rc := newJobSummaryRC(t, func(request *http.Request) (*http.Response, error) { + defer request.Body.Close() + body, err := io.ReadAll(request.Body) + if err != nil { + return nil, err + } + attempts = append(attempts, string(body)) + if len(attempts) == 1 { + close(started) + } + <-request.Context().Done() + finished = time.Now() + return nil, request.Context().Err() + }) + summaryPath := container.JoinPath(rc.JobContainer.GetActPath(), "summary.md") + steps := []*model.Step{{ID: "first"}, {ID: "second"}} + job := &jobInfoMock{} + job.On("steps").Return(steps) + for _, method := range []string{"startContainer", "interpolateOutputs", "stopContainer", "closeContainer"} { + job.On(method).Return(noopExecutor) + } + step := &stepMock{} + step.On("pre").Return(noopExecutor) + step.On("post").Return(noopExecutor) + step.On("main").Return(func(ctx context.Context) error { + require.NoError(t, os.WriteFile(summaryPath, []byte(steps[rc.CurrentStepIndex].ID), 0o600)) + processStepSummary(ctx, rc, summaryPath) + <-started + assert.Zero(t, time.Since(start)) + return nil + }) + factory := &stepFactoryMock{} + factory.On("newStep", mock.Anything, rc).Return(step, nil) + require.NoError(t, newJobExecutor(job, factory, rc)(t.Context())) + assert.Equal(t, jobSummaryUploadPhaseTimeout, time.Since(start)) + synctest.Wait() + assert.Equal(t, []string{"first", "first", "second"}, attempts) + assert.Equal(t, "success", rc.Run.Job().Result) + assert.Equal(t, time.Now(), finished) + }) +} + +func TestStepSummaryUploadsAfterEachOuterPhase(t *testing.T) { + type upload struct{ path, body string } + var got []upload + rc := newJobSummaryRC(t, func(r *http.Request) (*http.Response, error) { + defer r.Body.Close() assert.Equal(t, http.MethodPut, r.Method) - assert.Equal(t, "/_apis/pipelines/workflows/12/jobs/34/steps/0/summary", r.URL.Path) - assert.Equal(t, "Bearer "+runtimeToken, r.Header.Get("Authorization")) + assert.Equal(t, "Bearer "+fakeRuntimeToken(34), r.Header.Get("Authorization")) assert.Equal(t, "text/markdown; charset=utf-8", r.Header.Get("Content-Type")) body, err := io.ReadAll(r.Body) - assert.NoError(t, err) - assert.Equal(t, []byte("# summary"), body) - if requests == 1 { - w.WriteHeader(http.StatusInternalServerError) - return - } - w.WriteHeader(http.StatusNoContent) - })) - defer server.Close() - - ctx := t.Context() - cm := &containerMock{} - cm.On("GetContainerArchive", mock.Anything, "/var/run/act/workflow/step-summary-0.md").Return( - io.NopCloser(bytes.NewReader(tarArchive(t, tarEntry{name: "step-summary-0.md", body: "# summary"}))), - nil, - ).Once() - - rc := newJobSummaryRC(map[string]string{ - "GITEA_ACTIONS_CAPABILITIES": "cache, job-summary", - "ACTIONS_RUNTIME_URL": server.URL, - "ACTIONS_RUNTIME_TOKEN": runtimeToken, - "GITEA_RUN_ID": "12", - }, cm, 1) - - tryUploadJobSummary(ctx, rc) - - assert.Equal(t, 2, requests) - cm.AssertExpectations(t) -} - -func TestTryUploadJobSummaryStopsAtPhaseTimeout(t *testing.T) { - oldPhase := jobSummaryUploadPhaseTimeout - jobSummaryUploadPhaseTimeout = 100 * time.Millisecond - defer func() { - jobSummaryUploadPhaseTimeout = oldPhase - }() - - runtimeToken := fakeRuntimeToken(34) - - // The server blocks until either the request context is cancelled (the behaviour - // under test: the phase timeout aborts the in-flight upload) or the test tears it - // down. Without the phase timeout the upload would hang until the 30s client - // timeout instead of releasing the cleanup budget. The release channel guarantees - // the handler always returns so server.Close() cannot itself hang. - release := make(chan struct{}) - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - select { - case <-r.Context().Done(): - case <-release: - } - })) - defer server.Close() - defer close(release) - - ctx := t.Context() - cm := &containerMock{} - cm.On("GetContainerArchive", mock.Anything, "/var/run/act/workflow/step-summary-0.md").Return( - io.NopCloser(bytes.NewReader(tarArchive(t, tarEntry{name: "step-summary-0.md", body: "# summary"}))), - nil, - ).Once() - - rc := newJobSummaryRC(map[string]string{ - "GITEA_ACTIONS_CAPABILITIES": "job-summary", - "ACTIONS_RUNTIME_URL": server.URL, - "ACTIONS_RUNTIME_TOKEN": runtimeToken, - "GITEA_RUN_ID": "12", - }, cm, 1) - - done := make(chan struct{}) - go func() { - defer close(done) - tryUploadJobSummary(ctx, rc) - }() - - select { - case <-done: - case <-time.After(5 * time.Second): - t.Fatal("tryUploadJobSummary did not honour the phase timeout") - } - cm.AssertExpectations(t) -} - -func TestTryUploadJobSummaryUploadsEachStepIndependentlyWithInstanceTransport(t *testing.T) { - runtimeToken := fakeRuntimeToken(34) - - type upload struct { - path string - body string - } - var got []upload - server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - body, err := io.ReadAll(r.Body) - assert.NoError(t, err) got = append(got, upload{r.URL.Path, string(body)}) - w.WriteHeader(http.StatusNoContent) - })) - defer server.Close() - + return &http.Response{StatusCode: http.StatusNoContent, Body: http.NoBody}, err + }) ctx := t.Context() - cm := &containerMock{} - // Three steps: 0 has content, 1 has empty content (skipped), 2 has content. - cm.On("GetContainerArchive", mock.Anything, "/var/run/act/workflow/step-summary-0.md").Return( - io.NopCloser(bytes.NewReader(tarArchive(t, tarEntry{name: "step-summary-0.md", body: "first"}))), - nil, - ).Once() - cm.On("GetContainerArchive", mock.Anything, "/var/run/act/workflow/step-summary-1.md").Return( - io.NopCloser(bytes.NewReader(tarArchive(t, tarEntry{name: "step-summary-1.md", body: ""}))), - nil, - ).Once() - cm.On("GetContainerArchive", mock.Anything, "/var/run/act/workflow/step-summary-2.md").Return( - io.NopCloser(bytes.NewReader(tarArchive(t, tarEntry{name: "step-summary-2.md", body: "third"}))), - nil, - ).Once() + rc.summaryUploads = newStepSummaryUploads(ctx) + outer := &stepRun{RunContext: rc, Step: &model.Step{ID: "outer"}, env: map[string]string{}} + childRC := &RunContext{Parent: rc, Run: rc.Run, Config: rc.Config, JobContainer: rc.JobContainer} + childRC.ExprEval = childRC.NewExpressionEvaluator(ctx) + child := &stepRun{RunContext: childRC, Step: &model.Step{ID: "child"}, env: map[string]string{}} - rc := newJobSummaryRC(map[string]string{ - "GITEA_ACTIONS_CAPABILITIES": "job-summary", - "ACTIONS_RUNTIME_URL": server.URL, - "ACTIONS_RUNTIME_TOKEN": runtimeToken, - "GITEA_RUN_ID": "12", - }, cm, 3) - rc.Config.GitHubInstance, rc.Config.InstanceTransport = server.URL, server.Client().Transport + rc.CurrentStepIndex = 1 + require.NoError(t, runStepExecutor(outer, stepStagePre, runStepExecutor(child, stepStagePre, func(ctx context.Context) error { + childRC.AddMask(ctx, "private") + return os.WriteFile(child.env["GITHUB_STEP_SUMMARY"], []byte("pre private"), 0o600) + }))(ctx)) - tryUploadJobSummary(ctx, rc) + rc.CurrentStepIndex = 0 + first := &stepRun{RunContext: rc, Step: &model.Step{ID: "first"}, env: map[string]string{}} + require.NoError(t, runStepExecutor(first, stepStageMain, func(context.Context) error { + return os.WriteFile(first.env["GITHUB_STEP_SUMMARY"], []byte("first"), 0o600) + })(ctx)) - assert.Equal(t, []upload{ - {"/_apis/pipelines/workflows/12/jobs/34/steps/0/summary", "first"}, - {"/_apis/pipelines/workflows/12/jobs/34/steps/2/summary", "third"}, - }, got) - cm.AssertExpectations(t) -} + rc.CurrentStepIndex = 1 + require.NoError(t, runStepExecutor(outer, stepStageMain, func(context.Context) error { + content, err := os.ReadFile(outer.env["GITHUB_STEP_SUMMARY"]) + require.NoError(t, err) + return os.WriteFile(outer.env["GITHUB_STEP_SUMMARY"], append(content, " main"...), 0o600) + })(ctx)) -func TestTryUploadJobSummarySkipsUnsupportedUploads(t *testing.T) { - for name, tt := range map[string]struct { - capabilities string - runtimeToken string - }{ - "requires exact capability": {"not-job-summary,job-summary-v2", fakeRuntimeToken(34)}, - "requires job ID": {"job-summary", "not-a-jwt"}, - } { - t.Run(name, func(t *testing.T) { - requests := 0 - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _r *http.Request) { - requests++ - w.WriteHeader(http.StatusNoContent) - })) - defer server.Close() + rc.CurrentStepIndex = 2 + empty := &stepRun{RunContext: rc, Step: &model.Step{ID: "empty"}, env: map[string]string{}} + require.NoError(t, runStepExecutor(empty, stepStageMain, func(context.Context) error { + return os.Remove(first.env["GITHUB_STEP_SUMMARY"]) + })(ctx)) - rc := newJobSummaryRC(map[string]string{ - "GITEA_ACTIONS_CAPABILITIES": tt.capabilities, - "ACTIONS_RUNTIME_URL": server.URL, - "ACTIONS_RUNTIME_TOKEN": tt.runtimeToken, - "GITEA_RUN_ID": "12", - }, &containerMock{}, 1) + rc.CurrentStepIndex = 1 + postCtx, cancel := context.WithCancel(ctx) + defer cancel() + require.ErrorIs(t, runStepExecutor(outer, stepStagePost, func(context.Context) error { + require.NoError(t, os.WriteFile(outer.env["GITHUB_STEP_SUMMARY"], []byte("post private"), 0o600)) + cancel() + return postCtx.Err() + })(postCtx), context.Canceled) - tryUploadJobSummary(t.Context(), rc) - - assert.Zero(t, requests) - }) + for key, invalid := range map[string]string{"GITEA_ACTIONS_CAPABILITIES": "not-job-summary,job-summary-v2", "ACTIONS_RUNTIME_TOKEN": "not-a-jwt"} { + saved := rc.Env[key] + rc.Env[key] = invalid + processStepSummary(ctx, rc, outer.env["GITHUB_STEP_SUMMARY"]) + rc.Env[key] = saved } + rc.summaryUploads.wait(ctx) + const base = "/_apis/pipelines/workflows/12/jobs/34/steps/" + assert.Equal(t, []upload{ + {base + "1/summary", "pre ***"}, + {base + "0/summary", "first"}, + {base + "1/summary", "pre *** main"}, + {base + "1/summary", "post ***"}, + }, got) } func TestExtractJobIDFromRuntimeToken(t *testing.T) { @@ -944,7 +749,8 @@ func TestReadSingleFileFromContainerArchive(t *testing.T) { "truncates oversized summary without reading entire file": {strings.Repeat("a", 100000), 200, strings.Repeat("a", 200-len(jobSummaryTruncationMarker)) + jobSummaryTruncationMarker}, "keeps exact limit": {"abc", 3, "abc"}, "strips UTF-8 BOM before limit": {"\xef\xbb\xbfabc", 3, "abc"}, - "decodes UTF-16 before limit": {"\xff\xfea\x00b\x00c\x00", 3, "abc"}, + "decodes UTF-16LE before limit": {"\xff\xfea\x00b\x00c\x00", 3, "abc"}, + "decodes UTF-16BE before limit": {"\xfe\xff\x00a\x00b\x00c", 3, "abc"}, "limits expanded UTF-16": {"\xff\xfe" + strings.Repeat("\x2d\x4e", 150), 200, strings.Repeat("中", retainedBytes/3) + jobSummaryTruncationMarker}, "keeps complete UTF-8 characters": {strings.Repeat("a", retainedBytes-1) + "€" + strings.Repeat("a", 200), 200, strings.Repeat("a", retainedBytes-1) + jobSummaryTruncationMarker}, } { @@ -1042,25 +848,25 @@ func makeTestRC(t *testing.T, jobYAML string) *RunContext { } func TestApplyJobTimeout(t *testing.T) { - cases := []struct { - name string - yaml string - want time.Duration - }{ - {"empty", "runs-on: ubuntu-latest", 0}, - {"integer", "timeout-minutes: 5\nruns-on: ubuntu-latest", 5 * time.Minute}, - {"zero ignored", "timeout-minutes: 0\nruns-on: ubuntu-latest", 0}, - {"non-numeric ignored", "timeout-minutes: abc\nruns-on: ubuntu-latest", 0}, - } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - rc := makeTestRC(t, tc.yaml) - newCtx, cancel := applyJobTimeout(t.Context(), rc, rc.Run.Job()) + for input, want := range map[string]time.Duration{"": 0, "5": 5 * time.Minute, "0": 0} { + synctest.Test(t, func(t *testing.T) { + rc := makeTestRC(t, "runs-on: ubuntu-latest") + rc.Run.Job().TimeoutMinutes = input + logger, hook := logtest.NewLogger() + ctx, cancel, err := applyJobTimeout(common.WithLogger(t.Context(), logger), rc, rc.Run.Job()) + require.NoError(t, err) defer cancel() - deadline, hasDeadline := newCtx.Deadline() - assert.Equal(t, tc.want != 0, hasDeadline) - if hasDeadline { - assert.WithinDuration(t, time.Now().Add(tc.want), deadline, time.Minute) + deadline, ok := ctx.Deadline() + require.Equal(t, want > 0, ok) + if ok { + assert.Equal(t, want, time.Until(deadline)) + <-ctx.Done() + reportStepError(ctx, rc, ctx.Err()) + rc.markJobInterrupted(ctx) + require.Len(t, hook.AllRecords(), 1) + assert.Equal(t, "##[error]The job has exceeded the maximum execution time of 5m0s", hook.LastRecord().Message) + rc.setJobResult(ctx, true) + assert.Equal(t, "cancelled", rc.Run.Job().Result) } }) } @@ -1108,76 +914,49 @@ func TestJobSetContinueOnError(t *testing.T) { } } -func TestTryUploadJobSummaryMasksSecrets(t *testing.T) { +func TestStepSummaryMasksSecrets(t *testing.T) { const prefix = "deployed true with s3cr3t and runtime-added via pr0xypw 😀" const maskedPrefix = "deployed true with *** and *** via *** 😀" - padding := strings.Repeat("a", maxJobSummaryBytes-len(jobSummaryTruncationMarker)-len(prefix)-2) + padding := strings.Repeat("a", protocol.MaxStepSummarySize-len(jobSummaryTruncationMarker)-len(prefix)-2) content := prefix + padding + "s3cr3t" + strings.Repeat("中", 100) want := maskedPrefix + padding + "***" + strings.Repeat("中", (len(prefix)-len(maskedPrefix)-1)/3) + jobSummaryTruncationMarker longSecret := "PREFIX" + strings.Repeat("xy", 100) + "Z" - readLimit := maxJobSummaryBytes + base64.StdEncoding.EncodedLen(len(longSecret)) + 1 + readLimit := protocol.MaxStepSummarySize + base64.StdEncoding.EncodedLen(len(longSecret)) + 1 shrinkingPrefix := strings.Repeat(longSecret, (readLimit-len(longSecret)+1)/len(longSecret)) for name, testcase := range map[string]struct { - encoding encoding.Encoding content, want string masks []string }{ - "UTF-8": {unicode.UTF8, content, want, nil}, - "UTF-8 BOM": {unicode.UTF8BOM, content, want, nil}, - "UTF-16LE BOM": {unicode.UTF16(unicode.LittleEndian, unicode.UseBOM), content, want, nil}, - "UTF-16BE BOM": {unicode.UTF16(unicode.BigEndian, unicode.UseBOM), content, want, nil}, - "secret split by the read": {unicode.UTF8, strings.Repeat("s3cr3t", maxJobSummaryBytes/3), "", nil}, + "mask before truncation": {content, want, nil}, + "secret split by the read": {strings.Repeat("s3cr3t", protocol.MaxStepSummarySize/3), "", nil}, "split read keeps every masked secret before the limit": { - unicode.UTF8, "# public\n" + strings.Repeat(longSecret, readLimit/len(longSecret)+1), - "# public\n" + strings.Repeat("***", (maxJobSummaryBytes-len("# public\n"))/len(longSecret)) + jobSummaryTruncationMarker, + "# public\n" + strings.Repeat("***", (protocol.MaxStepSummarySize-len("# public\n"))/len(longSecret)) + jobSummaryTruncationMarker, []string{longSecret}, }, "nested secret expands the split tail": { - unicode.UTF8, shrinkingPrefix + strings.Repeat("*", readLimit-len(shrinkingPrefix)-len(longSecret)+1) + longSecret, "", []string{"xy", longSecret}, }, } { t.Run(name, func(t *testing.T) { - var got string - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - body, err := io.ReadAll(r.Body) - assert.NoError(t, err) - got = string(body) - w.WriteHeader(http.StatusNoContent) - })) - defer server.Close() - - content, err := testcase.encoding.NewEncoder().String(testcase.content) - require.NoError(t, err) - cm := &containerMock{} - cm.On("GetContainerArchive", mock.Anything, "/var/run/act/workflow/step-summary-0.md").Return( - io.NopCloser(bytes.NewReader(tarArchive(t, tarEntry{ - name: "step-summary-0.md", body: content, - }))), - nil, - ).Once() - - rc := newJobSummaryRC(map[string]string{ - "GITEA_ACTIONS_CAPABILITIES": "job-summary", - "ACTIONS_RUNTIME_URL": server.URL, - "ACTIONS_RUNTIME_TOKEN": fakeRuntimeToken(34), - "GITEA_RUN_ID": "12", - }, cm, 1) - rc.Config.Secrets = map[string]string{"TOK": "s3cr3t", "ACTIONS_STEP_DEBUG": "true"} - rc.Config.ExtraMasks = append([]string{"pr0xypw"}, testcase.masks...) - rc.Masks = []string{"runtime-added"} - - tryUploadJobSummary(t.Context(), rc) - + summaryPath := container.JoinPath(t.TempDir(), "summary.md") + require.NoError(t, os.WriteFile(summaryPath, []byte(testcase.content), 0o600)) + rc := &RunContext{ + Config: &Config{ + Secrets: map[string]string{"TOK": "s3cr3t", "ACTIONS_STEP_DEBUG": "true"}, + ExtraMasks: append([]string{"pr0xypw"}, testcase.masks...), + }, + JobContainer: &container.HostEnvironment{}, + Masks: []string{"runtime-added"}, + } + got := string(readStepSummary(t.Context(), rc, summaryPath)) if testcase.want == "" { assert.Equal(t, jobSummaryTruncationMarker, strings.TrimLeft(got, "*")) } else { assert.Equal(t, testcase.want, got) } - cm.AssertExpectations(t) }) } } diff --git a/act/runner/max_parallel_test.go b/act/runner/max_parallel_test.go index 7c667e7d..90243bca 100644 --- a/act/runner/max_parallel_test.go +++ b/act/runner/max_parallel_test.go @@ -10,31 +10,11 @@ import ( "gitea.dev/actionslib/pkg/model" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "go.yaml.in/yaml/v4" ) func TestMaxParallelStrategy(t *testing.T) { - for _, tt := range []struct { - name string - maxParallelString string - expectedMaxParallel int - }{ - {"max-parallel-1", "1", 1}, - {"max-parallel-2", "2", 2}, - {"max-parallel-default", "", 4}, - {"max-parallel-10-clamped-to-combinations", "10", 5}, - {"max-parallel-invalid-falls-back-to-default", "tow", 4}, - } { - t.Run(tt.name, func(t *testing.T) { - var rawMatrix yaml.Node - require.NoError(t, rawMatrix.Encode(map[string][]any{"version": {1, 2, 3, 4, 5}})) - job := &model.Job{Strategy: &model.Strategy{MaxParallelString: tt.maxParallelString, RawMatrix: rawMatrix}} - - matrixes, err := job.GetMatrixes() - require.NoError(t, err) - require.Len(t, matrixes, 5) - assert.Equal(t, tt.expectedMaxParallel, maxParallelFor(job.Strategy, len(matrixes))) - }) + for limit, want := range map[string]int{"1": 1, "": 4, "10": 5, "tow": 4} { + assert.Equal(t, want, maxParallelFor(&model.Strategy{MaxParallelString: limit}, 5), limit) } t.Run("deferred strategy", func(t *testing.T) { @@ -59,29 +39,20 @@ jobs: } func TestNewPlanExecutorInvalidMatrix(t *testing.T) { - var rawMatrix yaml.Node - require.NoError(t, rawMatrix.Encode(map[string]any{ - "config": map[string]any{"nested": "value"}, - })) - - plan := &model.Plan{Stages: []*model.Stage{{Runs: []*model.Run{{ - Workflow: &model.Workflow{Jobs: map[string]*model.Job{ - "test": {Strategy: &model.Strategy{RawMatrix: rawMatrix}}, - }}, - JobID: "test", - }}}}} runner := &runnerImpl{config: &Config{Env: testCheckoutEnv()}} - - require.ErrorContains(t, runner.NewPlanExecutor(plan)(t.Context()), "could not get job matrix:") - - for _, strategy := range []string{ - `${{ fromJSON('invalid') }}`, - `${{ '${{ inputs.unresolved }}' }}`, + for strategy, want := range map[string]string{ + `{matrix: {config: {nested: value}}}`: "could not get job matrix:", + `${{ fromJSON('invalid') }}`: "job strategy", + `${{ '${{ inputs.unresolved }}' }}`: "job strategy", + `{matrix: {x: [a, "${{ fromJSON('not json') }}"]}}`: "Error when evaluating 'strategy' for job 'job1'.", } { t.Run(strategy, func(t *testing.T) { - workflow, err := model.ReadWorkflow(strings.NewReader("jobs:\n test:\n strategy: " + strategy)) + workflow, err := model.ReadWorkflow(strings.NewReader("jobs:\n job1:\n strategy: " + strategy)) require.NoError(t, err) - require.Error(t, runner.NewPlanExecutor(&model.Plan{Stages: []*model.Stage{{Runs: []*model.Run{{Workflow: workflow, JobID: "test"}}}}})(t.Context())) + plan, err := model.CombineWorkflowPlanner(workflow).PlanAll() + require.NoError(t, err) + require.ErrorContains(t, runner.NewPlanExecutor(plan)(t.Context()), want) + assert.Equal(t, "failure", workflow.Jobs["job1"].Result) }) } } diff --git a/act/runner/reusable_workflow.go b/act/runner/reusable_workflow.go index 691a91ea..dcee860b 100644 --- a/act/runner/reusable_workflow.go +++ b/act/runner/reusable_workflow.go @@ -5,197 +5,152 @@ package runner import ( + "cmp" "context" "fmt" "net/url" - "path" + "os" + "path/filepath" "regexp" "gitea.com/gitea/runner/act/common" "gitea.com/gitea/runner/act/common/git" + "gitea.dev/actionslib/pkg/expreval" + "gitea.dev/actionslib/pkg/exprparser" "gitea.dev/actionslib/pkg/model" ) -func newLocalReusableWorkflowExecutor(rc *RunContext) common.Executor { - localWorkflow, err := model.ParseReusableWorkflowUses(rc.Run.Job().Uses) - if err != nil { - return common.NewErrorExecutor(err) - } - - preset := rc.Config.PresetGitHubContext - if preset == nil { - // resolve the local workflow against the workspace root, not the process - // working directory, so it is found regardless of where the runner is invoked - return newReusableWorkflowExecutor(rc, rc.Config.Workdir, localWorkflow.Path, false) - } - - uses := fmt.Sprintf("%s/%s@%s", preset.Repository, localWorkflow.Path, preset.Sha) - - remoteReusableWorkflow, err := newRemoteReusableWorkflow(rc.Config.GitHubInstance, uses) - if err != nil { - return common.NewErrorExecutor(err) - } - - workflowDir := fmt.Sprintf("%s/%s", rc.ActionCacheDir(), safeFilename(uses)) - - return common.NewPipelineExecutor( - cloneRemoteReusableWorkflow(rc, remoteReusableWorkflow.CloneURL(), remoteReusableWorkflow.Ref, workflowDir), - newReusableWorkflowExecutor(rc, workflowDir, remoteReusableWorkflow.Path, true), - ) -} - -func newRemoteReusableWorkflowExecutor(rc *RunContext) common.Executor { - remoteReusableWorkflow, err := newRemoteReusableWorkflow(rc.Config.GitHubInstance, rc.Run.Job().Uses) - if err != nil { - return common.NewErrorExecutor(err) - } - - // uses with safe filename makes the target directory look something like this {owner}-{repo}-.github-workflows-{filename}@{ref} - // instead we will just use {owner}-{repo}@{ref} as our target directory. This should also improve performance when we are using - // multiple reusable workflows from the same repository and ref since for each workflow we won't have to clone it again - filename := fmt.Sprintf("%s/%s@%s", remoteReusableWorkflow.Owner, remoteReusableWorkflow.Repo, remoteReusableWorkflow.Ref) - workflowDir := fmt.Sprintf("%s/%s", rc.ActionCacheDir(), safeFilename(filename)) - - return common.NewPipelineExecutor( - cloneRemoteReusableWorkflow(rc, remoteReusableWorkflow.CloneURL(), remoteReusableWorkflow.Ref, workflowDir), - newReusableWorkflowExecutor(rc, workflowDir, remoteReusableWorkflow.Path, true), - ) -} - -// cloneRemoteReusableWorkflow always invokes the clone executor — moving refs -// (branches, tags) must be re-resolved each run, matching GitHub Actions. -// -// Callers must not change remoteReusableWorkflow.URL, because: -// 1. Gitea doesn't support specifying GithubContext.ServerURL by the GITHUB_SERVER_URL env -// 2. Gitea has already full URL with rc.Config.GitHubInstance when calling newRemoteReusableWorkflow -// -// remoteReusableWorkflow.URL = rc.getGithubContext(ctx).ServerURL -func cloneRemoteReusableWorkflow(rc *RunContext, cloneURL, ref, targetDirectory string) common.Executor { - return func(ctx context.Context) error { - 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(rc.Config.withInstanceAuth(git.NewGitCloneExecutorInput{ - URL: interpolatedURL, - Ref: ref, - Dir: targetDirectory, - OfflineMode: rc.Config.ActionOfflineMode, - Depth: rc.Config.ActionCloneDepth, - }, rc.Config.GetToken()))(ctx) - } -} - -func newReusableWorkflowExecutor(rc *RunContext, directory, workflow string, cached bool) common.Executor { - return func(ctx context.Context) error { - planner, err := func() (model.WorkflowPlanner, error) { - if cached { - unlock, err := git.AcquireCloneLock(ctx, directory) - if err != nil { - return nil, err - } - defer unlock() - } - return model.NewWorkflowPlanner(path.Join(directory, workflow), true) - }() - if err != nil { - return err - } - - plan, err := planner.PlanEvent("workflow_call") - if err != nil { - return err - } - - runner, err := (&runnerImpl{ - config: rc.Config, - caller: &caller{ - runContext: rc, - reusedWorkflowJobResults: map[string]string{}, - }, - }).configure() - if err != nil { - return err - } - - return common.NewPipelineExecutor( // For Gitea - runner.NewPlanExecutor(plan), - setReusedWorkflowCallerResult(rc, runner), - )(ctx) - } -} - -type remoteReusableWorkflow struct { - *model.ReusableWorkflowUses - URL string -} - -func (r *remoteReusableWorkflow) CloneURL() string { - return fmt.Sprintf("%s/%s/%s", withHTTPS(r.URL), r.Owner, r.Repo) -} - var absoluteReusableWorkflowURLRegex = regexp.MustCompile(`^(https?://.*)/([^/]+/[^/]+/\.[^/]+/workflows/[^@]+@.*)$`) -// For Gitea -// newRemoteReusableWorkflow parses a remote `uses`, an absolute URL up to `{owner}/{repo}/.{git_platform}/workflows/` replaces baseURL -func newRemoteReusableWorkflow(baseURL, uses string) (*remoteReusableWorkflow, error) { +func (c *caller) loadReusableWorkflow(ctx context.Context, instance, uses string) (*model.Plan, error) { + rc := c.runContext if matches := absoluteReusableWorkflowURLRegex.FindStringSubmatch(uses); matches != nil { - baseURL, uses = matches[1], matches[2] + instance, uses = matches[1], matches[2] } - parsed, err := model.ParseReusableWorkflowUses(uses) + workflow, err := model.ParseReusableWorkflowUses(uses) if err != nil { return nil, err } - if parsed.IsLocal() { - return nil, fmt.Errorf("expected a remote reusable workflow, got %q", uses) + depth := 1 + for parent := rc.caller; parent != nil; parent = parent.runContext.caller { + depth++ } - return &remoteReusableWorkflow{ReusableWorkflowUses: parsed, URL: baseURL}, nil + if depth >= model.MaxWorkflowCallDepth { + return nil, fmt.Errorf("reusable workflow %q exceeds the limit of %d workflows including the root", workflow.Path, model.MaxWorkflowCallDepth) + } + + if rc.caller != nil { + c.checkout = rc.caller.checkout + } + cacheDir := "workflows" + if preset := rc.Config.PresetGitHubContext; workflow.IsLocal() && c.checkout.Dir == "" && preset != nil { + cacheDir = "local-workflows" // a same-repository checkout must never answer another repository's call unauthenticated + workflow, err = model.ParseReusableWorkflowUses(fmt.Sprintf("%s/%s@%s", preset.Repository, workflow.Path, preset.Sha)) + if err != nil { + return nil, err + } + } + if !workflow.IsLocal() { + cloneURL, err := rc.ExprEval.Interpolate(ctx, withHTTPS(instance)+"/"+workflow.Owner+"/"+workflow.Repo) + if err != nil { + return nil, fmt.Errorf("unable to interpolate the workflow clone URL: %w", err) + } + c.checkout = rc.Config.withInstanceAuth(git.NewGitCloneExecutorInput{ + URL: cloneURL, + Ref: workflow.Ref, + Dir: filepath.Join(rc.ActionCacheDir(), cacheDir, model.UsesHash(cloneURL+"@"+workflow.Ref), "git"), + }, rc.Config.GetToken()) + } + + if c.checkout.Dir != "" { + unlock, err := git.AcquireCloneLock(ctx, filepath.Dir(c.checkout.Dir)) + if err != nil { + return nil, err + } + defer unlock() + if err := git.NewGitCloneExecutor(c.checkout)(ctx); err != nil { + return nil, err + } + if !workflow.IsLocal() { + c.checkout.Ref, err = git.FindGitRevision(ctx, c.checkout.Dir) + if err != nil { + return nil, err + } + c.checkout.OfflineMode = true + } + } + file, err := os.Open(filepath.Join(cmp.Or(c.checkout.Dir, rc.Config.Workdir), workflow.Path)) + if err != nil { + return nil, err + } + defer file.Close() + planner, err := model.NewSingleWorkflowPlanner(filepath.Base(workflow.Path), file) + if err != nil { + return nil, err + } + return planner.PlanEvent("workflow_call") } -// For Gitea -func setReusedWorkflowCallerResult(rc *RunContext, runner *runnerImpl) common.Executor { - return func(ctx context.Context) error { - hasFailure := false - for _, result := range runner.caller.reusedWorkflowJobResults { - if result == "pending" { - return nil - } - if result == "failure" { - hasFailure = true - } +func (rc *RunContext) runReusableWorkflow(ctx context.Context) error { + call := &caller{runContext: rc} + plan, err := call.loadReusableWorkflow(ctx, rc.Config.GitHubInstance, rc.Run.Job().Uses) + if err == nil && len(plan.Stages) > 0 { + if err = call.resolveInputs(ctx, plan.Stages[0].Runs[0].Workflow); err == nil { + err = (&runnerImpl{config: rc.Config, eventJSON: rc.EventJSON, caller: call}).NewPlanExecutor(plan)(ctx) } - if err := setJobOutputs(ctx, rc); err != nil { // a bad output fails this job, as for ordinary jobs - common.Logger(ctx).Errorf("##[error]%s", EscapeCommandData(err.Error())) - hasFailure = true - } - - reusedWorkflowJobResult := "success" - reusedWorkflowJobResultMessage := "succeeded" - if hasFailure { - reusedWorkflowJobResult = "failure" - reusedWorkflowJobResultMessage = "failed" - } - - // Serialize this shared Job.Result write against the other matrix combos - // and setJobResult (same lockJob key). - unlock := lockJob(rc.Run.Job()) - rc.result(reusedWorkflowJobResult) - unlock() - - if rc.caller != nil { - rc.caller.setReusedWorkflowJobResult(rc.Run.JobID, reusedWorkflowJobResult) - } else { - common.Logger(ctx).With("jobResult", reusedWorkflowJobResult).Infof("Job %s", reusedWorkflowJobResultMessage) - } - - return nil } + call.finishWorkflowCall(ctx, err) + return cmp.Or(ctx.Err(), err) +} + +func (c *caller) finishWorkflowCall(ctx context.Context, planErr error) { + rc := c.runContext + config := c.workflowCallConfig + var jobs map[string]*model.WorkflowCallResult + if config != nil && len(config.Outputs) > 0 && (planErr == nil || len(c.reportedRuns) > 0) { + jobs = make(map[string]*model.WorkflowCallResult, len(c.reportedRuns)) + } + failed := planErr != nil + for _, run := range c.reportedRuns { + if run == nil { + failed = true + continue + } + job := run.Job() + switch job.NeedsResult() { + case "failure": + failed = true + case "cancelled": + rc.markCancelled() + } + if jobs != nil { + jobs[run.JobID] = &model.WorkflowCallResult{Outputs: job.Outputs} + } + } + if jobs != nil { + interpreter := exprparser.NewInterpeter(&exprparser.EvaluationEnvironment{ + Github: rc.getGithubContext(ctx), + Vars: rc.Config.Vars, + Jobs: &jobs, + Inputs: c.inputs, + }, exprparser.Config{}) + outputs, err := expreval.New(interpreter.Evaluate).EvaluateWorkflowCallOutputs(config) // unlogged, the caller's log lacks the called jobs' masks + if err != nil { + common.Logger(ctx).Errorf("##[error]unable to interpolate workflow %s", EscapeCommandData(err.Error())) + failed = true + } else if len(rc.Matrix) == 0 || (!failed && !rc.jobCancelled) { + mergeJobOutputs(rc.Run.Job(), outputs) + } + } + rc.markJobInterrupted(ctx) + rc.setJobResult(ctx, !failed) } // For Gitea // withInstanceAuth passes instance credentials only to clones from this Gitea instance, and runner.insecure only to its registered address. func (c Config) withInstanceAuth(input git.NewGitCloneExecutorInput, token string) git.NewGitCloneExecutorInput { + input.Depth, input.OfflineMode = c.ActionCloneDepth, c.ActionOfflineMode u, err := url.Parse(input.URL) if err != nil || !onInstanceHost(u.Host, c.GitHubInstance, c.trustedActionInstance()) { return input diff --git a/act/runner/reusable_workflow_test.go b/act/runner/reusable_workflow_test.go index f2e4f08d..ec60c2bf 100644 --- a/act/runner/reusable_workflow_test.go +++ b/act/runner/reusable_workflow_test.go @@ -8,118 +8,95 @@ import ( "crypto/tls" "crypto/x509" "encoding/pem" + "fmt" "net/http" "net/http/httptest" "os" "os/exec" "path/filepath" "strings" - "sync" "testing" - "time" + "testing/synctest" + "gitea.com/gitea/runner/act/common" "gitea.com/gitea/runner/act/common/git" + "gitea.com/gitea/runner/act/common/logging" + "gitea.com/gitea/runner/act/common/logging/logtest" "gitea.dev/actionslib/pkg/model" "github.com/stretchr/testify/require" ) -// Regression test for go-gitea/gitea#37483: a remote reusable workflow at a moving -// ref (branch/tag) must reflect the new tip on every invocation, not stay pinned -// to the cache populated on the first run. -func TestReusableWorkflowCachedBranchRefRefreshes(t *testing.T) { - t.Parallel() - if _, err := exec.LookPath("git"); err != nil { - t.Skip("git not available in PATH") - } - +func TestReusableWorkflowCacheRefreshesBranchRefAndIsolatesSameRepoCalls(t *testing.T) { + requireHostTools(t, "git") remoteDir := t.TempDir() + const instance = "https://workflows.example" + const cloneURL = instance + "/org/repo" + t.Setenv("GIT_CONFIG_GLOBAL", filepath.Join(t.TempDir(), "gitconfig")) + gitMust(t, "", "config", "--global", "url."+remoteDir+".insteadOf", cloneURL) + gitMust(t, "", "config", "--global", "core.longpaths", "true") gitMust(t, "", "init", "--template=", "--initial-branch=master", remoteDir) const workflowPath = ".gitea/workflows/reusable.yml" - tmpl := func(tag string) string { - return "name: reusable\non:\n workflow_call:\njobs:\n build:\n runs-on: ubuntu-latest\n steps:\n - run: echo " + tag + "\n" - } - require.NoError(t, os.MkdirAll(filepath.Join(remoteDir, ".gitea/workflows"), 0o755)) - require.NoError(t, os.WriteFile(filepath.Join(remoteDir, workflowPath), []byte(tmpl("v1")), 0o644)) - gitMust(t, remoteDir, "add", workflowPath) - gitMust(t, remoteDir, "commit", "-m", "v1") - - rc := &RunContext{ - Config: &Config{Env: testCheckoutEnv()}, - Run: &model.Run{ - JobID: "j1", - Workflow: &model.Workflow{ - Name: "wf", - Jobs: map[string]*model.Job{"j1": {}}, - }, - }, + rc := workflowCaller(t, &Config{ActionCacheDir: t.TempDir(), PresetGitHubContext: &model.GithubContext{Repository: "root/project"}}, "./"+workflowPath) + commit := func(version string) *caller { + t.Helper() + require.NoError(t, os.WriteFile(filepath.Join(remoteDir, workflowPath), []byte(`on: + workflow_call: + outputs: {version: {value: "`+version+`@${{ github.repository }}"}} +jobs: + skip: {if: false, uses: ./unused.yml} +`), 0o644)) + gitMust(t, remoteDir, "add", workflowPath) + gitMust(t, remoteDir, "commit", "-m", version) + call := &caller{runContext: rc} + _, err := call.loadReusableWorkflow(t.Context(), instance, "org/repo/"+workflowPath+"@master") + require.NoError(t, err) + return call } - cacheDir := t.TempDir() - require.NoError(t, cloneRemoteReusableWorkflow(rc, remoteDir, "master", cacheDir)(t.Context())) - got, err := os.ReadFile(filepath.Join(cacheDir, workflowPath)) + first := commit("v1") + commit("v2") + cacheDir := filepath.Join(rc.ActionCacheDir(), "workflows", model.UsesHash(cloneURL+"@master")) + got, err := os.ReadFile(filepath.Join(cacheDir, "git", workflowPath)) require.NoError(t, err) - require.Equal(t, tmpl("v1"), string(got)) - - // Branch tip moves; cache key (cacheDir) does not. - require.NoError(t, os.WriteFile(filepath.Join(remoteDir, workflowPath), []byte(tmpl("v2")), 0o644)) - gitMust(t, remoteDir, "commit", "-am", "v2") - - require.NoError(t, cloneRemoteReusableWorkflow(rc, remoteDir, "master", cacheDir)(t.Context())) - got, err = os.ReadFile(filepath.Join(cacheDir, workflowPath)) + require.Contains(t, string(got), "v2@") + sameRepo := workflowCaller(t, &Config{ActionCacheDir: rc.ActionCacheDir(), PresetGitHubContext: &model.GithubContext{Repository: "org/repo", Sha: "master"}}, "./"+workflowPath) + sameRepoCall := &caller{runContext: sameRepo} + _, err = sameRepoCall.loadReusableWorkflow(t.Context(), instance, "./"+workflowPath) require.NoError(t, err) - require.Equal(t, tmpl("v2"), string(got), "cached workflow file must reflect the updated branch tip") -} + require.NotEqual(t, cacheDir, filepath.Dir(sameRepoCall.checkout.Dir)) -func TestNewReusableWorkflowExecutorHoldsCloneLock(t *testing.T) { - workflowDir := t.TempDir() - require.NoError(t, os.WriteFile(filepath.Join(workflowDir, "reusable.yml"), []byte("["), 0o644)) + require.NoError(t, os.RemoveAll(remoteDir)) + require.NoError(t, first.resolveInputs(t.Context(), rc.Run.Workflow)) + call := (&runnerImpl{config: rc.Config, caller: first}).NewPlanExecutor(&model.Plan{Stages: []*model.Stage{{Runs: []*model.Run{rc.Run}}}}) + require.NoError(t, call(t.Context())) + require.Equal(t, "v1@root/project", rc.Run.Job().Outputs["version"]) - unlock, err := git.AcquireCloneLock(t.Context(), workflowDir) - require.NoError(t, err) - unlockOnce := sync.OnceFunc(unlock) - defer unlockOnce() - - rc := &RunContext{ - Config: &Config{}, - Run: &model.Run{Workflow: &model.Workflow{Jobs: map[string]*model.Job{}}}, - } - exec := newReusableWorkflowExecutor(rc, workflowDir, "reusable.yml", true) - - done := make(chan error, 1) - go func() { done <- exec(context.Background()) }() - - select { - case err := <-done: - t.Fatalf("executor returned while clone lock was held: %v", err) - case <-time.After(50 * time.Millisecond): - } - - unlockOnce() - - select { - case err := <-done: - require.Error(t, err) - case <-time.After(time.Second): - t.Fatal("executor did not return after lock was released") - } + synctest.Test(t, func(t *testing.T) { + unlock, err := git.AcquireCloneLock(t.Context(), cacheDir) + require.NoError(t, err) + defer unlock() + ctx, cancel := context.WithCancel(t.Context()) + done := make(chan error, 1) + go func() { done <- call(ctx) }() + synctest.Wait() + cancel() + require.ErrorIs(t, <-done, context.Canceled) + require.Equal(t, "cancelled", rc.Run.Job().Result) + }) } func TestNewLocalReusableWorkflowExecutorFindsSameRepositoryPaths(t *testing.T) { - workdir := filepath.Join(t.TempDir(), "workspace") - require.NoError(t, os.MkdirAll(filepath.Join(workdir, ".gitea", "workflows"), 0o755)) - require.NoError(t, os.Mkdir(workdir+".lock", 0o755)) - require.NoError(t, os.WriteFile(filepath.Join(workdir, ".gitea", "workflows", "reusable.yml"), []byte("["), 0o644)) + workdir := t.TempDir() + require.NoError(t, os.MkdirAll(filepath.Join(workdir, ".gitea/workflows"), 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(workdir, ".gitea/workflows/reusable.yml"), []byte("on: workflow_call\njobs:\n skip: {if: false, uses: ./unused.yml}\n"), 0o644)) for _, uses := range []string{"./.gitea/workflows/reusable.yml", "$/.gitea/workflows/reusable.yml"} { - rc := &RunContext{ - Config: &Config{Workdir: workdir, NoSkipCheckout: true}, - Run: &model.Run{JobID: "job", Workflow: &model.Workflow{Jobs: map[string]*model.Job{"job": {Uses: uses}}}}, - } - err := newLocalReusableWorkflowExecutor(rc)(t.Context()) - require.ErrorContains(t, err, "workflow is not valid") + rc := workflowCaller(t, &Config{Workdir: workdir, Env: testCheckoutEnv()}, uses) + require.NoError(t, rc.runReusableWorkflow(t.Context())) + require.Equal(t, "success", rc.Run.Job().Result) } } @@ -141,19 +118,17 @@ func TestCloneRemoteReusableWorkflowSendsInstanceTokenAndClientCertTrustingCA(t certFile, keyFile := filepath.Join(dir, "client.crt"), filepath.Join(dir, "client.key") require.NoError(t, os.WriteFile(certFile, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: pair.Certificate[0]}), 0o600)) require.NoError(t, os.WriteFile(keyFile, pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: keyDER}), 0o600)) - rc := &RunContext{ - Config: &Config{ - Env: testCheckoutEnv(), - GitHubInstance: server.URL, - Secrets: map[string]string{"GITEA_TOKEN": "token"}, - ClientCertFile: certFile, - ClientKeyFile: keyFile, - CAFile: certFile, - }, - Run: &model.Run{JobID: "j1", Workflow: &model.Workflow{Jobs: map[string]*model.Job{"j1": {}}}}, - } + rc := workflowCaller(t, &Config{ + ActionCacheDir: t.TempDir(), + Env: testCheckoutEnv(), + GitHubInstance: server.URL, + Secrets: map[string]string{"GITEA_TOKEN": "token"}, + ClientCertFile: certFile, + ClientKeyFile: keyFile, + CAFile: certFile, + }, server.URL+"/owner/repo/.gitea/workflows/test.yml@main") - err = cloneRemoteReusableWorkflow(rc, server.URL+"/owner/repo", "main", t.TempDir())(t.Context()) + err = rc.runReusableWorkflow(t.Context()) require.Error(t, err) require.True(t, gotCert, "clone failed before receiving a client certificate: %v", err) require.Equal(t, "token", gotToken) @@ -176,6 +151,8 @@ func TestInstanceAuthAndTransportOnlyApplyToTheInstance(t *testing.T) { t.Run(tt.name, func(t *testing.T) { conf := Config{ GitHubInstance: tt.instanceURL, + ActionCloneDepth: 3, + ActionOfflineMode: true, DefaultActionInstance: tt.trustedActionInstance, DefaultActionInstanceIsSelfHosted: tt.trustedActionInstance != "", InsecureSkipTLS: true, @@ -184,7 +161,7 @@ func TestInstanceAuthAndTransportOnlyApplyToTheInstance(t *testing.T) { CAFile: "/ca", InstanceTransport: &http.Transport{}, } - want := git.NewGitCloneExecutorInput{URL: tt.cloneURL, InsecureSkipTLS: tt.insecure} + want := git.NewGitCloneExecutorInput{URL: tt.cloneURL, Depth: 3, OfflineMode: true, InsecureSkipTLS: tt.insecure} if tt.insecure { want.CAFile, want.Transport = conf.CAFile, conf.InstanceTransport } @@ -215,16 +192,69 @@ func gitMust(t *testing.T, dir string, args ...string) { require.NoError(t, err, "git %v: %s", args, string(out)) } -func TestSetReusedWorkflowCallerResultFailsOnBadOutputs(t *testing.T) { - callerWorkflow, err := model.ReadWorkflow(strings.NewReader("jobs:\n call: {uses: ./reuse.yml}\n")) +func workflowCaller(t *testing.T, config *Config, uses string) *RunContext { + t.Helper() + rc, err := (&runnerImpl{config: config}).newRunContext(t.Context(), &model.Run{ + JobID: "call", Workflow: &model.Workflow{Jobs: map[string]*model.Job{"call": {Uses: uses}}}, + }, nil) require.NoError(t, err) - called, err := model.ReadWorkflow(strings.NewReader("on:\n workflow_call:\n outputs:\n bad: {value: \"${{ fromJSON('not-json') }}\"}\njobs:\n inner: {uses: ./leaf.yml}\n")) - require.NoError(t, err) - config := &Config{PresetGitHubContext: &model.GithubContext{}} - parent, err := (&runnerImpl{config: config}).newRunContext(t.Context(), &model.Run{Workflow: callerWorkflow, JobID: "call"}, nil) - require.NoError(t, err) - rc, err := (&runnerImpl{config: config, caller: &caller{runContext: parent, reusedWorkflowJobResults: map[string]string{}}}).newRunContext(t.Context(), &model.Run{Workflow: called, JobID: "inner"}, nil) - require.NoError(t, err) - require.NoError(t, setReusedWorkflowCallerResult(rc, &runnerImpl{caller: &caller{reusedWorkflowJobResults: map[string]string{"leaf": "success"}}})(t.Context())) - require.Equal(t, "failure", rc.Run.Job().Result) + return rc +} + +func TestReusableWorkflowBadOutputFailsCallerAndKeepsLastNonemptyMatrixOutput(t *testing.T) { + workdir := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(workdir, "callee.yml"), []byte(`on: + workflow_call: + inputs: {value: {type: string}} + outputs: {result: {value: "${{ fromJSON(inputs.value) }}"}} +jobs: + skipped: {if: false, uses: ./unused.yml} +`), 0o644)) + root, err := model.ReadWorkflow(strings.NewReader(`on: push +jobs: + call: + strategy: {max-parallel: 1, matrix: {value: [bad, '"one"', '"two"', '""']}} + uses: ./callee.yml + with: {value: "${{ matrix.value }}"} +`)) + require.NoError(t, err) + plan, err := model.CombineWorkflowPlanner(root).PlanEvent("push") + require.NoError(t, err) + runner, err := New(&Config{Workdir: workdir, Env: testCheckoutEnv()}) + require.NoError(t, err) + require.ErrorContains(t, runner.NewPlanExecutor(plan)(t.Context()), "job 'call' failed") + require.Equal(t, "two", root.Jobs["call"].Outputs["result"]) +} + +func TestReusableWorkflowKeepsCompletedOutputsOnChildErrorWithoutLoggingThem(t *testing.T) { + workdir := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(workdir, "callee.yml"), []byte(`on: + workflow_call: + outputs: + result: {value: "${{ jobs.first.outputs.value }}"} + unrun: {value: "${{ jobs.third.outputs.value }}"} +jobs: + placeholder: {result: cancelled} + first: {runs-on: ubuntu-latest, outputs: {value: from-first}, steps: [{run: echo first}]} + second: {needs: first, runs-on: ubuntu-latest, container: {image: node, ports: [invalid]}, steps: [{run: echo second}]} + third: {needs: second, runs-on: ubuntu-latest, outputs: {value: from-third}, steps: [{run: echo third}]} +`), 0o644)) + rc := workflowCaller(t, &Config{Workdir: workdir, Env: testCheckoutEnv(), PlatformPicker: mapPlatformPicker(platforms)}, "./callee.yml") + hook := logtest.NewWithLevel(logging.LevelDebug) + ctx := common.WithLogger(common.WithDryrun(t.Context(), true), logging.New(hook)) + require.ErrorContains(t, rc.runReusableWorkflow(ctx), "failed to parse container ports") + require.Equal(t, "failure", rc.Run.Job().Result) + require.Equal(t, map[string]string{"result": "from-first"}, rc.Run.Job().Outputs) + for _, record := range hook.AllRecords() { + require.NotContains(t, record.Message, "from-first") + } +} + +func TestReusableWorkflowNestingLimit(t *testing.T) { + workdir := t.TempDir() + for level := 2; level <= model.MaxWorkflowCallDepth; level++ { + require.NoError(t, os.WriteFile(filepath.Join(workdir, fmt.Sprintf("%d.yml", level)), []byte(fmt.Sprintf("on: workflow_call\njobs:\n next: {uses: ./%d.yml}\n", level+1)), 0o644)) + } + rc := workflowCaller(t, &Config{Workdir: workdir, Env: testCheckoutEnv()}, "./2.yml") + require.ErrorContains(t, rc.runReusableWorkflow(t.Context()), fmt.Sprintf(`"%d.yml" exceeds the limit of %d`, model.MaxWorkflowCallDepth+1, model.MaxWorkflowCallDepth)) } diff --git a/act/runner/run_context.go b/act/runner/run_context.go index 77a38767..87fc6495 100644 --- a/act/runner/run_context.go +++ b/act/runner/run_context.go @@ -67,6 +67,7 @@ type RunContext struct { JobContainer container.ExecutionsEnvironment serviceContainers []*serviceContainer kubernetes bool + runsOn []string containerSpec model.ContainerSpec // container:, resolved once with platformImage containerEnv yaml.Node // container.env of the kept containerSpec, decoded once the job env resolves defaultEnv map[string]string // ImageOS and the runner CA's NODE_EXTRA_CA_CERTS, beneath any env the job sets @@ -78,8 +79,8 @@ type RunContext struct { cleanUpJobContainer common.Executor taskWorkspace string deferVolumeCleanup func(common.Executor) - caller *caller // job calling this RunContext (reusable workflows) - workflowCallInputs map[string]any // the caller's with:, resolved once by resolveWorkflowCall + caller *caller // job calling this RunContext (reusable workflows) + callerRunIndex int 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 @@ -99,6 +100,7 @@ type RunContext struct { // so writes from later phases and from composite sub-steps append to the same file. // Only populated on the top-level RunContext; child RCs walk Parent via topLevelRunContext. summaryFileInitialized map[int]bool + summaryUploads *stepSummaryUploads // jobCancelled records that this job's run was cancelled (context.Canceled). It makes // getJobContext report the "cancelled" status so cancelled()/always() evaluate the way // GitHub Actions does, letting cleanup and always() steps run while normal steps skip. @@ -158,20 +160,6 @@ func (rc *RunContext) markFailed() { rc.jobFailed = true } -// markInterrupted records the job's interruption status from a context error so later step `if` evaluations and the job result observe it, -// keeping the timeout path symmetric with the cancel path: -// - context.Canceled (server cancel) marks the job cancelled, matching GitHub's "only always()/cancelled() run on cancel". -// - context.DeadlineExceeded (job timeout-minutes) evaluates later steps as cancelled like GitHub, but reports the job failed. -func (rc *RunContext) markInterrupted(err error) { - switch { - case errors.Is(err, context.Canceled): - rc.markCancelled() - case errors.Is(err, context.DeadlineExceeded): - rc.jobTimedOut = true - rc.markFailed() - } -} - // AddMask also hands the mask to the job logger's extra handler, which receives records unmasked. func (rc *RunContext) AddMask(ctx context.Context, mask string) { rc.Masks = append(rc.Masks, mask) @@ -183,8 +171,6 @@ func (rc *RunContext) AddMask(ctx context.Context, mask string) { func (rc *RunContext) String() string { name := fmt.Sprintf("%s/%s", rc.Run.Workflow.Name, rc.Name) if rc.caller != nil { - // prefix the reusable workflow with the caller job - // this is required to create unique container names name = fmt.Sprintf("%s/%s", rc.caller.runContext.Name, name) } return name @@ -223,12 +209,8 @@ func (rc *RunContext) setActionEnv(env map[string]string) { } func (rc *RunContext) jobContainerName() string { - // The job id, never evaluated, keeps two jobs apart when masking collapses their names. - nameParts := []string{rc.Config.ContainerNamePrefix, "WORKFLOW-" + rc.Run.Workflow.Name, "JOB-" + rc.Run.JobID, rc.Name} - if rc.caller != nil { - nameParts = append(nameParts, "CALLED-BY-"+rc.caller.runContext.JobName) - } - return createContainerName(nameParts...) // For Gitea + job := rc.topLevelRunContext() + return createContainerName(job.Config.ContainerNamePrefix, "WORKFLOW-"+job.Run.Workflow.Name, "JOB-"+job.Run.JobID, job.Name, job.runnerTrackingID()) } // networkNameForGitea return the name of the network @@ -553,7 +535,7 @@ func (rc *RunContext) startKubernetesPod() common.Executor { } var options container.KubernetesOptions if rc.Config.KubernetesPicker != nil { - options = rc.Config.KubernetesPicker(rc.runsOnPlatformNames(ctx)) + options = rc.Config.KubernetesPicker(rc.runsOn) } options.MaxLifetime, options.ForcePull = rc.Config.ContainerMaxLifetime, rc.Config.ForcePull pod, err := container.NewKubernetesPod(options) @@ -671,7 +653,6 @@ func (rc *RunContext) startJobContainer() common.Executor { Name: name, Env: envList, NetworkMode: networkName, - NetworkAliases: []string{rc.Name}, ExposedPorts: exposedPorts, PortBindings: portBindings, Stdout: logWriter, @@ -1321,14 +1302,17 @@ func (rc *RunContext) interpolateOutputs() common.Executor { if err := model.DecodeEvaluated("job outputs", job.RawOutputs, rc.NewExpressionEvaluator(ctx).shared(ctx).EvaluateYamlNode, &outputs); err != nil { return err } - // Matrix combinations share the job, so as on GitHub a failure publishes nothing and the last non-empty value wins. - maps0.DeleteFunc(outputs, func(_, value string) bool { return value == "" }) - defer lockJob(job)() - job.Outputs = mergeMaps(job.Outputs, outputs) + mergeJobOutputs(job, outputs) return nil } } +func mergeJobOutputs(job *model.Job, outputs map[string]string) { + maps0.DeleteFunc(outputs, func(_name, value string) bool { return value == "" }) // The last non-empty value wins across matrix combinations. + defer lockJob(job)() + job.Outputs = mergeMaps(job.Outputs, outputs) +} + func (rc *RunContext) startContainer() common.Executor { return func(ctx context.Context) error { var err error @@ -1374,14 +1358,6 @@ func (rc *RunContext) closeContainer() common.Executor { } } -func (rc *RunContext) matrix() map[string]any { - return rc.Matrix -} - -func (rc *RunContext) result(result string) { - rc.Run.Job().Result = result -} - func (rc *RunContext) steps() []*model.Step { // Return per-job copies of the steps. Matrix combinations run in parallel and share the // workflow model, but step execution mutates per-job fields and evaluates the If/Env nodes @@ -1416,64 +1392,31 @@ func (rc *RunContext) Executor() (common.Executor, error) { switch jobType { case model.JobTypeDefault: executor = newJobExecutor(rc, &stepFactoryImpl{}, rc) - case model.JobTypeReusableWorkflowLocal: - executor = newLocalReusableWorkflowExecutor(rc) - case model.JobTypeReusableWorkflowRemote: - executor = newRemoteReusableWorkflowExecutor(rc) + case model.JobTypeReusableWorkflowLocal, model.JobTypeReusableWorkflowRemote: + executor = rc.runReusableWorkflow case model.JobTypeInvalid: return nil, err } return func(ctx context.Context) error { - res, err := rc.isEnabled(ctx) - if err != nil { - // Record the failure so a job that cannot start gets a stop time. rc.caller is only set for reusable workflows. - rc.result("failure") - if rc.caller != nil { // For Gitea - rc.caller.setReusedWorkflowJobResult(rc.Run.JobID, "failure") - } + if enabled, err := rc.isEnabled(ctx); !enabled { return err } - if res { - return executor(ctx) + jobCtx, cancel, err := applyJobTimeout(ctx, rc, rc.Run.Job()) + if err != nil { + common.Logger(ctx).Errorf("##[error]%s", EscapeCommandData(err.Error())) + rc.setJobResult(ctx, false) + return nil } - return nil + defer cancel() + err = executor(jobCtx) + if rc.jobCancelled { + return ctx.Err() // downstream jobs still evaluate their conditions after a job timeout + } + return err }, nil } -func (rc *RunContext) runsOnImage(ctx context.Context) (string, error) { - runsOn := rc.Run.Job().RunsOn() - for i, v := range runsOn { - 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 { - return rc.Config.PlatformPicker(runsOn), nil - } - return "", nil -} - -func (rc *RunContext) runsOnPlatformNames(ctx context.Context) []string { - job := rc.Run.Job() - - if job.RunsOn() == nil { - return []string{} - } - - // Evaluate a copy: RawRunsOn is shared across parallel matrix jobs, so interpolating it in - // place would race and leak one matrix combination's runs-on into the others. - rawRunsOn := model.CloneYamlNode(job.RawRunsOn) - if err := rc.ExprEval.EvaluateYamlNode(ctx, &rawRunsOn); err != nil { - common.Logger(ctx).Errorf("Error while evaluating runs-on: %v", err) - return []string{} - } - - return model.RunsOnFromNode(rawRunsOn) -} - // resolvePlatformImage evaluates the job's container once for every consumer, skipping one whose image is empty as GitHub does. func (rc *RunContext) resolvePlatformImage(ctx context.Context) error { rc.jobEnv, _ = evaluateJobEnv(ctx, rc) // a broken env fails the job at setup instead @@ -1486,9 +1429,14 @@ func (rc *RunContext) resolvePlatformImage(ctx context.Context) error { if spec.Image != "" || imagelessContainer(withoutEnv) { rc.containerSpec, rc.containerEnv = spec, env } - image, err := rc.runsOnImage(ctx) - if err != nil { - return err + runsOn := model.CloneYamlNode(rc.Run.Job().RawRunsOn) + if err := rc.ExprEval.EvaluateYamlNode(ctx, &runsOn); err != nil { + return fmt.Errorf("unable to evaluate runs-on: %w", err) + } + rc.runsOn = model.RunsOnFromNode(runsOn) + var image string + if rc.Config.PlatformPicker != nil { + image = rc.Config.PlatformPicker(rc.runsOn) } image, rc.kubernetes = strings.CutPrefix(image, "kubernetes://") rc.platformImage = cmp.Or(rc.containerSpec.Image, image) @@ -1533,39 +1481,38 @@ func (rc *RunContext) isEnabled(ctx context.Context) (bool, error) { job := rc.Run.Job() l := common.Logger(ctx) runJob, runJobErr := EvalBool(ctx, rc.ExprEval, job.If.Value, exprparser.DefaultStatusCheckSuccess) - jobType, jobTypeErr := job.Type() - if runJobErr != nil { l.Errorf("Error when evaluating 'if' for job '%s'. %v", rc.Run.JobID, runJobErr) } - if jobType == model.JobTypeInvalid { - return false, jobTypeErr - } - - if !runJob { - if rc.caller != nil { // For Gitea - rc.caller.setReusedWorkflowJobResult(rc.Run.JobID, "skipped") - return false, nil + if runJob { + if job.Uses != "" { + return true, nil } - l.With("jobResult", "skipped").Debugf("Skipping job '%s' due to '%s'", job.Name, job.If.Value) - return false, nil - } - - if jobType != model.JobTypeDefault { - return true, nil - } - - if err := rc.resolvePlatformImage(ctx); err != nil { - return false, err - } - if rc.platformImage == "" { - for _, platformName := range rc.runsOnPlatformNames(ctx) { + if err := rc.resolvePlatformImage(ctx); err != nil { + rc.setJobResult(ctx, false) + return false, err + } + if rc.platformImage != "" { + return true, nil + } + for _, platformName := range rc.runsOn { l.Infof("Skipping unsupported platform -- Try running with `-P %+v=...`", platformName) } - return false, nil + if len(job.Steps) == 0 { // Gitea's needs placeholders carry the result from the server + return false, nil + } + } else if rc.caller == nil { + l.With("jobResult", "skipped").Debugf("Skipping job '%s' due to '%s'", job.Name, job.If.Value) } - return true, nil + defer lockJob(job)() + if rc.jobTotal == 1 || job.Result == "" { + job.Result = "skipped" + } + if rc.caller != nil { + rc.caller.reportedRuns[rc.callerRunIndex] = rc.Run + } + return false, nil } // proxyBuildArgs returns the job's proxy variables as docker build args. The docker CLI @@ -1681,8 +1628,11 @@ func (rc *RunContext) getGithubContext(ctx context.Context) *model.GithubContext ghc := &model.GithubContext{ Event: make(map[string]any), Workflow: rc.Run.Workflow.Name, + WorkflowRef: rc.Config.Env["GITHUB_WORKFLOW_REF"], + WorkflowSha: rc.Config.Env["GITHUB_WORKFLOW_SHA"], RunID: cmp.Or(rc.Config.Env["GITHUB_RUN_ID"], "1"), RunNumber: cmp.Or(rc.Config.Env["GITHUB_RUN_NUMBER"], "1"), + RunAttempt: cmp.Or(rc.Config.Env["GITHUB_RUN_ATTEMPT"], "1"), Actor: cmp.Or(rc.Config.Actor, "nektos/act"), // for configs that require a default rather than being run as a cmd EventName: rc.Config.EventName, Action: rc.CurrentStep, diff --git a/act/runner/run_context_test.go b/act/runner/run_context_test.go index 363871ff..f777a685 100644 --- a/act/runner/run_context_test.go +++ b/act/runner/run_context_test.go @@ -330,6 +330,7 @@ jobs: redis, job := inputs[0], inputs[1] require.Equal(t, "redis:latest", redis.Image) + require.Empty(t, job.NetworkAliases) require.Equal(t, map[string]string{"data": "/data"}, redis.Mounts) require.Equal(t, []string{"TITLE=${{ github.job }}"}, redis.Env) require.Equal(t, "${{ github.job }}", redis.Password) @@ -358,6 +359,7 @@ jobs: env: {TEXT: "${{ env.TEXT }}"} options: --volumes-from ${{ env.JOB_CONTAINER_NAME }} `, &Config{Vars: map[string]string{"REG_USER": "user", "TEXT": "${{ 'literal' }}"}}) + require.NotEqual(t, job.Name, inputs[1].Name) redis, job = inputs[0], inputs[1] require.Equal(t, "user", job.Username) require.Equal(t, "8080", job.PortBindings["80/tcp"][0].HostPort) @@ -969,7 +971,10 @@ func TestGetGitHubContext(t *testing.T) { EventName: "push", Workdir: cwd, Env: map[string]string{ - "GITHUB_REPOSITORY": "nektos/act", + "GITHUB_REPOSITORY": "nektos/act", + "GITHUB_RUN_ATTEMPT": "2", + "GITHUB_WORKFLOW_REF": "owner/repo/.github/workflows/build.yml@refs/heads/main", + "GITHUB_WORKFLOW_SHA": "local-workflow-sha", }, }, Run: &model.Run{ @@ -1006,6 +1011,9 @@ func TestGetGitHubContext(t *testing.T) { assert.Equal(t, "1", ghc.RunID) assert.Equal(t, "1", ghc.RunNumber) + assert.Equal(t, "2", ghc.RunAttempt) + assert.Equal(t, rc.Config.Env["GITHUB_WORKFLOW_REF"], ghc.WorkflowRef) + assert.Equal(t, "local-workflow-sha", ghc.WorkflowSha) assert.Equal(t, "0", ghc.RetentionDays) assert.Equal(t, actor, ghc.Actor) assert.Equal(t, repo, ghc.Repository) @@ -1144,7 +1152,7 @@ func createJob(t *testing.T, input, result string) *model.Job { return job } -func TestRunContextRunsOnPlatformNames(t *testing.T) { +func TestResolvePlatformImagePassesEvaluatedRunsOnLabelsToPicker(t *testing.T) { for _, testcase := range []struct { job string want []string @@ -1153,14 +1161,18 @@ func TestRunContextRunsOnPlatformNames(t *testing.T) { {"runs-on: ${{ 'ubuntu-latest' }}", []string{"ubuntu-latest"}}, {"runs-on: [self-hosted, my-runner]", []string{"self-hosted", "my-runner"}}, {`runs-on: [self-hosted, "${{ 'my-runner' }}"]`, []string{"self-hosted", "my-runner"}}, - {`runs-on: ${{ fromJSON('["ubuntu-latest"]') }}`, []string{"ubuntu-latest"}}, - {"name: something", []string{}}, - {"runs-on: {mapping: value}", []string{}}, - {"runs-on: ${{ invalid expression }}", []string{}}, + {`runs-on: ${{ fromJSON('["self-hosted","my-runner"]') }}`, []string{"self-hosted", "my-runner"}}, + {"name: something", nil}, + {"runs-on: {mapping: value}", nil}, } { t.Run(testcase.job, func(t *testing.T) { - rc := createIfTestRunContext(map[string]*model.Job{"job1": createJob(t, testcase.job, "")}) - assert.Equal(t, testcase.want, rc.runsOnPlatformNames(t.Context())) + rc := makeTestRC(t, testcase.job) + rc.Config.PlatformPicker = func(labels []string) string { + assert.Equal(t, testcase.want, labels) + return "ubuntu-latest" + } + require.NoError(t, rc.resolvePlatformImage(t.Context())) + assert.Equal(t, "ubuntu-latest", rc.platformImage) }) } } diff --git a/act/runner/runner.go b/act/runner/runner.go index 6ede6459..f552a132 100644 --- a/act/runner/runner.go +++ b/act/runner/runner.go @@ -16,6 +16,7 @@ import ( "time" "gitea.com/gitea/runner/act/common" + "gitea.com/gitea/runner/act/common/git" "gitea.com/gitea/runner/act/common/logging" "gitea.com/gitea/runner/act/container" "gitea.com/gitea/runner/act/ghcontext" @@ -117,10 +118,11 @@ func (c Config) DefaultActionURL() string { } type caller struct { - runContext *RunContext - - updateResultLock sync.Mutex // For Gitea - reusedWorkflowJobResults map[string]string // For Gitea + runContext *RunContext + checkout git.NewGitCloneExecutorInput + workflowCallConfig *model.WorkflowCall + inputs map[string]any + reportedRuns []*model.Run } type runnerImpl struct { @@ -216,6 +218,10 @@ func (runner *runnerImpl) NewPlanExecutor(plan *model.Plan) common.Executor { logging.Debugf("Job.With: %v", job.With) logging.Debugf("Job.Result: %v", job.Result) + failStrategy := func(err error) error { + job.Result = "failure" + return fmt.Errorf("Error when evaluating 'strategy' for job '%s'. %w", run.JobID, err) + } if job.Strategy != nil || job.RawStrategy.Kind == yaml.ScalarNode { strategyRc, err := runner.newRunContext(ctx, run, nil) if err != nil { @@ -223,28 +229,29 @@ func (runner *runnerImpl) NewPlanExecutor(plan *model.Plan) common.Executor { } if job.RawStrategy.Kind == yaml.ScalarNode { if err := model.DecodeEvaluated("job strategy", job.RawStrategy, strategyRc.ExprEval.shared(ctx).EvaluateYamlNode, &job.Strategy); err != nil { - return err + return failStrategy(err) } } else { logging.Debugf("Job.Strategy.FailFast: %v", job.Strategy.GetFailFast()) logging.Debugf("Job.Strategy.FailFastString: %v", job.Strategy.FailFastString) logging.Debugf("Job.Strategy.MaxParallelString: %v", job.Strategy.MaxParallelString) logging.Debugf("Job.Strategy.RawMatrix: %v", job.Strategy.RawMatrix) - // An unevaluated expression is left in place, which GetMatrixes below rejects. - if err := strategyRc.NewExpressionEvaluator(ctx).EvaluateYamlNode(ctx, &job.Strategy.RawMatrix); err != nil { - logging.Errorf("Error while evaluating matrix: %v", err) + if err := strategyRc.ExprEval.EvaluateYamlNode(ctx, &job.Strategy.RawMatrix); err != nil { + return failStrategy(err) } for _, value := range []*string{&job.Strategy.FailFastString, &job.Strategy.MaxParallelString} { - if evaluated, err := strategyRc.ExprEval.Interpolate(ctx, *value); err == nil { - *value = evaluated + evaluated, err := strategyRc.ExprEval.Interpolate(ctx, *value) + if err != nil { + return failStrategy(err) } + *value = evaluated } } } matrixes, err := job.GetMatrixes() if err != nil { - return fmt.Errorf("could not get job matrix: %w", err) + return failStrategy(fmt.Errorf("could not get job matrix: %w", err)) } logging.Debugf("Job Matrices: %v", matrixes) @@ -252,6 +259,7 @@ func (runner *runnerImpl) NewPlanExecutor(plan *model.Plan) common.Executor { logging.Infof("Running job with maxParallel=%d for %d matrix combinations", maxParallel, len(matrixes)) + var callerRunIndex int for i, matrix := range matrixes { index, total := i, len(matrixes) if runner.caller == nil && runner.config.PresetGitHubContext != nil && len(matrix) > 0 { @@ -271,20 +279,19 @@ func (runner *runnerImpl) NewPlanExecutor(plan *model.Plan) common.Executor { rc.Name = fmt.Sprintf("%s-%d", rc.Name, i+1) } maxJobNameLen = max(maxJobNameLen, len(rc.String())) - if rc.caller != nil { // For Gitea - rc.caller.setReusedWorkflowJobResult(rc.Run.JobID, "pending") + if i == 0 && runner.caller != nil { + callerRunIndex = len(runner.caller.reportedRuns) + runner.caller.reportedRuns = append(runner.caller.reportedRuns, nil) } + rc.callerRunIndex = callerRunIndex stageExecutor = append(stageExecutor, func(ctx context.Context) error { - jobName := fmt.Sprintf("%-*s", maxJobNameLen, rc.String()) executor, err := rc.Executor() if err != nil { return err } - jobCtx := common.WithJobErrorContainer(WithJobLogger(ctx, rc.Run.JobID, jobName, rc.Config, &rc.Masks, matrix)) - jobCtx, cancelTimeout := applyJobTimeout(jobCtx, rc, job) - defer cancelTimeout() - return executor(jobCtx) + ctx = WithJobLogger(ctx, rc.Run.JobID, fmt.Sprintf("%-*s", maxJobNameLen, rc.String()), rc.Config, &rc.Masks, matrix) + return executor(common.WithJobErrorContainer(ctx)) }) } // Run all matrix combinations of this job, then drop its aggregation mutex: the @@ -336,15 +343,20 @@ func (runner *runnerImpl) NewPlanExecutor(plan *model.Plan) common.Executor { } func handleFailure(plan *model.Plan) common.Executor { - return func(ctx context.Context) error { + return func(_ctx context.Context) error { + var failure error for _, stage := range plan.Stages { for _, run := range stage.Runs { - if run.Job().Result == "failure" && !run.Job().ContinueOnError { - return fmt.Errorf("job '%s' failed", run.String()) + job := run.Job() + if job.Result == "cancelled" && (len(job.Steps) > 0 || job.Uses != "") { + return jobTimeoutCancellation{} + } + if failure == nil && job.NeedsResult() == "failure" { + failure = fmt.Errorf("job '%s' failed", run.String()) } } } - return nil + return failure } } @@ -379,11 +391,3 @@ func (runner *runnerImpl) newCombinationRunContext(ctx context.Context, run *mod return rc, nil } - -// For Gitea -// Keyed by job id, not name: only the values are read, and masking can collapse two names into one. -func (c *caller) setReusedWorkflowJobResult(jobID, result string) { - c.updateResultLock.Lock() - defer c.updateResultLock.Unlock() - c.reusedWorkflowJobResults[jobID] = result -} diff --git a/act/runner/runner_test.go b/act/runner/runner_test.go index 40a040ea..eda483bd 100644 --- a/act/runner/runner_test.go +++ b/act/runner/runner_test.go @@ -7,7 +7,6 @@ package runner import ( "bytes" "context" - "crypto/rand" "fmt" "os" "path/filepath" @@ -15,10 +14,13 @@ import ( "strings" "sync" "testing" + "testing/synctest" "time" "gitea.com/gitea/runner/act/common" "gitea.com/gitea/runner/act/common/logging" + "gitea.com/gitea/runner/act/common/logging/logtest" + "gitea.com/gitea/runner/act/container" "gitea.com/gitea/runner/act/ghcontext" "gitea.dev/actionslib/pkg/model" @@ -33,7 +35,6 @@ var ( logLevel = logging.LevelDebug workdir = "testdata" secrets map[string]string - testRunID = strings.ToLower(rand.Text()[:8]) // keeps docker names apart from concurrent test processes on one daemon testCheckoutPins sync.Map ) @@ -170,6 +171,51 @@ func TestNewPlanExecutorRequiresRunsOnBeforeRunningAnyJob(t *testing.T) { assert.Equal(t, "success", workflow.Jobs["build"].Result) } +func TestLocalPlanContinuesAfterCancellationAndInvalidJobTimeout(t *testing.T) { + workflow, err := model.ReadWorkflow(strings.NewReader(` +jobs: + upstream: {} + timed: {needs: upstream, if: always(), runs-on: ubuntu-latest, timeout-minutes: 1, steps: [run: exit 1]} + skipped: + needs: timed + runs-on: ubuntu-latest + timeout-minutes: ${{ fromJSON('invalid') }} + steps: [run: exit 1] + unsupported: {needs: timed, if: always(), runs-on: unknown, steps: [run: exit 1]} + invalid: + needs: timed + if: always() + runs-on: ubuntu-latest + timeout-minutes: ${{ fromJSON('"abc"') }} + steps: [run: exit 1] + downstream: {needs: invalid, runs-on: ubuntu-latest, steps: [run: exit 1]} +`)) + require.NoError(t, err) + workflow.Jobs["upstream"].Result = "failure" + plan, err := model.CombineWorkflowPlanner(workflow).PlanAll() + require.NoError(t, err) + slow := &containerMock{} + slow.On("Pull", false).Return(func(ctx context.Context) error { + <-ctx.Done() + return ctx.Err() + }) + slow.On("Remove").Return(noopExecutor) + slow.On("Close").Return(noopExecutor) + original := newContainer + newContainer = func(_input *container.NewContainerInput) container.ExecutionsEnvironment { return slow } + t.Cleanup(func() { newContainer = original }) + runner := &runnerImpl{config: &Config{Env: testCheckoutEnv(), PlatformPicker: mapPlatformPicker(platforms)}} + hook := logtest.NewWithLevel(logging.LevelError) + synctest.Test(t, func(t *testing.T) { + ctx := common.WithLoggerHandler(common.WithDryrun(t.Context(), true), hook) + require.ErrorIs(t, runner.NewPlanExecutor(plan)(ctx), context.Canceled) + }) + for jobID, want := range map[string]string{"timed": "cancelled", "skipped": "skipped", "unsupported": "skipped", "invalid": "failure", "downstream": "skipped"} { + assert.Equal(t, want, workflow.Jobs[jobID].Result, jobID) + } + assert.Contains(t, hook.LastRecord().Message, "Error when evaluating 'timeout-minutes' for job 'invalid'. Unexpected value 'abc'") +} + func TestGraphEvent(t *testing.T) { planner, err := model.NewWorkflowPlanner("testdata/basic", true) assert.NoError(t, err) //nolint:testifylint // pre-existing issue from nektos/act @@ -237,8 +283,6 @@ func (j *TestJobFileInfo) runTest(ctx context.Context, t *testing.T, cfg *Config EventName: j.eventName, EventPath: cfg.EventPath, PlatformPicker: mapPlatformPicker(j.platforms), - // fixtures reuse workflow and job names, so parallel tests would collide without this - ContainerNamePrefix: strings.ReplaceAll(t.Name(), "/", "-") + "-" + testRunID, // 0 would run jobs runtime.NumCPU()-wide, making the network peak machine-dependent MaxParallel: 2, Env: cfg.Env, @@ -367,7 +411,7 @@ func TestRunEvent(t *testing.T) { config := &Config{ Secrets: table.secrets, - Env: map[string]string{"GITHUB_REPOSITORY": t.Name() + "-" + testRunID}, + Env: map[string]string{"GITHUB_REPOSITORY": t.Name()}, } eventFile := filepath.Join(workdir, table.workflowPath, "event.json") diff --git a/act/runner/step.go b/act/runner/step.go index 44fd9ffd..e7c33785 100644 --- a/act/runner/step.go +++ b/act/runner/step.go @@ -5,6 +5,7 @@ package runner import ( + "cmp" "context" "fmt" maps0 "maps" @@ -163,7 +164,8 @@ func runStepExecutor(step step, stage stepStage, executor common.Executor) commo topRC := rc.topLevelRunContext() stepSummaryIndex := topRC.CurrentStepIndex summaryFileCommand := path.Join("workflow", "step-summary-"+strconv.Itoa(stepSummaryIndex)+".md") - (*step.getEnv())["GITHUB_STEP_SUMMARY"] = container.JoinPath(actPath, summaryFileCommand) + summaryPath := container.JoinPath(actPath, summaryFileCommand) + (*step.getEnv())["GITHUB_STEP_SUMMARY"] = summaryPath aliasGiteaEnv(*step.getEnv()) // Reset the per-phase file-command files. GITHUB_STEP_SUMMARY is intentionally @@ -188,11 +190,12 @@ func runStepExecutor(step step, stage stepStage, executor common.Executor) commo fileCommandInitErr = rc.JobContainer.Copy(actPath, files...)(ctx) // a broken summary must not block the resets } - timeoutctx, cancelTimeOut := evaluateStepTimeout(ctx, step) - defer cancelTimeOut() + timeoutCtx, cancelTimeout := evaluateStepTimeout(ctx, step, stage, stepString) + defer cancelTimeout() err = fileCommandInitErr if err == nil { - err = rc.runWithCommands(timeoutctx, *step.getEnv(), executor) + err = rc.runWithCommands(timeoutCtx, *step.getEnv(), executor) + err = cmp.Or(context.Cause(timeoutCtx), err) } fileCommandCtx := ctx if ctx.Err() != nil { // an interrupted step still records its file commands, a live deadline stays in force @@ -213,11 +216,15 @@ func runStepExecutor(step step, stage stepStage, executor common.Executor) commo if fileErr := rc.UpdateExtraPath(fileCommandCtx, container.JoinPath(actPath, pathFileCommand)); fileErr != nil && err == nil { err = fileErr } + processStepSummary(fileCommandCtx, rc, summaryPath) } _ = rc.JobContainer.Copy(actPath, files...)(fileCommandCtx) if err == nil { logger.With("stepResult", stepResult.Conclusion).Infof("Success - %s %s", stage, stepString) + } else if _, timedOut := context.Cause(ctx).(jobTimeout); timedOut || ctx.Err() == context.Canceled { + stepResult.Outcome, stepResult.Conclusion = model.StepStatusFailure, model.StepStatusFailure + logger.With("stepResult", "cancelled").Infof("Cancelled - %s %s", stage, stepString) } else { stepResult.Outcome = model.StepStatusFailure @@ -245,16 +252,24 @@ func runStepExecutor(step step, stage stepStage, executor common.Executor) commo } } -func evaluateStepTimeout(ctx context.Context, step step) (context.Context, context.CancelFunc) { - if step.getStepModel().TimeoutMinutes == "" { - return ctx, func() {} - } - timeout, err := step.getRunContext().NewStepExpressionEvaluator(ctx, step).Interpolate(ctx, step.getStepModel().TimeoutMinutes) - 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 { - return context.WithTimeout(ctx, time.Duration(timeOutMinutes)*time.Minute) +type stepTimeout string + +func (timeout stepTimeout) Error() string { return string(timeout) } +func (stepTimeout) Unwrap() error { return context.DeadlineExceeded } + +func evaluateStepTimeout(ctx context.Context, step step, stage stepStage, name string) (context.Context, context.CancelFunc) { + if raw := step.getStepModel().TimeoutMinutes; raw != "" { + minutes, err := step.getRunContext().NewStepExpressionEvaluator(ctx, step).shared(ctx).EvaluateTimeoutMinutes(raw) + if err != nil { + logger := common.Logger(ctx) + logger.Error("##[error]An error occurred when attempting to determine the step timeout.") + logger.Errorf("##[error]%s", EscapeCommandData(err.Error())) + } else if minutes > 0 { + name = model.StepDisplayName(step.getStepModel(), name) + if stage != stepStageMain { + name = stage.String() + " " + name + } + return context.WithTimeoutCause(ctx, time.Duration(minutes)*time.Minute, stepTimeout(fmt.Sprintf("The action '%s' has timed out after %d minutes.", name, minutes))) } } return ctx, func() {} @@ -315,7 +330,7 @@ func isStepEnabled(ctx context.Context, expr string, step step, stage stepStage) if rc.Parent != nil && stage == stepStageMain && jobContext.Status != "cancelled" { jobContext.Status = rc.ownStatus() } - runStep, err := EvalBool(ctx, rc.newStepExpressionEvaluator(ctx, step, rc.actionInputs, jobContext, rc.getGithubContext(ctx)), expr, defaultStatusCheck) + runStep, err := EvalBool(ctx, rc.newExpressionEvaluator(ctx, *step.getEnv(), jobContext, rc.getGithubContext(ctx), "step"), expr, defaultStatusCheck) if err != nil { return false, fmt.Errorf("if-expression %q evaluation failed: %s", expr, err) } diff --git a/act/runner/step_action_local.go b/act/runner/step_action_local.go index c444d9ba..b3508833 100644 --- a/act/runner/step_action_local.go +++ b/act/runner/step_action_local.go @@ -83,12 +83,12 @@ func (sal *stepActionLocal) main() common.Executor { sal.action = actionModel - return sal.runAction(sal, actionDir, nil)(ctx) + return sal.runAction(sal)(ctx) }) } func (sal *stepActionLocal) post() common.Executor { - return runStepExecutor(sal, stepStagePost, runPostStep(sal)).If(hasPostStep(sal)).If(shouldRunPostStep(sal)) + return runStepExecutor(sal, stepStagePost, runActionHook(sal, stepStagePost)).If(hasPostStep(sal)).If(shouldRunPostStep(sal)) } func (sal *stepActionLocal) getRunContext() *RunContext { @@ -117,18 +117,13 @@ func (sal *stepActionLocal) getActionModel() *model.Action { return sal.action } -func (sal *stepActionLocal) getCompositeRunContext(ctx context.Context) (*RunContext, error) { +func (sal *stepActionLocal) getCompositeRunContext(ctx context.Context, inputs map[string]string) *RunContext { if sal.compositeRunContext == nil { _, containerActionDir := getContainerActionPaths(sal) - - compositeRunContext, err := newCompositeRunContext(ctx, sal.RunContext, sal, containerActionDir) - if err != nil { - return nil, err - } - sal.compositeRunContext = compositeRunContext - sal.compositeSteps = compositeRunContext.compositeExecutor(sal.action) + sal.compositeRunContext = newCompositeRunContext(ctx, sal.RunContext, sal, containerActionDir, inputs) + sal.compositeSteps = sal.compositeRunContext.compositeExecutor(sal.action) } - return sal.compositeRunContext, nil + return sal.compositeRunContext } func (sal *stepActionLocal) getCompositeSteps() *compositeSteps { diff --git a/act/runner/step_action_local_test.go b/act/runner/step_action_local_test.go index 6754fc7c..dc3c46b7 100644 --- a/act/runner/step_action_local_test.go +++ b/act/runner/step_action_local_test.go @@ -25,8 +25,8 @@ type stepActionMocks struct { mock.Mock } -func (salm *stepActionMocks) runAction(step actionStep, actionDir string, remoteAction *remoteAction) common.Executor { - args := salm.Called(step, actionDir, remoteAction) +func (salm *stepActionMocks) runAction(step actionStep) common.Executor { + args := salm.Called(step) return args.Get(0).(func(context.Context) error) } @@ -89,7 +89,7 @@ func TestStepActionLocalTest(t *testing.T) { expectStepFileCommands(t, cm) - salm.On("runAction", sal, filepath.Clean("/tmp/path/to/action"), (*remoteAction)(nil)).Return(func(ctx context.Context) error { + salm.On("runAction", sal).Return(func(ctx context.Context) error { sal.RunContext.setOutput(ctx, map[string]string{"name": "value"}, "ran") return nil }) diff --git a/act/runner/step_action_remote.go b/act/runner/step_action_remote.go index 4f523304..1860ccae 100644 --- a/act/runner/step_action_remote.go +++ b/act/runner/step_action_remote.go @@ -46,11 +46,9 @@ var stepActionRemoteFetch = git.FetchAction func (sar *stepActionRemote) fetchAction(ctx context.Context, remote *remoteAction, token string) (string, string, error) { cloneURL := remote.CloneURL(sar.RunContext.Config.DefaultActionURL()) return stepActionRemoteFetch(ctx, sar.RunContext.Config.withInstanceAuth(git.NewGitCloneExecutorInput{ - URL: cloneURL, - Ref: remote.Ref, - Dir: filepath.Join(sar.RunContext.ActionCacheDir(), model.UsesHash(remote.downloadKey(sar.RunContext.Config.DefaultActionURL()))), - OfflineMode: sar.RunContext.Config.ActionOfflineMode, - Depth: sar.RunContext.Config.ActionCloneDepth, + URL: cloneURL, + Ref: remote.Ref, + Dir: filepath.Join(sar.RunContext.ActionCacheDir(), model.UsesHash(remote.downloadKey(sar.RunContext.Config.DefaultActionURL()))), }, token)) } @@ -145,7 +143,7 @@ func (sar *stepActionRemote) pre() common.Executor { sar.prepareActionExecutor(), runStepExecutor(sar, stepStagePre, func(ctx context.Context) error { sar.preStepStarted = true - return runPreStep(sar)(ctx) + return runActionHook(sar, stepStagePre)(ctx) }).If(hasPreStep(sar)).If(shouldRunPreStep(sar))) } @@ -164,13 +162,13 @@ func (sar *stepActionRemote) main() common.Executor { 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)(ctx) }), ) } func (sar *stepActionRemote) post() common.Executor { - return runStepExecutor(sar, stepStagePost, runPostStep(sar)).If(hasPostStep(sar)).If(shouldRunPostStep(sar)) + return runStepExecutor(sar, stepStagePost, runActionHook(sar, stepStagePost)).If(hasPostStep(sar)).If(shouldRunPostStep(sar)) } func (sar *stepActionRemote) containerKey() string { @@ -217,16 +215,11 @@ func (sar *stepActionRemote) getActionModel() *model.Action { return sar.action } -func (sar *stepActionRemote) getCompositeRunContext(ctx context.Context) (*RunContext, error) { +func (sar *stepActionRemote) getCompositeRunContext(ctx context.Context, inputs map[string]string) *RunContext { if sar.compositeRunContext == nil { _, containerActionDir := getContainerActionPaths(sar) - - compositeRunContext, err := newCompositeRunContext(ctx, sar.RunContext, sar, containerActionDir) - if err != nil { - return nil, err - } - sar.compositeRunContext = compositeRunContext - sar.compositeSteps = compositeRunContext.compositeExecutor(sar.action) + sar.compositeRunContext = newCompositeRunContext(ctx, sar.RunContext, sar, containerActionDir, inputs) + sar.compositeSteps = sar.compositeRunContext.compositeExecutor(sar.action) } else { // Re-evaluate environment here. For remote actions the environment // need to be re-created for every stage (pre, main, post) as there @@ -234,14 +227,10 @@ func (sar *stepActionRemote) getCompositeRunContext(ctx context.Context) (*RunCo // stages are executed. (e.g. the output of another action is the // input for this action during the main stage, but the env // was already created during the pre stage) - env, err := evaluateCompositeInputAndEnv(ctx, sar.RunContext, sar) - if err != nil { - return nil, err - } - sar.compositeRunContext.setCompositeActionEnv(env) + sar.compositeRunContext.setCompositeActionEnv(sar.env, inputs) sar.compositeRunContext.ExtraPath = sar.RunContext.ExtraPath } - return sar.compositeRunContext, nil + return sar.compositeRunContext } func (sar *stepActionRemote) getCompositeSteps() *compositeSteps { diff --git a/act/runner/step_action_remote_test.go b/act/runner/step_action_remote_test.go index c4b9236e..0f3cd18c 100644 --- a/act/runner/step_action_remote_test.go +++ b/act/runner/step_action_remote_test.go @@ -114,7 +114,7 @@ func TestStepActionRemote(t *testing.T) { sarm.On("readAction", sar.Step, actionDir, "", mock.Anything, mock.Anything).Return(&model.Action{}, nil) if tt.status != model.StepStatusSkipped { - sarm.On("runAction", sar, actionDir, mustNewRemoteAction(t, sar.Step.Uses)).Return(func(_ctx context.Context) error { return tt.runError }) + sarm.On("runAction", sar).Return(func(_ctx context.Context) error { return tt.runError }) expectStepFileCommands(t, cm) } @@ -133,17 +133,15 @@ func TestStepActionRemote(t *testing.T) { t.Run("refreshes composite inputs without leaking environment", func(t *testing.T) { step := &stepActionRemote{ - Step: &model.Step{Uses: "org/composite@v1", With: map[string]string{"SHARED": "first"}}, + Step: &model.Step{Uses: "org/composite@v1"}, RunContext: &RunContext{Config: &Config{ActionCacheDir: t.TempDir(), PresetGitHubContext: &model.GithubContext{}}, Run: &model.Run{JobID: "job", Workflow: &model.Workflow{Jobs: map[string]*model.Job{"job": {}}}}, JobContainer: &jobContainerMock{}}, - action: &model.Action{Inputs: map[string]model.Input{"shared": {}}}, - env: map[string]string{}, + action: &model.Action{}, + env: map[string]string{"INPUT_SHARED": "stale", "INPUT_UNDECLARED": "stale"}, remoteAction: mustNewRemoteAction(t, "org/composite@v1"), } for _, value := range []string{"first", "second"} { - step.env["INPUT_SHARED"] = value - composite, err := step.getCompositeRunContext(t.Context()) - require.NoError(t, err) + composite := step.getCompositeRunContext(t.Context(), map[string]string{"SHARED": value}) assert.Equal(t, map[string]any{"shared": value}, composite.actionInputs) assert.NotContains(t, composite.Env, "INPUT_SHARED") } diff --git a/act/runner/step_docker.go b/act/runner/step_docker.go index 679f78ac..18422d74 100644 --- a/act/runner/step_docker.go +++ b/act/runner/step_docker.go @@ -6,6 +6,8 @@ package runner import ( "context" + "errors" + "fmt" "strings" "gitea.com/gitea/runner/act/common" @@ -26,7 +28,7 @@ func (sd *stepDocker) pre() common.Executor { return common.NewPipelineExecutor( func (sd *stepDocker) main() common.Executor { sd.env = map[string]string{} - return runStepExecutor(sd, stepStageMain, sd.runUsesContainer()) + return runStepExecutor(sd, stepStageMain, sd.runUsesContainer) } func (sd *stepDocker) post() common.Executor { return common.NewPipelineExecutor() } @@ -47,37 +49,38 @@ func (sd *stepDocker) getIfExpression(_ context.Context, _ stepStage) string { return sd.Step.If.Value } -func (sd *stepDocker) runUsesContainer() common.Executor { +func (sd *stepDocker) runUsesContainer(ctx context.Context) error { rc := sd.RunContext - step := sd.Step - - return func(ctx context.Context) error { - if rc.isWindowsHost() { - return errWindowsHostContainer - } - if rc.kubernetes { - return errKubernetesDocker - } - image := strings.TrimPrefix(step.Uses, "docker://") - cmd, err := shellquote.Split(stepInput(step, "args")) - if err != nil { - return err - } - - var entrypoint []string - if entry := stepInput(step, "entrypoint"); entry != "" { - entrypoint = []string{entry} - } - - stepContainer := newStepContainer(ctx, sd, image, cmd, entrypoint, "") - - return common.NewPipelineExecutor( - stepContainer.Pull(rc.Config.ForcePull), - stepContainer.Remove(), - stepContainer.Create(rc.Config.ContainerCapAdd, rc.Config.ContainerCapDrop), - stepContainer.Start(true), - ).Finally(stepContainer.Close())(ctx) + if rc.isWindowsHost() { + return errWindowsHostContainer } + if rc.kubernetes { + return errKubernetesDocker + } + cmd, err := shellquote.Split(stepInput(sd.Step, "args")) + if err != nil { + return err + } + + var entrypoint []string + if entry := stepInput(sd.Step, "entrypoint"); entry != "" { + entrypoint = []string{entry} + } + input := stepContainerInput(ctx, sd, strings.TrimPrefix(sd.Step.Uses, "docker://"), cmd, entrypoint, "") + return rc.runStepContainer(ctx, ContainerNewContainer(input), nil, rc.Config.ForcePull) +} + +func (rc *RunContext) runStepContainer(ctx context.Context, stepContainer container.Container, prepImage common.Executor, forcePull bool) error { + if stepContainer == nil { + return fmt.Errorf("running a Docker action: %w", errors.ErrUnsupported) + } + return common.NewPipelineExecutor( + prepImage, + stepContainer.Pull(forcePull), + stepContainer.Remove(), + stepContainer.Create(rc.Config.ContainerCapAdd, rc.Config.ContainerCapDrop), + stepContainer.Start(true), + ).Finally(stepContainer.Close())(ctx) } var ContainerNewContainer = container.NewContainer diff --git a/act/runner/step_docker_test.go b/act/runner/step_docker_test.go index 24a7762f..e02cf7a3 100644 --- a/act/runner/step_docker_test.go +++ b/act/runner/step_docker_test.go @@ -5,8 +5,8 @@ package runner import ( + "errors" "slices" - "strings" "testing" "gitea.com/gitea/runner/act/container" @@ -43,28 +43,14 @@ func TestStepDockerMain(t *testing.T) { "DOCKER_PASSWORD": "docker-password", }, }, - Run: &model.Run{ - JobID: "1", - Workflow: &model.Workflow{ - Jobs: map[string]*model.Job{ - "1": { - Defaults: model.Defaults{ - Run: model.RunDefaults{ - Shell: "bash", - }, - }, - }, - }, - }, - }, + Run: &model.Run{JobID: "1", Workflow: &model.Workflow{Jobs: map[string]*model.Job{"1": {}}}}, JobContainer: cm, Env: map[string]string{"GITHUB_ACTION_REPOSITORY": "other/composite", "GITHUB_ACTION_REF": "v1"}, }, Step: &model.Step{ - ID: "1", - Uses: "docker://node:14", - WorkingDirectory: "workdir", - If: yaml.Node{Value: "github.action_repository == 'other/composite' && github.action_ref == 'v1'"}, + ID: "1", + Uses: "docker://node:14", + If: yaml.Node{Value: "github.action_repository == 'other/composite' && github.action_ref == 'v1'"}, }, } require.NoError(t, sd.Step.RawWith.Encode(map[string]string{"args": "identity:${{ github.action_repository }}:${{ github.action_ref }}"})) @@ -95,67 +81,35 @@ func TestStepDockerMain(t *testing.T) { assert.True(t, input.AutoRemove) cm.AssertExpectations(t) + ContainerNewContainer = func(_input *container.NewContainerInput) container.ExecutionsEnvironment { return nil } + require.ErrorIs(t, sd.runUsesContainer(ctx), errors.ErrUnsupported) } func TestStepDockerNewStepContainer(t *testing.T) { inheritedPath := (&container.LinuxContainerEnvironmentExtensions{}).DefaultPathVariable() for _, test := range []struct { - name, platform, image, path, greeting string - allocPTY, expectDefault, keepsPath bool + name, platform, path, network string + allocPTY, keepsPath bool }{ - {name: "allocate PTY/off", platform: "node:14", image: "node:14", greeting: "hi"}, - {name: "allocate PTY/on", platform: "node:14", image: "node:14", greeting: "hi", allocPTY: true}, - {name: "docker mode attaches to job container network", platform: "node:14", image: "alpine:3.20", path: inheritedPath, greeting: "hello", keepsPath: true}, - {name: "host mode uses default network and the image's PATH", platform: "-self-hosted", image: "alpine:3.20", path: inheritedPath, greeting: "hello", expectDefault: true}, - {name: "host mode keeps a PATH that is not the runner's", platform: "-self-hosted", image: "alpine:3.20", path: "/custom/bin", greeting: "hello", expectDefault: true, keepsPath: true}, + {name: "docker mode attaches to job container network", platform: "node:14", path: inheritedPath, network: "job-network", allocPTY: true, keepsPath: true}, + {name: "host mode uses default network and the image's PATH", platform: "-self-hosted", path: inheritedPath, network: "default"}, + {name: "host mode keeps a PATH that is not the runner's", platform: "-self-hosted", path: "/custom/bin", network: "default", keepsPath: true}, } { t.Run(test.name, func(t *testing.T) { - cm := &containerMock{} - var captured *container.NewContainerInput - origContainerNewContainer := ContainerNewContainer - ContainerNewContainer = func(input *container.NewContainerInput) container.ExecutionsEnvironment { - captured = input - return cm + job := &RunContext{ + Config: &Config{AllocatePTY: test.allocPTY}, + Run: &model.Run{Workflow: &model.Workflow{}}, + jobNetworkName: "job-network", } - defer func() { - ContainerNewContainer = origContainerNewContainer - }() - - ctx := t.Context() - sd := &stepDocker{ - RunContext: &RunContext{ - StepResults: map[string]*model.StepResult{}, - Config: &Config{ - PresetGitHubContext: &model.GithubContext{}, - AllocatePTY: test.allocPTY, - PlatformPicker: func(_platforms []string) string { - return test.platform - }, - }, - Run: &model.Run{JobID: "1", Workflow: &model.Workflow{Jobs: map[string]*model.Job{"1": {}}}}, - JobContainer: cm, - }, - Step: &model.Step{ID: "1", Uses: "docker://" + test.image}, - } - sd.RunContext.ExprEval = sd.RunContext.NewExpressionEvaluator(ctx) - if test.path != "" { - sd.env = map[string]string{"PATH": test.path} - require.NoError(t, sd.RunContext.resolvePlatformImage(ctx)) - assert.Equal(t, test.expectDefault, sd.RunContext.IsHostEnv(), "IsHostEnv mismatch for platform %q", test.platform) - } - - newStepContainer(ctx, sd, test.image, []string{"echo", test.greeting}, nil, "") - assert.Equal(t, test.allocPTY, captured.AllocatePTY) - if test.path != "" { - assert.Equal(t, test.keepsPath, slices.Contains(captured.Env, "PATH="+test.path)) - if test.expectDefault { - assert.Equal(t, "default", captured.NetworkMode, - "host-mode step container must use 'default' network, got %q", captured.NetworkMode) - } else { - assert.True(t, strings.HasPrefix(captured.NetworkMode, "container:"), - "docker-mode step container must attach to job container network, got %q", captured.NetworkMode) - } + step := &stepDocker{ + RunContext: &RunContext{Parent: job, Config: job.Config, JobContainer: &containerMock{}, platformImage: test.platform}, + Step: &model.Step{}, + env: map[string]string{"PATH": test.path}, } + input := stepContainerInput(t.Context(), step, "alpine", nil, nil, "") + assert.Equal(t, test.network, input.NetworkMode) + assert.Equal(t, test.allocPTY, input.AllocatePTY) + assert.Equal(t, test.keepsPath, slices.Contains(input.Env, "PATH="+test.path)) }) } } @@ -181,10 +135,10 @@ func TestWindowsHostContainerActions(t *testing.T) { wantError = errWindowsHostContainer.Error() } t.Run("docker step", func(t *testing.T) { - require.EqualError(t, (&stepDocker{RunContext: rc}).runUsesContainer()(t.Context()), wantError) + require.EqualError(t, (&stepDocker{RunContext: rc}).runUsesContainer(t.Context()), wantError) }) t.Run("container action", func(t *testing.T) { - require.EqualError(t, execAsDocker(t.Context(), &stepActionRemote{RunContext: rc}, "action", "", "", false, stepStageMain), wantError) + require.EqualError(t, execAsDocker(t.Context(), &stepActionRemote{RunContext: rc}, stepStageMain, nil, "", ""), wantError) }) }) } diff --git a/act/runner/step_run.go b/act/runner/step_run.go index 67f81516..4705609b 100644 --- a/act/runner/step_run.go +++ b/act/runner/step_run.go @@ -88,27 +88,23 @@ func (sr *stepRun) printRunScriptActionDetails(ctx context.Context) { // printRunActionHeader mirrors actions/runner's "Run " header for `uses:` steps, // including the with: inputs and the step-level env: block. func printRunActionHeader(ctx context.Context, step *model.Step, action *model.Action, env map[string]string, rc *RunContext) { - if step == nil { - return - } - rawLogger := common.Logger(ctx).With(rawOutputField, true) - - rawLogger.Infof("::group::Run %s", EscapeCommandData(step.Uses)) - - inputs := map[string]string{} - maps.Copy(inputs, step.With) - if action != nil { + inputs := step.With + if action != nil && len(action.Inputs) != 0 { + inputs = mergeMaps(inputs) for name := range action.Inputs { if _, provided := common.LookupFold(step.With, name, true); !provided { inputs[name] = env[inputEnvKey(name)] } } } - maps.DeleteFunc(inputs, func(_name, value string) bool { return value == "" }) - if len(inputs) > 0 { - rawLogger.Infof("with:") - for _, k := range slices.Sorted(maps.Keys(inputs)) { - logKeyedValue(rawLogger, k, inputs[k]) + rawLogger := common.Logger(ctx).With(rawOutputField, true) + rawLogger.Infof("::group::Run %s", EscapeCommandData(step.Uses)) + + names := slices.DeleteFunc(slices.Sorted(maps.Keys(inputs)), func(name string) bool { return inputs[name] == "" }) + if len(names) > 0 { + rawLogger.Info("with:") + for _, name := range names { + logKeyedValue(rawLogger, name, inputs[name]) } } diff --git a/act/runner/step_test.go b/act/runner/step_test.go index c9b29fbd..18c4fe85 100644 --- a/act/runner/step_test.go +++ b/act/runner/step_test.go @@ -15,6 +15,7 @@ import ( "testing/synctest" "gitea.com/gitea/runner/act/common" + "gitea.com/gitea/runner/act/common/logging" "gitea.com/gitea/runner/act/common/logging/logtest" "gitea.com/gitea/runner/act/container" "gitea.com/gitea/runner/internal/pkg/telemetry" @@ -179,7 +180,7 @@ func TestSetupEnv(t *testing.T) { "GITHUB_JOB": "1", "GITHUB_REF_PROTECTED": "false", "GITHUB_RETENTION_DAYS": "0", - "GITHUB_RUN_ATTEMPT": "", + "GITHUB_RUN_ATTEMPT": "1", "GITHUB_RUN_ID": "runId", "GITHUB_RUN_NUMBER": "1", "GITHUB_WORKFLOW": "", @@ -235,7 +236,7 @@ jobs: t.Parallel() rc, err := (&runnerImpl{config: &Config{PresetGitHubContext: &model.GithubContext{}}}).newRunContext(t.Context(), &model.Run{Workflow: workflow, JobID: "test"}, map[string]any{"env": `{"WORKFLOW":"` + value + `${{ github.job }}","PRIORITY":"workflow"}`, "priority": "${{ github.job }}", "defaults": `{"shell":"` + value + `"}`}) require.NoError(t, err) - rc.workflowCallInputs = map[string]any{"args": `{"name":"` + value + `${{ github.job }}","fetch-depth":1234567}`} + rc.Config.WorkflowCallInputs = map[string]any{"args": `{"name":"` + value + `${{ github.job }}","fetch-depth":1234567}`} enabled, err := rc.isEnabled(t.Context()) require.NoError(t, err) require.True(t, enabled) @@ -263,7 +264,7 @@ jobs: require.NoError(t, err) rc, err := (&runnerImpl{config: &Config{PresetGitHubContext: &model.GithubContext{}}}).newRunContext(t.Context(), &model.Run{Workflow: workflow, JobID: "test"}, nil) require.NoError(t, err) - rc.workflowCallInputs = map[string]any{"args": "${{ inputs.unresolved }}"} + rc.Config.WorkflowCallInputs = map[string]any{"args": "${{ inputs.unresolved }}"} require.ErrorContains(t, setupInputs(t.Context(), &stepRun{RunContext: rc, Step: workflow.Jobs["test"].Steps[0].Clone(), env: map[string]string{}}), "with:") }) @@ -541,11 +542,13 @@ func TestRunStepExecutorParity(t *testing.T) { t.Run("file commands survive a job timeout", func(t *testing.T) { synctest.Test(t, func(t *testing.T) { - step := newStep(t, &model.Step{ID: "interrupted"}) - ctx, cancel := applyJobTimeout(t.Context(), step.RunContext, &model.Job{TimeoutMinutes: "1"}) + step := newStep(t, &model.Step{ID: "interrupted", RawContinueOnError: "true"}) + logger, hook := logtest.NewLogger() + ctx, cancel, err := applyJobTimeout(common.WithLogger(t.Context(), logger), step.RunContext, &model.Job{TimeoutMinutes: "1"}) + require.NoError(t, err) defer cancel() step.RunContext.JobContainer = &fileCommandTestContainer{step.RunContext.JobContainer.(*container.HostEnvironment)} - err := runStepExecutor(step, stepStageMain, func(execCtx context.Context) error { + err = runStepExecutor(step, stepStageMain, func(execCtx context.Context) error { for name, content := range map[string]string{ "GITHUB_ENV": "KEPT_ENV=value\n", "GITHUB_STATE": "saved=value\n", "GITHUB_OUTPUT": "kept=value\n", "GITHUB_PATH": "/kept/bin\n", @@ -556,6 +559,7 @@ func TestRunStepExecutorParity(t *testing.T) { return execCtx.Err() })(ctx) require.ErrorIs(t, err, context.DeadlineExceeded) + assert.Equal(t, "cancelled", lastRecordAttr(hook, "stepResult")) assert.Equal(t, "value", step.RunContext.Env["KEPT_ENV"]) assert.Equal(t, "value", step.RunContext.IntraActionState[step.Step.ID]["saved"]) assert.Equal(t, "value", step.RunContext.StepResults[step.Step.ID].Outputs["kept"]) @@ -612,23 +616,43 @@ func TestRunStepExecutorParity(t *testing.T) { assert.Contains(t, ended[3].Attributes(), semconv.CICDPipelineTaskRunResultFailure) }) - t.Run("timeout must be positive", func(t *testing.T) { - for timeout, wantDeadline := range map[string]bool{"-1": false, "0": false, "1": true} { - ctx, cancel := evaluateStepTimeout(t.Context(), newStep(t, &model.Step{TimeoutMinutes: timeout})) + t.Run("nonpositive or invalid timeouts leave the step deadline unset", func(t *testing.T) { + for timeout, wantError := range map[string]string{ + "-1": "", + "0": "", + `${{ '1' }}`: "##[error]Unexpected value '1'", + } { + hook := logtest.NewWithLevel(logging.LevelError) + ctx, cancel := evaluateStepTimeout(common.WithLogger(t.Context(), logging.New(hook)), + newStep(t, &model.Step{TimeoutMinutes: timeout}), stepStageMain, "") _, hasDeadline := ctx.Deadline() cancel() - assert.Equal(t, wantDeadline, hasDeadline, timeout) + assert.False(t, hasDeadline, timeout) + records := hook.AllRecords() + if wantError == "" { + assert.Empty(t, records, timeout) + } else { + require.Len(t, records, 2) + assert.Equal(t, "##[error]An error occurred when attempting to determine the step timeout.", records[0].Message) + assert.Equal(t, wantError, records[1].Message) + } } }) t.Run("timeout reads step environment", func(t *testing.T) { - step := newStep(t, &model.Step{ID: "timeout", TimeoutMinutes: "${{ fromJSON(env.STEP_TIMEOUT) }}"}) - require.NoError(t, step.Step.Env.Encode(map[string]string{"STEP_TIMEOUT": "1"})) - require.NoError(t, runStepExecutor(step, stepStageMain, func(ctx context.Context) error { - _, hasDeadline := ctx.Deadline() - assert.True(t, hasDeadline) - return nil - })(t.Context())) + synctest.Test(t, func(t *testing.T) { + step := newStep(t, &model.Step{ID: "timeout", Run: "echo first\necho second", TimeoutMinutes: "${{ fromJSON(env.STEP_TIMEOUT) }}"}) + require.NoError(t, step.Step.Env.Encode(map[string]string{"STEP_TIMEOUT": "1"})) + err := runStepExecutor(step, stepStageMain, func(ctx context.Context) error { + _, ok := ctx.Deadline() + require.True(t, ok) + <-ctx.Done() + return nil + })(t.Context()) + require.EqualError(t, err, "The action 'Run echo first' has timed out after 1 minutes.") + require.ErrorIs(t, err, context.DeadlineExceeded) + assert.Equal(t, model.StepStatusFailure, step.RunContext.StepResults[step.Step.ID].Conclusion) + }) }) } diff --git a/e2e/failure_test.go b/e2e/failure_test.go index 8da917b1..e8cb58b0 100644 --- a/e2e/failure_test.go +++ b/e2e/failure_test.go @@ -32,14 +32,17 @@ func testFailurePaths(t *testing.T, m mode) { func testJobTimeout(t *testing.T) { t.Parallel() - api, repo, _ := startIsolatedScenario(t, "timeout.yml", "e2e-timeout", runnerOptions{timeout: 15 * time.Second}) + const timeout = 15 * time.Second + api, repo, _ := startIsolatedScenario(t, "timeout.yml", "e2e-timeout", runnerOptions{timeout: timeout}) wfRun := waitForRun(t, api, repo) completed, err := api.WaitForRunConclusion(t.Context(), repo, wfRun.ID, runTimeout) if err != nil { dumpRunLogs(t, api, repo, wfRun.ID) t.Fatalf("wait for run: %v", err) } - if logs := runLogs(t, api, repo, wfRun.ID); completed.Conclusion != "failure" || commandRow(logs, "e2e-timeout-started") == "" { - t.Errorf("run concluded %q, want failure after the job started, logs:\n%s", completed.Conclusion, logs) + logs := runLogs(t, api, repo, wfRun.ID) + if completed.Conclusion != "failure" || commandRow(logs, "e2e-timeout-started") == "" || + commandRow(logs, "job exceeded runner.timeout of "+timeout.String()) == "" { + t.Errorf("run concluded %q, want failure after the job started and exceeded runner.timeout, logs:\n%s", completed.Conclusion, logs) } } diff --git a/examples/systemd/gitea-runner.service b/examples/systemd/gitea-runner.service index 17c37694..90eb65ec 100644 --- a/examples/systemd/gitea-runner.service +++ b/examples/systemd/gitea-runner.service @@ -24,6 +24,7 @@ RestartSec=5s # Allow running jobs to finish before the runner is stopped. Keep this in sync # with runner.shutdown_timeout in the config. +KillMode=mixed TimeoutStopSec=3h [Install] diff --git a/go.mod b/go.mod index e0ff3e6c..0652c6f7 100644 --- a/go.mod +++ b/go.mod @@ -6,7 +6,7 @@ toolchain go1.27.4 require ( connectrpc.com/connect/v2 v2.0.2 - gitea.dev/actionslib v1.6.0 + gitea.dev/actionslib v1.7.0 github.com/bmatcuk/doublestar/v4 v4.10.4 github.com/coder/websocket v1.8.15 github.com/containerd/errdefs v1.0.0 diff --git a/go.sum b/go.sum index 76fcb922..8fb397ea 100644 --- a/go.sum +++ b/go.sum @@ -1,7 +1,7 @@ connectrpc.com/connect/v2 v2.0.2 h1:PoPDmOlhc46elsuCdKCKTxjNBb3HJlKF+s/sP2oucPw= connectrpc.com/connect/v2 v2.0.2/go.mod h1:N32OLrstcPUzkykFynnefFro3+xzSdOrZlK2jHmS/xo= -gitea.dev/actionslib v1.6.0 h1:1xKhGyJzL9CYHJ+ESqFdxetbAU+2U7YIEuPYtsS3Fuk= -gitea.dev/actionslib v1.6.0/go.mod h1:i8wUQMnvGwT13f2re2ZTMCFL/TyauQLeOb1L4ngjtPk= +gitea.dev/actionslib v1.7.0 h1:J2KWyKyb2XvhizjGmLu3b1I94lZzTShZ3eMmSRMGm/Q= +gitea.dev/actionslib v1.7.0/go.mod h1:i8wUQMnvGwT13f2re2ZTMCFL/TyauQLeOb1L4ngjtPk= github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY= github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= diff --git a/internal/app/cmd/daemon.go b/internal/app/cmd/daemon.go index 28770304..d3bfa4e4 100644 --- a/internal/app/cmd/daemon.go +++ b/internal/app/cmd/daemon.go @@ -295,21 +295,19 @@ type daemonArgs struct { // resolveLabels picks the labels to run with: --labels/GITEA_RUNNER_LABELS > config > .runner. // The flag lets a registered runner change its labels without deleting the .runner file. func resolveLabels(argLabels string, cfgLabels, regLabels []string) []string { - if lbls := splitLabels(argLabels); len(lbls) > 0 { + lbls := trimLabels(strings.Split(argLabels, ",")) + if lbls = slices.DeleteFunc(lbls, func(label string) bool { return label == "" }); len(lbls) > 0 { return lbls } if len(cfgLabels) > 0 { - return cfgLabels + regLabels = cfgLabels } - return regLabels + return trimLabels(slices.Clone(regLabels)) } -func splitLabels(s string) []string { - var lbls []string - for l := range strings.SplitSeq(s, ",") { - if l = strings.TrimSpace(l); l != "" { - lbls = append(lbls, l) - } +func trimLabels(lbls []string) []string { + for i := range lbls { + lbls[i] = strings.TrimSpace(lbls[i]) } return lbls } diff --git a/internal/app/cmd/daemon_test.go b/internal/app/cmd/daemon_test.go index 064a3613..d237b7ba 100644 --- a/internal/app/cmd/daemon_test.go +++ b/internal/app/cmd/daemon_test.go @@ -39,9 +39,9 @@ func TestResolveLabels(t *testing.T) { reg []string want []string }{ - {"flag wins", "flag:host,other", cfgLabels, regLabels, []string{"flag:host", "other"}}, - {"config wins over registration", "", cfgLabels, regLabels, cfgLabels}, - {"registration is the fallback", "", nil, regLabels, regLabels}, + {"flag wins", "flag:host, , other", cfgLabels, regLabels, []string{"flag:host", "other"}}, + {"config wins over registration", "", []string{" cfg:host "}, regLabels, cfgLabels}, + {"registration is the fallback", "", nil, []string{" reg:host "}, regLabels}, {"blank flag is ignored", " , ", cfgLabels, regLabels, cfgLabels}, {"nothing configured", "", nil, nil, nil}, } diff --git a/internal/app/cmd/register.go b/internal/app/cmd/register.go index a763799f..b11d58be 100644 --- a/internal/app/cmd/register.go +++ b/internal/app/cmd/register.go @@ -162,7 +162,7 @@ func (r *registerInputs) assignToNext(stage registerStage, value string, cfg *co // if there are some labels configured in config file, skip input labels stage if len(cfg.Runner.Labels) > 0 { ls := make([]string, 0, len(cfg.Runner.Labels)) - for _, l := range cfg.Runner.Labels { + for _, l := range trimLabels(cfg.Runner.Labels) { _, err := labels.Parse(l) if err != nil { logging.WithError(err).Warnf("ignored invalid label %q", l) @@ -180,7 +180,7 @@ func (r *registerInputs) assignToNext(stage registerStage, value string, cfg *co case StageInputLabels: r.Labels = defaultLabels if value != "" { - r.Labels = strings.Split(value, ",") + r.Labels = trimLabels(strings.Split(value, ",")) } if validateLabels(r.Labels) != nil { @@ -216,10 +216,8 @@ func initInputs(regArgs *registerArgs) (*registerInputs, error) { RunnerName: strings.TrimSpace(regArgs.RunnerName), Ephemeral: regArgs.Ephemeral, } - regArgs.Labels = strings.TrimSpace(regArgs.Labels) - // command line flag. - if regArgs.Labels != "" { - inputs.Labels = strings.Split(regArgs.Labels, ",") + if labels := strings.TrimSpace(regArgs.Labels); labels != "" { + inputs.Labels = trimLabels(strings.Split(labels, ",")) } return inputs, nil } @@ -303,10 +301,10 @@ func registerNoInteractive(ctx context.Context, configFile string, regArgs *regi } // specify labels in config file. if len(cfg.Runner.Labels) > 0 { - if regArgs.Labels != "" { + if len(inputs.Labels) > 0 { logging.Warn("Labels from command will be ignored, use labels defined in config file.") } - inputs.Labels = cfg.Runner.Labels + inputs.Labels = trimLabels(cfg.Runner.Labels) } if len(inputs.Labels) == 0 { inputs.Labels = defaultLabels diff --git a/internal/app/cmd/register_test.go b/internal/app/cmd/register_test.go index fc8f834d..78d99225 100644 --- a/internal/app/cmd/register_test.go +++ b/internal/app/cmd/register_test.go @@ -144,7 +144,7 @@ func TestRegisterInputsAssignToNext(t *testing.T) { t.Run("labels from config skip the labels stage", func(t *testing.T) { cfg := &config.Config{} - cfg.Runner.Labels = []string{"ubuntu:host", "", "pool:e57e18d4"} + cfg.Runner.Labels = []string{" ubuntu:host ", " ", "pool:e57e18d4"} inputs := ®isterInputs{} require.Equal(t, StageWaitingForRegistration, inputs.assignToNext(StageInputRunnerName, "runner", cfg)) require.Equal(t, []string{"ubuntu:host", "pool:e57e18d4"}, inputs.Labels) @@ -158,13 +158,13 @@ func TestRegisterInputsAssignToNext(t *testing.T) { t.Run("invalid labels input loops back", func(t *testing.T) { inputs := ®isterInputs{} - require.Equal(t, StageInputLabels, inputs.assignToNext(StageInputLabels, "ubuntu:host,,bad", emptyCfg)) + require.Equal(t, StageInputLabels, inputs.assignToNext(StageInputLabels, "ubuntu:host, ,bad", emptyCfg)) require.Nil(t, inputs.Labels) }) t.Run("labels containing a colon are accepted", func(t *testing.T) { inputs := ®isterInputs{} - require.Equal(t, StageWaitingForRegistration, inputs.assignToNext(StageInputLabels, "pool:e57e18d4,ubuntu:host", emptyCfg)) + require.Equal(t, StageWaitingForRegistration, inputs.assignToNext(StageInputLabels, "pool:e57e18d4 , ubuntu:host", emptyCfg)) require.Equal(t, []string{"pool:e57e18d4", "ubuntu:host"}, inputs.Labels) }) @@ -245,7 +245,7 @@ func TestInitInputs(t *testing.T) { require.Equal(t, tc.wantToken, inputs.Token) require.Equal(t, "runner", inputs.RunnerName) require.True(t, inputs.Ephemeral) - require.Equal(t, []string{"ubuntu:host ", " ubuntu:docker://node:18"}, inputs.Labels) + require.Equal(t, []string{"ubuntu:host", "ubuntu:docker://node:18"}, inputs.Labels) }) } diff --git a/internal/app/run/post_task_script_test.go b/internal/app/run/post_task_script_test.go index 9bb2f676..6684467e 100644 --- a/internal/app/run/post_task_script_test.go +++ b/internal/app/run/post_task_script_test.go @@ -49,14 +49,12 @@ func TestRunPostTaskScriptNonZeroExitDoesNotPanic(t *testing.T) { cfg.Runner.PostTaskScript = scriptPath r := &Runner{cfg: cfg} - ctx, cancel := context.WithCancel(t.Context()) - defer cancel() task := &runnerv1.Task{Id: 1, Context: &structpb.Struct{}} - reporter := report.NewReporter(ctx, cancel, nil, task, cfg) + reporter := report.NewReporter(t.Context(), nil, nil, task, cfg) require.NotPanics(t, func() { - r.runPostTaskScript(ctx, reporter, task, "/workspace/owner/repo") + r.runPostTaskScript(t.Context(), reporter, task, "/workspace/owner/repo") }) require.NotNil(t, hook.LastRecord()) assert.Contains(t, hook.LastRecord().Message, "exited with code 2") @@ -92,16 +90,13 @@ func TestPostTaskScriptEnv(t *testing.T) { envs: map[string]string{"BASE": "1"}, } - ctx, cancel := context.WithCancel(t.Context()) - defer cancel() - taskCtx, err := structpb.NewStruct(map[string]any{ "run_id": "99", "repository": "acme/widget", }) require.NoError(t, err) task := &runnerv1.Task{Id: 3, Context: taskCtx} - reporter := report.NewReporter(ctx, cancel, nil, task, cfg) + reporter := report.NewReporter(t.Context(), nil, nil, task, cfg) setReporterJobResult(t, reporter, runnerv1.Result_RESULT_FAILURE) env := r.postTaskScriptEnv(reporter, task, "/tmp/workspace") @@ -134,14 +129,11 @@ func TestRunPostTaskScriptIntegration(t *testing.T) { envs: map[string]string{"CUSTOM": "runner-env"}, } - ctx, cancel := context.WithCancel(t.Context()) - defer cancel() - task := &runnerv1.Task{Id: 11, Context: &structpb.Struct{}} - reporter := report.NewReporter(ctx, cancel, nil, task, cfg) + reporter := report.NewReporter(t.Context(), nil, nil, task, cfg) setReporterJobResult(t, reporter, runnerv1.Result_RESULT_SUCCESS) - r.runPostTaskScript(ctx, reporter, task, "/workspace/acme/repo") + r.runPostTaskScript(t.Context(), reporter, task, "/workspace/acme/repo") content, err := os.ReadFile(outFile) require.NoError(t, err) diff --git a/internal/app/run/runner.go b/internal/app/run/runner.go index f58d6a5c..94a594b7 100644 --- a/internal/app/run/runner.go +++ b/internal/app/run/runner.go @@ -300,11 +300,12 @@ func (r *Runner) Run(ctx context.Context, task *runnerv1.Task) (err error) { start := time.Now() - ctx, cancel := context.WithTimeout(ctx, r.cfg.Runner.Timeout) + ctx, cancel := context.WithTimeoutCause(ctx, r.cfg.Runner.Timeout, fmt.Errorf("job exceeded runner.timeout of %s", r.cfg.Runner.Timeout)) defer cancel() + ctx, cancelJob := context.WithCancelCause(ctx) ctx, endJob := telemetry.StartJob(ctx, task) // A proxy URL may carry credentials, and every job is given it; keep them out of the log. - reporter := report.NewReporter(ctx, cancel, r.client, task, r.cfg, proxyPasswords(r.envs)...) + reporter := report.NewReporter(ctx, cancelJob, r.client, task, r.cfg, proxyPasswords(r.envs)...) var volumeCleanup []common.Executor var volumeCleanupMu sync.Mutex if r.cfg.Runner.PostTaskScript == "" { @@ -316,11 +317,7 @@ func (r *Runner) Run(ctx context.Context, task *runnerv1.Task) (err error) { } var runErr error defer func() { - lastWords := "" - if runErr != nil { - lastWords = runErr.Error() - } - err = reporter.Close(lastWords) + err = reporter.Close(runErr) if err := cleanupJobVolumes(ctx, volumeCleanup); err != nil { logging.Warnf("task %d volume cleanup after reporting: %v", task.Id, err) } @@ -331,6 +328,9 @@ func (r *Runner) Run(ctx context.Context, task *runnerv1.Task) (err error) { }() reporter.RunDaemon() runErr = r.run(ctx, task, reporter) + if ctx.Err() != nil && errors.Is(runErr, ctx.Err()) { + runErr = context.Cause(ctx) + } return nil } @@ -519,6 +519,9 @@ func (r *Runner) run(ctx context.Context, task *runnerv1.Task, reporter *report. preset := model.GithubContextFromMap(task.Context.AsMap()) preset.Token = cmp.Or(task.Secrets["GITEA_TOKEN"], task.Secrets["GITHUB_TOKEN"], preset.Token) + if task.Secrets == nil { + task.Secrets = make(map[string]string) + } if actionsIDTokenRequestURL := taskContext["actions_id_token_request_url"].GetStringValue(); actionsIDTokenRequestURL != "" { envs["ACTIONS_ID_TOKEN_REQUEST_URL"] = actionsIDTokenRequestURL envs["ACTIONS_ID_TOKEN_REQUEST_TOKEN"] = taskContext["actions_id_token_request_token"].GetStringValue() @@ -647,8 +650,6 @@ func (r *Runner) run(ctx context.Context, task *runnerv1.Task, reporter *report. if err != nil { return err } - executor := rr.NewPlanExecutor(plan) - reporter.Logf("workflow prepared") // add logger recorders @@ -658,7 +659,7 @@ func (r *Runner) run(ctx context.Context, task *runnerv1.Task, reporter *report. ctx = runner.WithJobLoggerFactory(ctx, NullLogger{}) } - execErr := executor(ctx) + execErr := rr.NewPlanExecutor(plan)(ctx) reporter.SetOutputs(job.Outputs) if r.cfg.Container.BindWorkdir { diff --git a/internal/app/run/runner_test.go b/internal/app/run/runner_test.go index b8ebac73..caf7365a 100644 --- a/internal/app/run/runner_test.go +++ b/internal/app/run/runner_test.go @@ -124,6 +124,7 @@ func TestRunnerReclaimsVolumesAfterReporting(t *testing.T) { if response, ok := map[string]string{ "/_ping": "OK", "/info": `{"Architecture":"amd64","OSType":"linux"}`, + "/version": `{"Os":"linux","Arch":"amd64"}`, "/containers/json": "[]", "/networks": "[]", "/volumes": `{"Volumes":[]}`, @@ -163,7 +164,7 @@ func TestRunnerReclaimsVolumesAfterReporting(t *testing.T) { t.Cleanup(daemon.Close) t.Setenv("DOCKER_HOST", daemon.URL) require.NoError(t, r.Run(t.Context(), &runnerv1.Task{ - Context: &structpb.Struct{}, + Context: &structpb.Struct{Fields: map[string]*structpb.Value{"gitea_runtime_token": structpb.NewStringValue("runtime-token")}}, WorkflowPayload: []byte("jobs:\n job:\n runs-on: ubuntu\n steps:\n - run: exit 0\n if: false\n"), })) assert.True(t, reported.Load()) diff --git a/internal/app/run/workflow.go b/internal/app/run/workflow.go index 340c5950..5edc3246 100644 --- a/internal/app/run/workflow.go +++ b/internal/app/run/workflow.go @@ -33,7 +33,7 @@ func generateWorkflow(task *runnerv1.Task) (*model.Workflow, string, error) { for id, need := range task.Needs { workflow.Jobs[id] = &model.Job{ Outputs: need.Outputs, - Result: strings.ToLower(strings.TrimPrefix(need.Result.String(), "RESULT_")), + Result: need.Result.Conclusion(), } rawNeeds.Content = append(rawNeeds.Content, &yaml.Node{ Kind: yaml.ScalarNode, diff --git a/internal/pkg/config/registration.go b/internal/pkg/config/registration.go index 464f4a5a..1ae7b197 100644 --- a/internal/pkg/config/registration.go +++ b/internal/pkg/config/registration.go @@ -6,6 +6,7 @@ package config import ( "encoding/json/jsontext" "encoding/json/v2" + "errors" "os" ) @@ -42,12 +43,15 @@ func LoadRegistration(file string) (*Registration, error) { } func SaveRegistration(file string, reg *Registration) error { - f, err := os.Create(file) + f, err := os.OpenFile(file, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600) if err != nil { return err } defer f.Close() + if err := f.Chmod(0o600); err != nil && !errors.Is(err, os.ErrPermission) { + return err + } reg.Warning = registrationWarning if err := json.MarshalWrite(f, reg, jsontext.WithIndent(" ")); err != nil { diff --git a/internal/pkg/config/registration_test.go b/internal/pkg/config/registration_test.go index 434b5f01..6e6382a8 100644 --- a/internal/pkg/config/registration_test.go +++ b/internal/pkg/config/registration_test.go @@ -6,6 +6,7 @@ package config import ( "os" "path/filepath" + "runtime" "testing" "github.com/stretchr/testify/require" @@ -25,6 +26,14 @@ func TestSaveAndLoadRegistration(t *testing.T) { } require.NoError(t, SaveRegistration(file, reg)) + require.NoError(t, os.Chmod(file, 0o644)) + reg.Name = "new" + require.NoError(t, SaveRegistration(file, reg)) + if runtime.GOOS != "windows" { + info, err := os.Stat(file) + require.NoError(t, err) + require.Equal(t, os.FileMode(0o600), info.Mode().Perm()) + } // SaveRegistration stamps the warning onto the in-memory struct require.Equal(t, registrationWarning, reg.Warning) diff --git a/internal/pkg/report/joblog_test.go b/internal/pkg/report/joblog_test.go index 3f1675e1..c66e21b8 100644 --- a/internal/pkg/report/joblog_test.go +++ b/internal/pkg/report/joblog_test.go @@ -42,10 +42,8 @@ func TestJobLog_MirrorsUploadedRows(t *testing.T) { require.NoError(t, err) cfg.Log.Job.Dir = t.TempDir() - ctx, cancel := context.WithCancel(t.Context()) - t.Cleanup(cancel) task := &runnerv1.Task{Id: 41, Context: &structpb.Struct{}, Secrets: map[string]string{"TOKEN": "s3cret-value"}} - reporter := NewReporter(ctx, cancel, client, task, cfg) + reporter := NewReporter(t.Context(), nil, client, task, cfg) require.NotNil(t, reporter.jobLog) reporter.RunDaemon() reporter.ResetSteps(newTestSteps(1)) @@ -60,7 +58,7 @@ func TestJobLog_MirrorsUploadedRows(t *testing.T) { fire("the token is s3cret-value") reporter.AddMask("dyn4mic-value") fire("and dyn4mic-value too") - require.NoError(t, reporter.Close("")) + require.NoError(t, reporter.Close(nil)) job := readJobLog(t, reporter.jobLog) assert.Contains(t, job, "the token is ***") diff --git a/internal/pkg/report/reporter.go b/internal/pkg/report/reporter.go index b017de27..258939da 100644 --- a/internal/pkg/report/reporter.go +++ b/internal/pkg/report/reporter.go @@ -22,6 +22,7 @@ import ( "connectrpc.com/connect/v2" "gitea.dev/actionslib/pkg/model" + "gitea.dev/actionslib/pkg/protocol" runnerv1 "gitea.dev/actionslib/runner/v1" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/known/timestamppb" @@ -30,12 +31,6 @@ import ( // errOutputsNotSent travels the same return path as transport failures but is not one. var errOutputsNotSent = errors.New("there are still outputs that have not been sent") -// Size limits for the outputs reported to the server. -const ( - maxOutputKeyLen = 255 - maxOutputValueLen = 1024 * 1024 // 1 MiB -) - // jobOutput is a job output on its way to the server, sent once the server has acknowledged it. type jobOutput struct { value string @@ -44,7 +39,7 @@ type jobOutput struct { type Reporter struct { ctx context.Context - cancel context.CancelFunc + cancel context.CancelCauseFunc closed bool client client.Client @@ -68,10 +63,8 @@ type Reporter struct { currentReportedStep *runnerv1.StepState stepModels []*model.Step // reportFailing keeps an outage to one log line at each end. - reportFailing map[string]bool - // serverResult is what the server decided, e.g. the zombie reaper failing - // the task. Guarded by stateMu. - serverResult runnerv1.Result + reportFailing map[string]bool + serverEndErr error stateMu sync.RWMutex outputsMu sync.Mutex outputs map[string]jobOutput @@ -102,7 +95,7 @@ type Reporter struct { // extraMasks are values known before the job starts that are not among its secrets, such as // the password in the runner's proxy URL. -func NewReporter(ctx context.Context, cancel context.CancelFunc, client client.Client, task *runnerv1.Task, cfg *config.Config, extraMasks ...string) *Reporter { +func NewReporter(ctx context.Context, cancel context.CancelCauseFunc, client client.Client, task *runnerv1.Task, cfg *config.Config, extraMasks ...string) *Reporter { var oldnew []string for _, v := range extraMasks { oldnew = runner.AppendSecretMasker(oldnew, v) @@ -174,7 +167,7 @@ func (r *Reporter) ResetSteps(steps []*model.Step) { setup.LogLength = int64(r.logOffset + len(r.logRows)) // the runner's own lines logged before the job was parsed r.currentReportedStep = setup for i, step := range steps { - r.addReportedStep(len(r.state.ReportedSteps), runnerv1.StepStage_STEP_STAGE_MAIN, i, r.mask(stepDisplayName(step, ""))) + r.addReportedStep(len(r.state.ReportedSteps), runnerv1.StepStage_STEP_STAGE_MAIN, i, r.mask(model.StepDisplayName(step, ""))) } r.addReportedStep(len(r.state.ReportedSteps), runnerv1.StepStage_STEP_STAGE_CLEANUP, 0, "Complete job") } @@ -184,16 +177,6 @@ type reportedStepKey struct { number int } -// stepDisplayName names a workflow step like Gitea and GitHub do, prefixing an unnamed one with "Run". -// evaluated is step.String() with its expressions evaluated, empty while the step has not run yet. -func stepDisplayName(step *model.Step, evaluated string) string { - if step.Name != "" { - return cmp.Or(evaluated, step.Name) - } - first, _, _ := strings.Cut(strings.TrimSpace(cmp.Or(evaluated, step.String())), "\n") - return "Run " + cmp.Or(strings.TrimSpace(first), step.String()) -} - // addReportedStep inserts a step at pos of the reported steps. Caller holds stateMu. func (r *Reporter) addReportedStep(pos int, stage runnerv1.StepStage, number int, name string) *runnerv1.StepState { step := &runnerv1.StepState{Name: name, Stage: stage, Number: int64(number)} @@ -233,7 +216,7 @@ func (r *Reporter) reportedStepOf(entry logging.Record) (*runnerv1.StepState, bo main := r.reportedSteps[reportedStepKey{runnerv1.StepStage_STEP_STAGE_MAIN, number}] if evaluated, _ := recordAttr[string](entry, "step"); evaluated != "" { // evaluated as GitHub shows it, and masked as an expression can name a secret - main.Name = r.mask(stepDisplayName(r.stepModels[number], evaluated)) + main.Name = r.mask(model.StepDisplayName(r.stepModels[number], evaluated)) } if step, ok := r.reportedSteps[key]; ok { return step, true @@ -332,15 +315,19 @@ func (h *reporterHandler) WithAttrs(attrs []logging.Attr) logging.Handler { func (r *Reporter) appendLogRow(row *runnerv1.LogRow) { row.Content = r.mask(row.Content) if step := r.currentReportedStep; step != nil { - if step.LogLength == 0 { - step.LogIndex = int64(r.logOffset + len(r.logRows)) - } - step.LogLength++ + r.extendStepLog(step) } r.logRows = append(r.logRows, row) r.jobLog.write(row.Time.AsTime(), row.Content) } +func (r *Reporter) extendStepLog(step *runnerv1.StepState) { + if step.LogLength == 0 { + step.LogIndex = int64(r.logOffset + len(r.logRows)) + } + step.LogLength++ +} + func attrArgs(attrs []logging.Attr) []any { args := make([]any, len(attrs)) for i, a := range attrs { @@ -420,7 +407,9 @@ func (r *Reporter) Handle(_ context.Context, entry logging.Record) error { if v, ok := entry.Attr("jobResult"); ok { if jobResult, ok := parseResult(v); ok { // We need to ensure log upload before this upload - r.state.Result = jobResult + if r.serverEndErr == nil { + r.state.Result = jobResult + } r.state.StoppedAt = timestamppb.New(timestamp) for _, s := range r.state.Steps { if s.Result == runnerv1.Result_RESULT_UNSPECIFIED { @@ -464,10 +453,7 @@ func (r *Reporter) Handle(_ context.Context, entry logging.Record) error { v, hasRawOutput := entry.Attr("raw_output") rawOutput, _ := v.(bool) if entry.Level >= logging.LevelError || rawOutput { - if step.LogLength == 0 { - step.LogIndex = int64(r.logOffset + len(r.logRows)) - } - step.LogLength++ + r.extendStepLog(step) r.appendLogRow(logRow(entry)) } else if !hasRawOutput && r.shouldAppendLogRow(entry) { r.appendLogRow(logRow(entry)) @@ -624,19 +610,18 @@ func (r *Reporter) SetOutputs(outputs map[string]string) { r.outputs = map[string]jobOutput{} } for k, v := range outputs { - if l := len(k); l > maxOutputKeyLen { - logging.Warnf("ignore output %q because the key is too long: %d > %d", k, l, maxOutputKeyLen) - r.logf("ignore output %q because the key is too long: %d > %d", k, l, maxOutputKeyLen) - continue + var reason string + switch { + case len(k) > protocol.MaxOutputKeyLength: + reason = fmt.Sprintf("the key is too long: %d > %d", len(k), protocol.MaxOutputKeyLength) + case len(v) > protocol.MaxOutputValueLength: + reason = fmt.Sprintf("the value is too long: %d > %d", len(v), protocol.MaxOutputValueLength) + case r.logReplacer.Replace(v) != v: // GitHub skips an output that may carry a secret rather than masking it + reason = "it may contain a secret" } - if l := len(v); l > maxOutputValueLen { - logging.Warnf("ignore output %q because the value is too long: %d > %d", k, l, maxOutputValueLen) - r.logf("ignore output %q because the value is too long: %d > %d", k, l, maxOutputValueLen) - continue - } - if r.logReplacer.Replace(v) != v { // GitHub skips an output that may carry a secret rather than masking it - logging.Warnf("ignore output %q because it may contain a secret", k) - r.logf("ignore output %q because it may contain a secret", k) + if reason != "" { + logging.Warnf("ignore output %q because %s", k, reason) + r.logf("ignore output %q because %s", k, reason) continue } if _, ok := r.outputs[k]; !ok { @@ -645,34 +630,32 @@ func (r *Reporter) SetOutputs(outputs map[string]string) { } } -func (r *Reporter) Close(lastWords string) error { +func (r *Reporter) Close(runErr error) error { defer deregisterGlobalMasks(r) // deferred so a panic below cannot strand this task's masks r.stateMu.Lock() r.closed = true + var lastWords string if r.state.Result == runnerv1.Result_RESULT_UNSPECIFIED { - // No result of its own, so say why it stopped. - result, words := runnerv1.Result_RESULT_FAILURE, "Early termination" - switch { - case r.serverResult != runnerv1.Result_RESULT_UNSPECIFIED: - result, words = r.serverResult, "Ended by the server" - case errors.Is(r.ctx.Err(), context.Canceled): - result, words = runnerv1.Result_RESULT_CANCELLED, "Cancelled" - } - if lastWords == "" { - lastWords = words + if r.ctx.Err() == context.Canceled { + r.state.Result = runnerv1.Result_RESULT_CANCELLED + lastWords = "Cancelled" + } else { + r.state.Result = runnerv1.Result_RESULT_FAILURE + lastWords = "Early termination" } + } + if r.state.StoppedAt == nil { for _, v := range r.state.Steps { if v.Result == runnerv1.Result_RESULT_UNSPECIFIED { v.Result = runnerv1.Result_RESULT_CANCELLED } } - r.state.Result = result - r.appendLogRow(&runnerv1.LogRow{ - Time: timestamppb.Now(), - Content: lastWords, - }) r.state.StoppedAt = timestamppb.Now() - } else if lastWords != "" { + } + if runErr != nil && (r.serverEndErr == nil || runErr != context.Canceled && !errors.Is(runErr, r.serverEndErr)) { + lastWords = cmp.Or(runErr.Error(), lastWords) + } + if lastWords != "" { r.appendLogRow(&runnerv1.LogRow{ Time: timestamppb.Now(), Content: lastWords, @@ -888,11 +871,18 @@ func (r *Reporter) ReportState(reportResult bool) error { // A terminal result means the server is done with this task; keep running and // the job holds a capacity slot until runner.timeout. - if state := resp.State; state != nil && state.Result != runnerv1.Result_RESULT_UNSPECIFIED { + if result := resp.GetState().GetResult(); result != runnerv1.Result_RESULT_UNSPECIFIED { r.stateMu.Lock() - r.serverResult = state.Result + if !r.closed && r.serverEndErr == nil { + r.serverEndErr = errors.New("Ended by the server: " + metrics.ResultToStatusLabel(result)) + r.state.Result = result + if step := r.currentReportedStep; step != nil && step.Stage == runnerv1.StepStage_STEP_STAGE_MAIN && step.StoppedAt == nil { + r.extendStepLog(r.state.Steps[step.Number]) + } + r.appendLogRow(&runnerv1.LogRow{Time: timestamppb.Now(), Content: r.serverEndErr.Error()}) + r.cancel(r.serverEndErr) + } r.stateMu.Unlock() - r.cancel() } if len(noSent) > 0 { return fmt.Errorf("%w: %v", errOutputsNotSent, noSent) @@ -919,23 +909,12 @@ func (r *Reporter) shouldAppendLogRow(entry logging.Record) bool { return !r.duringSteps() && entry.Level >= r.logReportLevel } -var stringToResult = map[string]runnerv1.Result{ - "success": runnerv1.Result_RESULT_SUCCESS, - "failure": runnerv1.Result_RESULT_FAILURE, - "skipped": runnerv1.Result_RESULT_SKIPPED, - "cancelled": runnerv1.Result_RESULT_CANCELLED, -} - func parseResult(result any) (runnerv1.Result, bool) { - str := "" - if v, ok := result.(string); ok { // for jobResult - str = v - } else if v, ok := result.(fmt.Stringer); ok { // for stepResult - str = v.String() + if stringer, ok := result.(fmt.Stringer); ok { + result = stringer.String() } - - ret, ok := stringToResult[str] - return ret, ok + conclusion, _ := result.(string) + return runnerv1.ParseConclusion(conclusion) } func logRow(entry logging.Record) *runnerv1.LogRow { diff --git a/internal/pkg/report/reporter_test.go b/internal/pkg/report/reporter_test.go index 68ef0215..543e0e90 100644 --- a/internal/pkg/report/reporter_test.go +++ b/internal/pkg/report/reporter_test.go @@ -27,6 +27,7 @@ import ( "gitea.com/gitea/runner/internal/pkg/metrics" "gitea.dev/actionslib/pkg/model" + "gitea.dev/actionslib/pkg/protocol" runnerv1 "gitea.dev/actionslib/runner/v1" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" @@ -72,7 +73,7 @@ func TestReporter_LogLevelFiltering(t *testing.T) { assert.True(t, reporter.shouldAppendLogRow(logging.Record{Level: logging.LevelWarn})) reporter.RunDaemon() defer func() { - require.NoError(t, reporter.Close("")) + require.NoError(t, reporter.Close(nil)) }() reporter.ResetSteps(newTestSteps(2)) @@ -172,18 +173,13 @@ func TestReporter_RunDaemonClose_Race(t *testing.T) { }, ) - ctx, cancel := context.WithCancel(t.Context()) cfg, _ := config.LoadDefault("") - reporter := NewReporter(ctx, cancel, client, &runnerv1.Task{ - Context: &structpb.Struct{}, - }, cfg) + reporter := newTestReporter(t, client, cfg) reporter.ResetSteps(newTestSteps(1)) reporter.RunDaemon() - require.NoError(t, reporter.Close("")) - - cancel() + require.NoError(t, reporter.Close(nil)) } func TestReporter_LogFlush(t *testing.T) { @@ -215,7 +211,7 @@ func TestReporter_LogFlush(t *testing.T) { reporter := newTestReporter(t, client, cfg) reporter.ResetSteps(newTestSteps(1)) reporter.RunDaemon() - defer func() { require.NoError(t, reporter.Close("")) }() + defer func() { require.NoError(t, reporter.Close(nil)) }() for _, message := range tc.messages { require.NoError(t, fire(reporter, logEntry{ @@ -340,7 +336,7 @@ func TestReporter_StateNotifyFlush(t *testing.T) { reporter.ResetSteps(newTestSteps(1)) reporter.RunDaemon() defer func() { - _ = reporter.Close("") + _ = reporter.Close(nil) }() require.NoError(t, fire(reporter, logEntry{ @@ -394,7 +390,7 @@ func TestReporter_CloseFinalizesLogWithoutRows(t *testing.T) { reporter.state.StoppedAt = timestamppb.Now() reporter.stateMu.Unlock() - require.NoError(t, reporter.Close("")) + require.NoError(t, reporter.Close(nil)) require.Equal(t, int64(1), noMoreCalls.Load(), "Close must send exactly one UpdateLog with NoMore=true") final := lastReq.Load() @@ -436,65 +432,36 @@ func TestReporter_StateHeartbeat(t *testing.T) { } func TestReporter_ServerCancelStillFlushesFinal(t *testing.T) { - var ( - updateTaskCalls atomic.Int64 - finalLogNoMoreSeen atomic.Bool - finalTaskStateSeen atomic.Bool - ) - + const message = "Ended by the server: failure" client := mocks.NewClient(t) - client.On("UpdateLog", mock.Anything, mock.Anything).Return( - func(_ context.Context, req *runnerv1.UpdateLogRequest) (*runnerv1.UpdateLogResponse, error) { - if req.NoMore { - finalLogNoMoreSeen.Store(true) - } - return &runnerv1.UpdateLogResponse{ - AckIndex: req.Index + int64(len(req.Rows)), - }, nil - }, - ) - client.On("UpdateTask", mock.Anything, mock.Anything).Return( - func(_ context.Context, req *runnerv1.UpdateTaskRequest) (*runnerv1.UpdateTaskResponse, error) { - n := updateTaskCalls.Add(1) - if n == 1 { - return &runnerv1.UpdateTaskResponse{ - State: &runnerv1.TaskState{ - Result: runnerv1.Result_RESULT_CANCELLED, - }, - }, nil - } - if req.State != nil && req.State.Result != runnerv1.Result_RESULT_UNSPECIFIED { - finalTaskStateSeen.Store(true) - } - return &runnerv1.UpdateTaskResponse{}, nil - }, - ) - - ctx, cancel := context.WithCancel(t.Context()) - defer cancel() - cfg, _ := config.LoadDefault("") - reporter := NewReporter(ctx, cancel, client, &runnerv1.Task{Context: &structpb.Struct{}}, cfg) - reporter.ResetSteps(newTestSteps(1)) - - reporter.stateMu.Lock() - reporter.stateChanged = true - reporter.stateMu.Unlock() - - require.NoError(t, reporter.ReportState(false)) - require.Equal(t, int64(1), updateTaskCalls.Load()) - - select { - case <-ctx.Done(): - case <-time.After(time.Second): - t.Fatal("expected r.ctx to be cancelled after server returned RESULT_CANCELLED") - } + var lastState *runnerv1.TaskState + client.On("UpdateTask", mock.Anything, mock.Anything).Return(func(ctx context.Context, req *runnerv1.UpdateTaskRequest) (*runnerv1.UpdateTaskResponse, error) { + require.NoError(t, ctx.Err()) + lastState = req.State + return &runnerv1.UpdateTaskResponse{State: &runnerv1.TaskState{Result: runnerv1.Result_RESULT_FAILURE}}, nil + }) + client.On("UpdateLog", mock.Anything, mock.Anything).Return(func(ctx context.Context, req *runnerv1.UpdateLogRequest) (*runnerv1.UpdateLogResponse, error) { + require.NoError(t, ctx.Err()) + require.True(t, req.NoMore) + require.Len(t, req.Rows, 3) + assert.Equal(t, []string{"running", message, "stopped"}, []string{req.Rows[0].Content, req.Rows[1].Content, req.Rows[2].Content}) + return &runnerv1.UpdateLogResponse{AckIndex: int64(len(req.Rows))}, nil + }).Once() + reporter := newTestReporter(t, client, &config.Config{Runner: config.Runner{LogReportLevel: "info"}}) close(reporter.daemon) - - require.NoError(t, reporter.Close("cancelled")) - - assert.True(t, finalLogNoMoreSeen.Load(), "Close() must send a final UpdateLog{NoMore:true} even after server-side cancellation") - assert.True(t, finalTaskStateSeen.Load(), "Close() must send a final UpdateTask with the populated final state even after server-side cancellation") + reporter.ResetSteps(newTestSteps(1)) + step := map[string]any{"stage": runner.StageMain, "stepNumber": 0, "raw_output": true} + require.NoError(t, fire(reporter, logEntry{Message: "running", Data: step})) + require.NoError(t, reporter.ReportState(false)) + require.EqualError(t, context.Cause(reporter.ctx), message) + require.NoError(t, fire(reporter, logEntry{Message: "stopped", Data: step})) + require.NoError(t, fire(reporter, logEntry{Level: logging.LevelDebug, Data: map[string]any{"jobResult": "cancelled"}})) + assert.Equal(t, runnerv1.Result_RESULT_FAILURE, reporter.Result()) + require.NoError(t, reporter.ReportState(false)) + require.NoError(t, reporter.Close(fmt.Errorf("run: %w", context.Cause(reporter.ctx)))) + assert.Equal(t, runnerv1.Result_RESULT_FAILURE, lastState.Result) + assert.EqualValues(t, 3, lastState.Steps[0].LogLength) } func TestReporter_CloseReportsCancelledOnCanceledCtx(t *testing.T) { @@ -522,16 +489,15 @@ func TestReporter_CloseReportsCancelledOnCanceledCtx(t *testing.T) { }, ) - ctx, cancel := context.WithCancel(t.Context()) cfg, _ := config.LoadDefault("") - reporter := NewReporter(ctx, cancel, client, &runnerv1.Task{Context: &structpb.Struct{}}, cfg) + reporter := newTestReporter(t, client, cfg) reporter.ResetSteps(newTestSteps(1)) - cancel() + reporter.cancel(nil) close(reporter.daemon) - require.NoError(t, reporter.Close("")) + require.NoError(t, reporter.Close(nil)) got := finalState.Load() require.NotNil(t, got, "Close() must send a final UpdateTask") @@ -607,7 +573,7 @@ func TestReporter_StopHeartbeats(t *testing.T) { assert.Equal(t, beforeStop, updateTaskCalls.Load(), "UpdateTask must not be called after StopHeartbeats") - require.NoError(t, reporter.Close("")) + require.NoError(t, reporter.Close(nil)) assert.Greater(t, updateTaskCalls.Load(), beforeStop, "Close() must still send a final UpdateTask after StopHeartbeats") }) @@ -646,12 +612,12 @@ func TestReporter_SetOutputs(t *testing.T) { r.SetOutputs(map[string]string{"foo": "baz"}) assert.Equal(t, "bar", r.outputs["foo"].value) - longKey := strings.Repeat("k", maxOutputKeyLen+1) + longKey := strings.Repeat("k", protocol.MaxOutputKeyLength+1) r.SetOutputs(map[string]string{longKey: "v"}) _, ok = r.outputs[longKey] assert.False(t, ok) - longValue := strings.Repeat("v", maxOutputValueLen+1) + longValue := strings.Repeat("v", protocol.MaxOutputValueLength+1) r.SetOutputs(map[string]string{"big": longValue}) _, ok = r.outputs["big"] assert.False(t, ok) @@ -665,10 +631,10 @@ func TestReporter_SetOutputs(t *testing.T) { require.True(t, ok) assert.Equal(t, "caf\xff", got.value) - r.SetOutputs(map[string]string{"atlimit": longValue[:maxOutputValueLen]}) + r.SetOutputs(map[string]string{"atlimit": longValue[:protocol.MaxOutputValueLength]}) got, ok = r.outputs["atlimit"] require.True(t, ok) - assert.Len(t, got.value, maxOutputValueLen) + assert.Len(t, got.value, protocol.MaxOutputValueLength) } func TestReporter_DebugSettingsAreNotMasked(t *testing.T) { @@ -733,8 +699,7 @@ func TestReporter_ParseResult(t *testing.T) { wantOk bool }{ {"job result string", "success", runnerv1.Result_RESULT_SUCCESS, true}, - {"failure string", "failure", runnerv1.Result_RESULT_FAILURE, true}, - {"step result stringer", runnerv1.Result_RESULT_SKIPPED, runnerv1.Result_RESULT_UNSPECIFIED, false}, + {"step result stringer", model.StepStatusSkipped, runnerv1.Result_RESULT_SKIPPED, true}, {"unknown string", "bogus", runnerv1.Result_RESULT_UNSPECIFIED, false}, {"unsupported type", 123, runnerv1.Result_RESULT_UNSPECIFIED, false}, } @@ -840,39 +805,10 @@ func TestReporter_CloseWithStuckDaemon(t *testing.T) { case <-time.After(5 * time.Second): t.Fatal("daemon never reached UpdateLog") } - require.NoError(t, reporter.Close("")) + require.NoError(t, reporter.Close(nil)) }) } -func TestReporter_ServerFailureResultIsReportedAsFailure(t *testing.T) { - var lastState *runnerv1.TaskState - client := mocks.NewClient(t) - client.On("UpdateTask", mock.Anything, mock.Anything).Return(func(_ context.Context, req *runnerv1.UpdateTaskRequest) (*runnerv1.UpdateTaskResponse, error) { - lastState = req.State - return &runnerv1.UpdateTaskResponse{ - State: &runnerv1.TaskState{Result: runnerv1.Result_RESULT_FAILURE}, - }, nil - }) - client.On("UpdateLog", mock.Anything, mock.Anything).Return(func(_ context.Context, req *runnerv1.UpdateLogRequest) (*runnerv1.UpdateLogResponse, error) { - return &runnerv1.UpdateLogResponse{ - AckIndex: req.Index + int64(len(req.Rows)), - }, nil - }).Maybe() - - ctx, cancel := context.WithCancel(t.Context()) - defer cancel() - cfg, _ := config.LoadDefault("") - reporter := NewReporter(ctx, cancel, client, &runnerv1.Task{Context: &structpb.Struct{}}, cfg) - close(reporter.daemon) - - require.NoError(t, reporter.ReportState(false)) - require.ErrorIs(t, ctx.Err(), context.Canceled) - require.NoError(t, reporter.Close("")) - - require.NotNil(t, lastState) - assert.Equal(t, runnerv1.Result_RESULT_FAILURE, lastState.Result) -} - func TestReporter_NoteReport(t *testing.T) { hook := logtest.SetDefault(t) @@ -904,25 +840,19 @@ func TestReporter_CloseMasksLastWords(t *testing.T) { }, nil }, ) - client.On("UpdateTask", mock.Anything, mock.Anything).Return( - func(_ context.Context, _ *runnerv1.UpdateTaskRequest) (*runnerv1.UpdateTaskResponse, error) { - return &runnerv1.UpdateTaskResponse{}, nil - }, - ) + client.On("UpdateTask", mock.Anything, mock.Anything).Return(&runnerv1.UpdateTaskResponse{}, nil) - ctx, cancel := context.WithCancel(t.Context()) - defer cancel() const idToken = "id-token-request-secret" taskCtx, err := structpb.NewStruct(map[string]any{"actions_id_token_request_token": idToken}) require.NoError(t, err) cfg, _ := config.LoadDefault("") - reporter := NewReporter(ctx, cancel, client, &runnerv1.Task{ + reporter := NewReporter(t.Context(), nil, client, &runnerv1.Task{ Context: taskCtx, Secrets: map[string]string{"TOKEN": secret}, }, cfg) close(reporter.daemon) - require.NoError(t, reporter.Close("could not get job matrix: "+secret+" "+idToken)) + require.NoError(t, reporter.Close(fmt.Errorf("could not get job matrix: %s %s", secret, idToken))) require.Len(t, rows, 1) assert.Equal(t, "could not get job matrix: *** ***", rows[0].Content) @@ -983,7 +913,7 @@ func TestReporter_StepRangeCoversAckedRows(t *testing.T) { reporter.ResetSteps(newTestSteps(1)) reporter.RunDaemon() defer func() { - _ = reporter.Close("") + _ = reporter.Close(nil) }() stepData := map[string]any{"stage": "Main", "stepNumber": 0, "raw_output": true} @@ -1027,8 +957,8 @@ func TestReporter_FlushWithoutAckedRowsSkipsState(t *testing.T) { func newTestReporter(t *testing.T, client *mocks.Client, cfg *config.Config) *Reporter { t.Helper() - ctx, cancel := context.WithCancel(t.Context()) - t.Cleanup(cancel) + ctx, cancel := context.WithCancelCause(t.Context()) + t.Cleanup(func() { cancel(nil) }) return NewReporter(ctx, cancel, client, &runnerv1.Task{Context: &structpb.Struct{}}, cfg) } @@ -1041,14 +971,14 @@ func newTestSteps(n int) []*model.Step { } func TestReporter_ReportedSteps(t *testing.T) { - newReporter := func(t *testing.T, steps []*model.Step) (*Reporter, context.CancelFunc) { + newReporter := func(t *testing.T, steps []*model.Step) (*Reporter, context.CancelCauseFunc) { client := mocks.NewClient(t) client.On("UpdateLog", mock.Anything, mock.Anything).Maybe().Return(func(_ context.Context, req *runnerv1.UpdateLogRequest) (*runnerv1.UpdateLogResponse, error) { return &runnerv1.UpdateLogResponse{AckIndex: req.Index + int64(len(req.Rows))}, nil }) client.On("UpdateTask", mock.Anything, mock.Anything).Maybe().Return(&runnerv1.UpdateTaskResponse{}, nil) cfg, _ := config.LoadDefault("") - ctx, cancel := context.WithCancel(t.Context()) + ctx, cancel := context.WithCancelCause(t.Context()) reporter := NewReporter(ctx, cancel, client, &runnerv1.Task{Context: &structpb.Struct{}, Secrets: map[string]string{"TOKEN": "s3cr3t"}}, cfg) reporter.RunDaemon() reporter.Logf("runner version") @@ -1123,7 +1053,7 @@ func TestReporter_ReportedSteps(t *testing.T) { assert.Equal(t, want, reportedOf(t, reporter)) send(t, reporter, logging.LevelInfo, "Removing images", map[string]any{"stage": runner.StageComplete}) - require.NoError(t, reporter.Close("")) + require.NoError(t, reporter.Close(nil)) want[5].result, want[5].logLen = success, 3 assert.Equal(t, want, reportedOf(t, reporter)) @@ -1156,8 +1086,8 @@ func TestReporter_ReportedSteps(t *testing.T) { send(t, reporter, logging.LevelInfo, "main output", map[string]any{"stage": runner.StageMain, "stepNumber": 1, "raw_output": true}) send(t, reporter, logging.LevelInfo, "Run Post echo 0", started(runner.StagePost, 0)) send(t, reporter, logging.LevelInfo, "Failure - Post echo 0", result(runner.StagePost, 0, model.StepStatusFailure)) - cancel() - require.NoError(t, reporter.Close("")) + cancel(nil) + require.NoError(t, reporter.Close(nil)) results := make(map[string]runnerv1.Result) for _, v := range reportedOf(t, reporter) { @@ -1184,7 +1114,7 @@ func TestReporter_ReportedSteps(t *testing.T) { reporter, _ := newReporter(t, newTestSteps(1)) reporter.Logf("workflow prepared") send(t, reporter, logging.LevelInfo, "Job failed", map[string]any{"jobResult": model.StepStatusFailure}) - require.NoError(t, reporter.Close("")) + require.NoError(t, reporter.Close(nil)) assert.Equal(t, []reported{ {setup, 0, "Set up job", failure, 0, 3}, @@ -1199,7 +1129,7 @@ func TestReporter_ReportedSteps(t *testing.T) { send(t, reporter, logging.LevelError, "##[error]unable to clone 'invalid-owner/invalid-action'", nil) send(t, reporter, logging.LevelInfo, "Cleaning up container", map[string]any{"stage": runner.StageComplete}) send(t, reporter, logging.LevelInfo, "Job failed", map[string]any{"stage": runner.StageComplete, "jobResult": model.StepStatusFailure}) - require.NoError(t, reporter.Close("")) + require.NoError(t, reporter.Close(nil)) got := reportedOf(t, reporter) assert.Equal(t, []runnerv1.Result{failure, skipped, success}, []runnerv1.Result{got[0].result, got[1].result, got[2].result}) @@ -1209,7 +1139,7 @@ func TestReporter_ReportedSteps(t *testing.T) { reporter, _ := newReporter(t, newTestSteps(1)) send(t, reporter, logging.LevelError, "##[error]job completed hook failed", map[string]any{"stage": runner.StageComplete}) send(t, reporter, logging.LevelInfo, "Job failed", map[string]any{"stage": runner.StageComplete, "jobResult": model.StepStatusFailure}) - require.NoError(t, reporter.Close("")) + require.NoError(t, reporter.Close(nil)) step := reporter.state.ReportedSteps[len(reporter.state.ReportedSteps)-1] assert.Equal(t, failure, step.Result) @@ -1220,7 +1150,7 @@ func TestReporter_ReportedSteps(t *testing.T) { t.Run("step not reached in a succeeding job", func(t *testing.T) { reporter, _ := newReporter(t, newTestSteps(1)) send(t, reporter, logging.LevelInfo, "Job succeeded", map[string]any{"stage": runner.StageComplete, "jobResult": model.StepStatusSuccess}) - require.NoError(t, reporter.Close("")) + require.NoError(t, reporter.Close(nil)) assert.Equal(t, skipped, reportedOf(t, reporter)[1].result) }) @@ -1231,7 +1161,7 @@ func TestReporter_ReportedSteps(t *testing.T) { reporter, _ := newReporter(t, steps) send(t, reporter, logging.LevelDebug, "Run Main", map[string]any{"stage": runner.StageMain, "stepNumber": 0, "step": "echo linux\necho more"}) send(t, reporter, logging.LevelDebug, "Run Main", map[string]any{"stage": runner.StageMain, "stepNumber": 1, "step": "Deploy with s3cr3t"}) - require.NoError(t, reporter.Close("")) + require.NoError(t, reporter.Close(nil)) names := []string{} for _, v := range reportedOf(t, reporter) { @@ -1244,7 +1174,7 @@ func TestReporter_ReportedSteps(t *testing.T) { reporter, _ := newReporter(t, nil) send(t, reporter, logging.LevelInfo, "Cleaning up container", map[string]any{"stage": runner.StageComplete}) send(t, reporter, logging.LevelInfo, "Job succeeded", map[string]any{"stage": runner.StageComplete, "jobResult": model.StepStatusSuccess}) - require.NoError(t, reporter.Close("")) + require.NoError(t, reporter.Close(nil)) assert.Empty(t, reportedOf(t, reporter)) }) } diff --git a/scripts/run.sh b/scripts/run.sh index 2f315bf8..24af4d30 100755 --- a/scripts/run.sh +++ b/scripts/run.sh @@ -1,53 +1,26 @@ #!/usr/bin/env bash -if [[ ! -d /data ]]; then - mkdir -p /data -fi +mkdir -p /data +cd /data || exit 1 -cd /data - -CONFIG_ARG="" -if [[ ! -z "${CONFIG_FILE}" ]]; then - CONFIG_ARG="--config ${CONFIG_FILE}" -fi -RUNNER_STATE_FILE=${RUNNER_STATE_FILE:-$(gitea-runner ${CONFIG_ARG} config runner-file)} -LABEL_ARGS="" -if [[ ! -z "${GITEA_RUNNER_LABELS}" ]]; then - LABEL_ARGS="--labels ${GITEA_RUNNER_LABELS}" -fi -EXTRA_ARGS="${LABEL_ARGS}" -if [[ ! -z "${GITEA_RUNNER_EPHEMERAL}" ]]; then - EXTRA_ARGS="${EXTRA_ARGS} --ephemeral" -fi -# Also pass the labels to the daemon, so that an already registered runner -# picks up changes to GITEA_RUNNER_LABELS instead of keeping the labels it -# was first registered with. -RUN_ARGS="${LABEL_ARGS}" -if [[ ! -z "${GITEA_RUNNER_ONCE}" ]]; then - RUN_ARGS="${RUN_ARGS} --once" -fi - -# In case no token is set, it's possible to read the token from a file, i.e. a Docker Secret -if [[ -z "${GITEA_RUNNER_REGISTRATION_TOKEN}" ]] && [[ -f "${GITEA_RUNNER_REGISTRATION_TOKEN_FILE}" ]]; then - GITEA_RUNNER_REGISTRATION_TOKEN=$(cat "${GITEA_RUNNER_REGISTRATION_TOKEN_FILE}") -fi +runner_args=(--config "$CONFIG_FILE") +RUNNER_STATE_FILE=${RUNNER_STATE_FILE:-$(gitea-runner "${runner_args[@]}" config runner-file)} # Use the same ENV variable names as https://github.com/vegardit/docker-gitea-act-runner test -f "$RUNNER_STATE_FILE" || echo "$RUNNER_STATE_FILE is missing or not a regular file" if [[ ! -s "$RUNNER_STATE_FILE" ]]; then + register_args=("${runner_args[@]}" --instance "$GITEA_INSTANCE_URL" --name "$GITEA_RUNNER_NAME" --labels "$GITEA_RUNNER_LABELS" + --no-interactive ${GITEA_RUNNER_EPHEMERAL:+--ephemeral}) + if [[ -z $GITEA_RUNNER_REGISTRATION_TOKEN && -f $GITEA_RUNNER_REGISTRATION_TOKEN_FILE ]]; then + register_args+=(--token-file "$GITEA_RUNNER_REGISTRATION_TOKEN_FILE") + fi for ((try = 1; ; try++)); do # waits for Gitea like the daemon does, a container may have no restart policy - gitea-runner register \ - --instance "${GITEA_INSTANCE_URL}" \ - --token "${GITEA_RUNNER_REGISTRATION_TOKEN}" \ - --name "${GITEA_RUNNER_NAME:-`hostname`}" \ - ${CONFIG_ARG} ${EXTRA_ARGS} --no-interactive 2>&1 | tee /tmp/reg.log - - if grep -q 'Runner registered successfully' /tmp/reg.log; then + if gitea-runner register "${register_args[@]}" 2>&1; then echo "SUCCESS" break fi - if [[ ${GITEA_MAX_REG_ATTEMPTS:-0} -gt 0 ]] && [[ $try -ge $GITEA_MAX_REG_ATTEMPTS ]]; then + if [[ ${GITEA_MAX_REG_ATTEMPTS:-0} -gt 0 && $try -ge $GITEA_MAX_REG_ATTEMPTS ]]; then echo "Registration failed after ${try} attempts" exit 1 fi @@ -56,7 +29,6 @@ if [[ ! -s "$RUNNER_STATE_FILE" ]]; then done fi # Prevent reading the token from the gitea-runner process -unset GITEA_RUNNER_REGISTRATION_TOKEN -unset GITEA_RUNNER_REGISTRATION_TOKEN_FILE +unset GITEA_RUNNER_REGISTRATION_TOKEN GITEA_RUNNER_REGISTRATION_TOKEN_FILE -exec gitea-runner daemon ${CONFIG_ARG} ${RUN_ARGS} +exec gitea-runner daemon "${runner_args[@]}" ${GITEA_RUNNER_ONCE:+--once}