Skip to content

Feat/retry k8s api calls 2.338 - #63

Closed
KadenZhang3321 wants to merge 88 commits into
mainfrom
feat/retry-k8s-api-calls-2.338
Closed

KadenZhang3321 wants to merge 88 commits into
mainfrom
feat/retry-k8s-api-calls-2.338

Conversation

@KadenZhang3321

Copy link
Copy Markdown
Collaborator

描述

相关 Issue

变更类型

  • Bug 修复
  • 新功能
  • 代码重构
  • 文档更新
  • 样式改进
  • 性能优化
  • 测试相关
  • 其他

Goalina and others added 30 commits October 14, 2025 15:01
…s#263)

* Change command to copy externals instead of move

* fix: using only mv, remove sudo
* Sort 'find' output before hashing for consistency across different platforms

* fix style issues
* feat: check if required binaries are present

Previously the necessary binaries were copied over using the runner
container. This lead to issues in case your main container was using the
musl libc implementation.

Instead of copying over any binaries, the initContainer now checks if
the required binaries are present in the main container.

* feat: get rid of the init container

* fix: add _runner_file_commands

* fix: do not fail if _runner_file_commands does not exist

It seems that for container actions this directory does not exist.
* Allow non-root container

* format

* add lint:fix and fix lint errors

* fix tests and volume mounts
* fix: calculate hash again after failure

The hash from the source is calculated only once. The source hash is
checked with the destination hash, but if the destination hash does not
match, the destination match is calculated again.

The problem is that if the source hash is incorrect, the check will keep
failing because the source hash is never re-calculated.

Now, in the event that the hashes do not match, the hash of the source
and the destination are calculated again.

* fix: use size instead of block size

Previously the %b parameter was used with stat. This displays the block
size of the file. We noticed that in some cases the block size of the
source and the destination file could be slightly different. Since the
source and target run in different containers, they can have different
block sizes defined. If the block size did not match, the hash would also not match, even if
the file content would be exactly the same.

With this change, the block size is no longer used. Instead the actual
size in bytes of the file is listed.
…actions#283)

* Fix workingDir permissions issue by creating it within init container

* Apply suggestion from @Copilot

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* rework init commands

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
…olume mode (actions#287)

In run-script-step, the _temp directory was being copied to the workflow pod,
but the _github_home and _github_workflow directories were not being moved
from their temporary location to the /github directory structure where they
are expected by GitHub Actions.

This caused event.json to be missing at /github/workflow/event.json, breaking
actions that depend on GITHUB_EVENT_PATH.

The fix adds a setup step that copies _github_home and _github_workflow from
/__w/_temp/ to /github/ after copying the temp directory to the pod, matching
the behavior of run-container-step and prepareJobScript.

Uses cp -r instead of symlinks to avoid symlink validation errors when copying
files back from the pod to the runner.
When a CI job references a non-existent image or one it lacks permission
to pull, the pod stays in Pending and waitForPodPhases previously timed
out with only a generic phase-status message. GitHub Actions users had
no indication of the real cause.

Detect unrecoverable container waiting reasons (ImagePullBackOff,
ErrImagePull, InvalidImageName, CreateContainerConfigError,
CreateContainerError) on both init and regular containers, and fail fast
with the container name, reason, and Kubernetes message so the error is
visible in the Actions log.

Refactor getPodPhase into readPod + parsePodPhase so the pod object can
be inspected for container errors, and add unit tests covering
parsePodPhase, getContainerErrors, and waitForPodPhases.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
…r reasons

Extend the error feedback mechanism introduced in the previous commit with:

- describePodFailure(): aggregates pod phase, conditions, container statuses
  and Warning events into a single human-readable diagnostic string.
  Never throws — safe to call from any error path.

- describePodWarningEvents(): best-effort retrieval of recent Warning K8s
  events (requires optional "events" RBAC permission). Degrades gracefully
  when the permission is missing.

- getUnrecoverableWaitingReasons(): allows operators to extend the built-in
  fast-fail whitelist via the ACTIONS_RUNNER_K8S_UNRECOVERABLE_WAITING_REASONS
  environment variable without a code change. Built-in defaults cannot be
  removed.

- All three failure paths in waitForPodPhases now attach full diagnostics:
  1. Non-backoff phase (e.g. Failed) — includes pod details + events
  2. Unrecoverable container error (e.g. ImagePullBackOff) — fail-fast with
     diagnostics instead of waiting for timeout
  3. Timeout — includes pod details so the user can see WHY the pod never
     became ready

- README: document the optional "events" permission and the new env var.

- Tests: 8 new test cases (19 total) covering describePodFailure,
  describePodWarningEvents, getUnrecoverableWaitingReasons, and edge cases
  such as forbidden events API and unreadable pods.
The project pins prettier@2.6.2 in package-lock.json, but the previous
commit was formatted with prettier 3.x which has different line-wrapping
rules for template literals. Re-format with prettier 2.6.2 to pass CI.
v2.329.0 was deprecated by GitHub and rejected at the broker level with
"Runner version v2.329.0 is deprecated and cannot receive messages.",
causing runner pods to crash-loop immediately after connecting.

Also fix Dockerfile layer ordering: switch to root before COPY so that
the subsequent chown is not run as the unprivileged runner user.

Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>
- namespace() now reads /var/run/secrets/kubernetes.io/serviceaccount/namespace
  as fallback when kubeconfig context has no namespace (in-cluster ARC setup)
- Dockerfile: add --platform=linux/amd64 to runner base image stage

Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>
The release/no_volumes base uses @kubernetes/client-node v0.22+ where
API methods take an options object and return the resource directly
(no .body wrapper). Fix describePodWarningEvents() accordingly.

Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>
- Remove --platform=linux/amd64: Jenkins build host is aarch64,
  without the flag the final image is ARM64, matching the working
  release/no_volumes build
- Revert to ghcr.io/actions/actions-runner:2.334.0 (same as
  release/no_volumes); the nju.edu.cn mirror at 2.335.1 caused
  silent 0-second exit with no logs (likely corrupted/wrong image)
- Remove USER root + chown (not needed, matches release/no_volumes)
- Update nodeSelector to arm64 to match ARM64 image architecture

Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>
- describePodFailure(): skip container waiting reasons already in
  UNRECOVERABLE_WAITING_REASONS (they appear in the caller's first
  line via getContainerErrors, printing them again is redundant)
- describePodFailure(): suppress terminated containers with exitCode=0
  (e.g. fs-init Completed) -- successful init containers are noise
- Add tao/ to .gitignore; remove accidentally committed values file

Result: InvalidImageName/ErrImagePull now shows as one clean block:
  Pod <name> has unrecoverable container errors: container "job": ErrImagePull - <message>
  Phase: Pending
  Condition Ready=False ...

Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>
Layer the error output into clearly separated sections:

  Pod <name> has unrecoverable container errors:
    ✗ container "job": ErrImagePull
      Error response from daemon: manifest for ... not found
  ────────────────────────────────────────────────────────────
  Pod status: Pending
    ✗ Ready=False (ContainersNotReady): containers with ...
    ✗ ContainersReady=False (ContainersNotReady): ...

  Recent warning events:
    [Failed] (x3) Error response from daemon: ...

Changes:
- getContainerErrors(): format each entry as indented ✗ lines with
  message detail on a separate indented line
- describePodFailure(): group output into sections (pod status,
  container details, warning events) separated by blank lines
- waitForPodPhases(): add ─── separator between summary and details
- describePodWarningEvents(): indent event lines consistently

Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>
- prepare-job.ts: use err.message instead of String(err) to avoid
  double "Error: Error:" prefix; change separator to newline so the
  multi-section detail block renders on its own lines:
    pod failed to come online:
    Pod <name> has unrecoverable container errors:
      ✗ container "job": ErrImagePull
        <message>
    ────────────────────────────────────
    Pod status: Pending
      ✗ Ready=False ...
- .gitignore: fix corrupted line (tao/ was appended without newline
  to test-kind.yaml entry); restore original content, drop tao/
  (the values file should not be tracked in this repo)
- Dockerfile: restore to byte-identical match with release/no_volumes
  (only had trailing-newline diff, no content change)

Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>
Add event-based fast-fail detection alongside the existing container
waiting-reason check in waitForPodPhases().

Problem: some failures never surface in container.status.state.waiting
.reason — the container stays stuck in ContainerCreating — so the hook
polled until the 3600s timeout. Examples:
  - FailedMount: hostPath directory missing, missing Secret/ConfigMap volume
  - FailedScheduling: no schedulable node (resource/nodeSelector/affinity)
  - FailedBinding: PVC cannot bind (no PV, wrong storageClass)

Changes:
- UNRECOVERABLE_EVENT_REASONS: new exported Set with the three reasons above
- getUnrecoverableEventReasons(): mirrors getUnrecoverableWaitingReasons(),
  extended at runtime via ACTIONS_RUNNER_K8S_UNRECOVERABLE_EVENT_REASONS
  env var (comma-separated, additive)
- getPodEventErrors(): queries the event API for Warning events whose
  reason is in the unrecoverable set; deduplicates by reason; gracefully
  degrades to [] when the optional events RBAC permission is missing
- waitForPodPhases(): call getPodEventErrors() alongside getContainerErrors()
  each poll; fail fast when either returns results
- Error message updated: "unrecoverable container errors" →
  "unrecoverable errors" to cover both detection paths
- Tests: add coverage for FailedMount/FailedScheduling/FailedBinding event
  detection, env-var extension, RBAC degradation, and deduplication

Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>
…rors

The k8s client throws HttpException with a multi-line message:
  HTTP-Code: 422
  Message: Unknown API Status Code!
  Body: "{\"message\":\"Pod is invalid: ...\"}"

Parse the "message" field from the embedded JSON body so the log shows:
  failed to create job pod:
    Pod "xxx" is invalid: spec.volumes[5].name: Duplicate value: "bad-hostpath"

Falls back to the raw string if parsing fails (e.g. non-422 errors or
network errors that don't have a JSON body).

Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>
Longwt123 and others added 16 commits July 13, 2026 11:59
- pod-side sync: append '2>/dev/null || true' so that missing or
  restricted sync binary in minimal/distroless images does not cause
  the entire tar+chmod sh -c command to fail with a non-zero exit code
- runner-side sync: remove the spawn('sync') call entirely; it was
  made redundant by the writerStream 'finish' event fix (222a63b)
  which already guarantees all tar-fs writes are flushed to disk
  before the hash verification loop starts

Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>
…e data durability

fix(k8s): PostCheckout复制时不匹配反复重试add sync after file copy to ensure data durability
…n failures

When prepareJob fails (pod creation/startup fails), state.jobPod is not
initialized. Subsequent runScriptStep attempts to access null.jobPod,
causing TypeError: Cannot read properties of null.

This fix adds early validation to throw a clear error when jobPod is null,
indicating that prepareJob failed. This prevents cryptic null reference
errors and improves debugging.

- Add null/undefined check at runScriptStep entry point
- Add test cases for null and undefined jobPod scenarios
- Error message clearly indicates prepareJob dependency
…ation failures

fix: add null check for jobPod in runScriptStep to handle pod creation failures
- prepare-job: format 422 pod creation errors with consistent header,
  separator, and actionable troubleshooting hints matching the
  unrecoverable-errors output style.
- k8s/index.ts: include getContainerTerminatedErrors in
  checkUnrecoverableErrors so OOMKilled / non-zero exit failures are
  reported with their hints during waitForPodPhases. When phase=Failed
  and terminated errors exist, the error now uses the
  "has unrecoverable errors" format instead of the generic
  "is unhealthy" message.
Address code review feedback:
- prepare-job.ts: refactor 422 error from single long line to array of
  strings joined by \n for readability and ESLint max-len compliance.
- Replace Unicode box-drawing character (U+2500) with standard hyphens
  across all hooks (prepare-job, index, run-script-step, run-container-step)
  for consistent rendering across terminal emulators and log aggregators.
…container hints

fix(k8s): 统一错误格式并优化提示信息unify error format and surface terminated container hints
ImagePullBackOff was in UNRECOVERABLE_WAITING_REASONS, so the hook failed
the job the moment it appeared (~2nd kubelet pull attempt). During a
transient network outage this killed jobs that would have recovered.

ImagePullBackOff/ErrImagePull now get a bounded grace window (default 300s,
configurable via ACTIONS_RUNNER_K8S_IMAGE_PULL_GRACE_SECONDS): the pull can
self-heal within it, and the hook fails only once the window is exceeded
without recovery. Waiting messages that positively identify a permanent
cause (manifest not found, pull access denied, unauthorized, repository
does not exist, ...) still fail immediately.

Setting grace to 0 restores the previous instant-fail behavior.

Co-Authored-By: Claude <noreply@anthropic.com>
… fail

fix(k8s): grace period for image pull failures instead of instant fail
Trivy scan on PR #42 flagged js-yaml 4.3.0 with quadratic CPU consumption vulnerability in !!omap resolution (CVE-2026-59870). Upgrade to 4.3.1.
The runner pod talks to the in-cluster API through a per-node ClusterIP
rule; every time the managed apiserver endpoints rotate, that path opens
sub-second windows of ECONNREFUSED / connection hangs / momentary 403s.
The hook's isAuthPermissionsOK() preflight fired 13 parallel, untimed,
non-retried SelfSubjectAccessReviews before EVERY step, so a single
window aborted whole CI jobs with 'custom container implementation
failed' (see ascend-gha-runners/docs#274).

Add a reusable retryK8sApiCall(): bounded retries with exponential
backoff and a per-attempt timeout for transient network/401/403/429/5xx
errors. Also give each SAR request its own body object so a retried
call never re-submits a body mutated by the outer loop.
@opensourceways-bot

Copy link
Copy Markdown

Welcome To opensourceways Community

Hey @KadenZhang3321 , thanks for your contribution to the community.

Bot Usage Manual

I'm the Bot here serving you. You can find the instructions on how to interact with me at Here . That means you can comment below every pull request or issue to trigger Bot Commands.

Contact Guide

If you have any questions, please contact the SIG: infratructure ,
and any of the maintainers: @GeorgeCao-hw, @TangJia025, @pkking, @zhongjun2 ,
and any of the committers: @GeorgeCao-hw, @Goalina, @Hourunze1997, @JavaPythonAIForBAT, @KadenZhang3321, @LiYanghang00, @ccijunk, @drizzlezyk, @pkking, @rosecoffe, @tfhddd, @yao-xiaobai, @zhongjun2, @zkhzkhz .

@opensourceways-bot

Copy link
Copy Markdown

CLA Signature Guide

@KadenZhang3321 , thanks for your pull request.

The following commit(s) are not associated with a signed Contributor License Agreement (CLA).

Commit Reason
ea25fd1b Change command to remove sudo to... the email used in the commit is not linked to a signed CLA!
please verify that it matches the email you used when signing the CLA.
2934de33 Sort 'find' output before hashin... the email used in the commit is an invalid email!
please check all commits.
ad9cb43c feat: check if required binaries... the email used in the commit is not linked to a signed CLA!
please verify that it matches the email you used when signing the CLA.
15e80893 Allow non-root container (#264) ... the email used in the commit is not linked to a signed CLA!
please verify that it matches the email you used when signing the CLA.
0951cc73 Improve validation checks after ... the email used in the commit is not linked to a signed CLA!
please verify that it matches the email you used when signing the CLA.
a8f7515b feat(k8s): ride through transien... the email used in the commit is an invalid email!
please check all commits.

To sign CLA, click here.

To check if your email is configured correctly, refer to the FAQs.

Once you've signed the CLA or updating your email, please comment /check-cla to revalidate CLA status.

@opensourceways-bot

Copy link
Copy Markdown

Linking Issue Notice

@KadenZhang3321 , the pull request must be linked to at least one issue.
If an issue has already been linked, but the needs-issue label remains, you can remove the label by commenting /check-issue .

@opensourceways-bot

Copy link
Copy Markdown
检查项 状态
敏感信息扫描 ✅
安全编码扫描 ✅
漏洞扫描 ❌
开源license合规扫描 ✅
UT测试覆盖率 ❌
开发阶段设计文档检查 ❌
流水线链接 点击跳转查看日志

@opensourceways-bot

Copy link
Copy Markdown

CLA Signature Guide

@KadenZhang3321 , thanks for your pull request.

The following commit(s) are not associated with a signed Contributor License Agreement (CLA).

Commit Reason
ea25fd1b Change command to remove sudo to... the email used in the commit is not linked to a signed CLA!
please verify that it matches the email you used when signing the CLA.
2934de33 Sort 'find' output before hashin... the email used in the commit is an invalid email!
please check all commits.
ad9cb43c feat: check if required binaries... the email used in the commit is not linked to a signed CLA!
please verify that it matches the email you used when signing the CLA.
15e80893 Allow non-root container (#264) ... the email used in the commit is not linked to a signed CLA!
please verify that it matches the email you used when signing the CLA.
0951cc73 Improve validation checks after ... the email used in the commit is not linked to a signed CLA!
please verify that it matches the email you used when signing the CLA.
a8f7515b feat(k8s): ride through transien... the email used in the commit is an invalid email!
please check all commits.

To sign CLA, click here.

To check if your email is configured correctly, refer to the FAQs.

Once you've signed the CLA or updating your email, please comment /check-cla to revalidate CLA status.

@opensourceways-bot

Copy link
Copy Markdown
检查项 状态
敏感信息扫描 ✅
安全编码扫描 ✅
漏洞扫描 ❌
开源license合规扫描 ✅
UT测试覆盖率 ❌
开发阶段设计文档检查 ❌
流水线链接 点击跳转查看日志

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.