Compare commits

..
Author SHA1 Message Date
copilot-swe-agent[bot]andnikola-jokic 5f503f27d3 Update package-lock.json after dependency updates
Co-authored-by: nikola-jokic <[email protected]>
2025-12-11 14:27:55 +00:00
copilot-swe-agent[bot] 287a0458a1 Initial plan 2025-12-11 14:19:39 +00:00
dependabot[bot]andGitHub b8af7ebe0e Bump the all-dependencies group in /packages/docker with 6 updates
Bumps the all-dependencies group in /packages/docker with 6 updates:

| Package | From | To |
| --- | --- | --- |
| [@actions/exec](https://github.com/actions/toolkit/tree/HEAD/packages/exec) | `1.1.1` | `2.0.0` |
| [uuid](https://github.com/uuidjs/uuid) | `11.1.0` | `13.0.0` |
| [@babel/core](https://github.com/babel/babel/tree/HEAD/packages/babel-core) | `7.28.4` | `7.28.5` |
| [@babel/preset-env](https://github.com/babel/babel/tree/HEAD/packages/babel-preset-env) | `7.28.3` | `7.28.5` |
| [@typescript-eslint/parser](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/parser) | `8.45.0` | `8.49.0` |
| [ts-jest](https://github.com/kulshekhar/ts-jest) | `29.4.4` | `29.4.6` |


Updates `@actions/exec` from 1.1.1 to 2.0.0
- [Changelog](https://github.com/actions/toolkit/blob/main/packages/exec/RELEASES.md)
- [Commits](https://github.com/actions/toolkit/commits/HEAD/packages/exec)

Updates `uuid` from 11.1.0 to 13.0.0
- [Release notes](https://github.com/uuidjs/uuid/releases)
- [Changelog](https://github.com/uuidjs/uuid/blob/main/CHANGELOG.md)
- [Commits](https://github.com/uuidjs/uuid/compare/v11.1.0...v13.0.0)

Updates `@babel/core` from 7.28.4 to 7.28.5
- [Release notes](https://github.com/babel/babel/releases)
- [Changelog](https://github.com/babel/babel/blob/main/CHANGELOG.md)
- [Commits](https://github.com/babel/babel/commits/v7.28.5/packages/babel-core)

Updates `@babel/preset-env` from 7.28.3 to 7.28.5
- [Release notes](https://github.com/babel/babel/releases)
- [Changelog](https://github.com/babel/babel/blob/main/CHANGELOG.md)
- [Commits](https://github.com/babel/babel/commits/v7.28.5/packages/babel-preset-env)

Updates `@typescript-eslint/parser` from 8.45.0 to 8.49.0
- [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases)
- [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/parser/CHANGELOG.md)
- [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v8.49.0/packages/parser)

Updates `ts-jest` from 29.4.4 to 29.4.6
- [Release notes](https://github.com/kulshekhar/ts-jest/releases)
- [Changelog](https://github.com/kulshekhar/ts-jest/blob/main/CHANGELOG.md)
- [Commits](https://github.com/kulshekhar/ts-jest/compare/v29.4.4...v29.4.6)

---
updated-dependencies:
- dependency-name: "@actions/exec"
  dependency-version: 2.0.0
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: all-dependencies
- dependency-name: uuid
  dependency-version: 13.0.0
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: all-dependencies
- dependency-name: "@babel/core"
  dependency-version: 7.28.5
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: all-dependencies
- dependency-name: "@babel/preset-env"
  dependency-version: 7.28.5
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: all-dependencies
- dependency-name: "@typescript-eslint/parser"
  dependency-version: 8.49.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: all-dependencies
- dependency-name: ts-jest
  dependency-version: 29.4.6
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: all-dependencies
...

Signed-off-by: dependabot[bot] <[email protected]>
2025-12-10 20:51:03 +00:00
22 changed files with 2010 additions and 2026 deletions
+2 -14
View File
@@ -13,11 +13,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- uses: actions/setup-node@v6
with:
node-version: 24
cache: npm
- run: npm ci
- run: npm install
name: Install dependencies
- run: npm run bootstrap
name: Bootstrap the packages
@@ -36,11 +32,7 @@ jobs:
needs: format-and-lint
steps:
- uses: actions/checkout@v5
- uses: actions/setup-node@v6
with:
node-version: 24
cache: npm
- run: npm ci
- run: npm install
name: Install dependencies
- run: npm run bootstrap
name: Bootstrap the packages
@@ -55,10 +47,6 @@ jobs:
needs: format-and-lint
steps:
- uses: actions/checkout@v5
- uses: actions/setup-node@v6
with:
node-version: 24
cache: npm
- run: sed -i "s|{{PATHTOREPO}}|$(pwd)|" packages/k8s/tests/test-kind.yaml
name: Setup kind cluster yaml config
- uses: helm/[email protected]
-4
View File
@@ -12,10 +12,6 @@ jobs:
steps:
- uses: actions/checkout@v5
- uses: actions/setup-node@v6
with:
node-version: 24
cache: npm
- name: Install dependencies
run: npm install
-55
View File
@@ -1,55 +0,0 @@
# ADR 0135: RWX volume strategy and RWO affinity fallback
**Date:** 22 April 2026
**Status**: Accepted
## Context
The Kubernetes hook implementation for GitHub Actions runners requires access to the runner's working directory (`_work`) within the dynamically created job pods. This shared access is typically managed via Persistent Volume Claims (PVCs).
The choice of storage strategy significantly impacts pod scheduling. While ReadWriteOnce (RWO) volumes require job pods to be co-located on the same node as the runner pod, ReadWriteMany (RWX) volumes allow job pods to be scheduled freely across the cluster.
Depending on the storage provider and cluster configuration, operators may choose between `ReadWriteMany` (RWX) or `ReadWriteOnce` (RWO) access modes. RWX is preferred because it allows the Kubernetes scheduler to place job pods on any available node, improving resource utilization and cluster flexibility. RWO restricts volume access to a single node at a time, requiring all pods using the volume to be pinned to that specific node.
## Decision
We have decided to establish `ReadWriteMany` (RWX) as the preferred storage strategy for the Kubernetes hook. RWX provides superior operational flexibility by enabling free scheduling of job pods across the cluster, as the shared volume is accessible from any node. This decoupling of job pods from the runner's node allows for better resource distribution and reduces the risk of node-level resource exhaustion.
For environments where RWX is unavailable or undesirable, we support a `ReadWriteOnce` (RWO) fallback strategy. This fallback is implemented using node affinity to ensure that job pods are scheduled onto the same node as the runner pod that holds the RWO volume.
### Operational Guidance
1. **Preferred Model (RWX):** Operators should configure the runner with a PVC supporting `ReadWriteMany`.
2. **Fallback Model (RWO):** If using `ReadWriteOnce`, the Kubernetes scheduler integration is enabled by default. Operators can optionally disable it by setting `ACTIONS_RUNNER_DISABLE_KUBE_SCHEDULER=true` (not recommended).
3. **Node Selection:** By default, the hook applies a `requiredDuringSchedulingIgnoredDuringExecution` node affinity targeting the runner's current node (`kubernetes.io/hostname`).
4. **Implementation Details:**
- The hook determines the node name via `getCurrentNodeName()` and applies affinity in `packages/k8s/src/k8s/index.ts` (lines 101, 165).
- The scheduler is enabled by default. Setting `ACTIONS_RUNNER_DISABLE_KUBE_SCHEDULER=true` disables it, as defined in `packages/k8s/src/k8s/utils.ts` (line 16).
- The PVC claim name defaults to `${ACTIONS_RUNNER_POD_NAME}-work` unless overridden by `ACTIONS_RUNNER_CLAIM_NAME` (`packages/k8s/src/hooks/constants.ts`, lines 27-33).
### Non-Recommendations
We explicitly do **not** recommend the use of `spec.nodeName` for operator-driven scheduling. While the hook uses `nodeName` as a legacy fallback when `ACTIONS_RUNNER_DISABLE_KUBE_SCHEDULER` is set to `true` (`packages/k8s/src/k8s/index.ts`, lines 103, 167), this bypasses the Kubernetes scheduler and can lead to scheduling failures or resource imbalances. Operators should prefer the default affinity-based approach for RWO volumes.
## Alternatives
- **nodeName Bypass:** Directly setting `nodeName` bypasses the scheduler entirely. This was rejected as a recommendation because it prevents the scheduler from accounting for taints, tolerations, and resource pressure.
- **Local Volumes:** Using local volumes tied to specific nodes. This is a subset of the RWO fallback and is supported via the affinity mechanism.
## Consequences
- **Flexibility:** RWX users benefit from the ability to schedule job pods on any node in the cluster, maximizing resource utilization.
- **Node Coupling:** RWO users remain coupled to the node where the runner pod is running. The hook ensures job pods are scheduled on the same node via affinity (enabled by default) to maintain workspace integrity.
- **Configuration:** Operators using RWO can rely on the default affinity-based scheduling. Setting `ACTIONS_RUNNER_DISABLE_KUBE_SCHEDULER=true` will fall back to legacy `nodeName` pinning (not recommended). RWX configurations do not require any special configuration for basic operation.
## Migration Guidance
Operators migrating from an RWO setup that relied on legacy `nodeName` behavior can continue by setting `ACTIONS_RUNNER_DISABLE_KUBE_SCHEDULER=true`, but should migrate to the default affinity-based scheduling for better scheduler integration:
1. Remove the `ACTIONS_RUNNER_DISABLE_KUBE_SCHEDULER` environment variable to use the default affinity-based scheduling.
2. Verify that the runner's ServiceAccount has the necessary permissions to list pods (to determine its own node).
## Non-Goals
- This ADR does not recommend `nodeName` as a primary or secondary configuration path for operators.
- This ADR does not dictate specific storage providers (e.g., EBS vs. EFS vs. Azure Files), but rather the access mode strategy.
+2 -10
View File
@@ -1,12 +1,12 @@
{
"name": "hooks",
"version": "0.8.1",
"version": "0.8.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "hooks",
"version": "0.8.1",
"version": "0.8.0",
"license": "MIT",
"dependencies": {
"eslint-plugin-jest": "^29.0.1"
@@ -560,7 +560,6 @@
"integrity": "sha512-HC3y9CVuevvWCl/oyZuI47dOeDF9ztdMEfMH8/DW/Mhwa9cCLnK1oD7JoTVGW/u7kFzNZUKUoyJEqkaJh5y3Wg==",
"devOptional": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@eslint-community/regexpp": "^4.10.0",
"@typescript-eslint/scope-manager": "8.45.0",
@@ -591,7 +590,6 @@
"integrity": "sha512-TGf22kon8KW+DeKaUmOibKWktRY8b2NSAZNdtWh798COm1NWx8+xJ6iFBtk3IvLdv6+LGLJLRlyhrhEDZWargQ==",
"devOptional": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@typescript-eslint/scope-manager": "8.45.0",
"@typescript-eslint/types": "8.45.0",
@@ -788,7 +786,6 @@
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz",
"integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==",
"license": "MIT",
"peer": true,
"bin": {
"acorn": "bin/acorn"
},
@@ -1084,7 +1081,6 @@
}
],
"license": "MIT",
"peer": true,
"dependencies": {
"baseline-browser-mapping": "^2.8.9",
"caniuse-lite": "^1.0.30001746",
@@ -1587,7 +1583,6 @@
"resolved": "https://registry.npmjs.org/eslint/-/eslint-9.36.0.tgz",
"integrity": "sha512-hB4FIzXovouYzwzECDcUkJ4OcfOEkXTv2zRY6B9bkwjx/cprAq0uvm1nl7zvQ0/TsUk0zQiN4uPfJpB9m+rPMQ==",
"license": "MIT",
"peer": true,
"dependencies": {
"@eslint-community/eslint-utils": "^4.8.0",
"@eslint-community/regexpp": "^4.12.1",
@@ -1649,7 +1644,6 @@
"integrity": "sha512-82GZUjRS0p/jganf6q1rEO25VSoHH0hKPCTrgillPjdI/3bgBhAE1QzHrHTizjpRvy6pGAvKjDJtk2pF9NDq8w==",
"dev": true,
"license": "MIT",
"peer": true,
"bin": {
"eslint-config-prettier": "bin/cli.js"
},
@@ -3652,7 +3646,6 @@
"integrity": "sha512-I7AIg5boAr5R0FFtJ6rCfD+LFsWHp81dolrFD8S79U9tb8Az2nGrJncnMSnys+bpQJfRUzqs9hnA81OAA3hCuQ==",
"dev": true,
"license": "MIT",
"peer": true,
"bin": {
"prettier": "bin/prettier.cjs"
},
@@ -4387,7 +4380,6 @@
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
"license": "Apache-2.0",
"peer": true,
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "hooks",
"version": "0.8.1",
"version": "0.8.0",
"description": "Three projects are included - k8s: a kubernetes hook implementation that spins up pods dynamically to run a job - docker: A hook implementation of the runner's docker implementation - A hook lib, which contains shared typescript definitions and utilities that the other packages consume",
"main": "",
"directories": {
@@ -8,7 +8,7 @@
},
"scripts": {
"test": "npm run test --prefix packages/docker && npm run test --prefix packages/k8s",
"bootstrap": "npm install --prefix packages/hooklib && npm ci --prefix packages/k8s && npm ci --prefix packages/docker",
"bootstrap": "npm install --prefix packages/hooklib && npm install --prefix packages/k8s && npm install --prefix packages/docker",
"format": "prettier --write '**/*.ts'",
"format-check": "prettier --check '**/*.ts'",
"lint": "eslint packages/**/*.ts",
+458 -390
View File
File diff suppressed because it is too large Load Diff
+6 -6
View File
@@ -13,21 +13,21 @@
"author": "",
"license": "MIT",
"dependencies": {
"@actions/core": "^2.0.2",
"@actions/core": "^1.11.1",
"@actions/exec": "^2.0.0",
"hooklib": "file:../hooklib",
"shlex": "^3.0.0",
"uuid": "^11.1.0"
"uuid": "^13.0.0"
},
"devDependencies": {
"@babel/core": "^7.25.2",
"@babel/preset-env": "^7.25.4",
"@babel/core": "^7.28.5",
"@babel/preset-env": "^7.28.5",
"@types/jest": "^30.0.0",
"@types/node": "^24.0.14",
"@typescript-eslint/parser": "^8.37.0",
"@typescript-eslint/parser": "^8.49.0",
"@vercel/ncc": "^0.38.3",
"jest": "^30.0.4",
"ts-jest": "^29.4.0",
"ts-jest": "^29.4.6",
"ts-node": "^10.9.2",
"tsconfig-paths": "^4.2.0",
"typescript": "^5.8.3"
+427 -243
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -22,6 +22,6 @@
"typescript": "^5.8.3"
},
"dependencies": {
"@actions/core": "^2.0.2"
"@actions/core": "^1.11.1"
}
}
-21
View File
@@ -30,27 +30,6 @@ rules:
- The `ACTIONS_RUNNER_REQUIRE_JOB_CONTAINER` env should be set to true to prevent the runner from running any jobs outside of a container
- The runner pod should map a persistent volume claim into the `_work` directory
- The `ACTIONS_RUNNER_CLAIM_NAME` env should be set to the persistent volume claim that contains the runner's working directory, otherwise it defaults to `${ACTIONS_RUNNER_POD_NAME}-work`
- By default, the hook uses the Kubernetes scheduler with `nodeAffinity` to ensure job pods are scheduled correctly (essential for `ReadWriteOnce` volumes). Setting `ACTIONS_RUNNER_DISABLE_KUBE_SCHEDULER=true` will fall back to legacy `nodeName` pinning (not recommended).
## Storage Guidance
The K8s hooks require a shared volume between the runner pod and the job pods to share the workspace and other internal directories.
### RWX (Recommended)
The preferred way to configure storage is using a `ReadWriteMany` (RWX) Persistent Volume Claim. RWX allows the Kubernetes scheduler to place job pods on any node in the cluster, maximizing resource availability and flexibility.
To migrate from RWO to RWX:
1. Provision a new `ReadWriteMany` StorageClass if one is not available.
2. Update your PVC definition to use `accessModes: [ReadWriteMany]`.
3. No additional environment variables are needed - affinity-based scheduling is the default.
### RWO Fallback (Affinity-based)
If `ReadWriteMany` storage is not available, you can use `ReadWriteOnce` (RWO) storage. In this mode, all job pods must be scheduled on the same node as the runner pod that owns the PVC.
To enable this safely:
1. The default affinity-based scheduling works automatically. Do not set `ACTIONS_RUNNER_DISABLE_KUBE_SCHEDULER`.
2. The hooks will automatically add a `nodeAffinity` to the job pods, ensuring they are scheduled on the same node as the runner pod (`kubernetes.io/hostname` match).
> **Note:** We do not recommend manually setting `nodeName` in the pod template, as the hooks handle node placement automatically via affinity when the scheduler is enabled.
- Some actions runner env's are expected to be set. These are set automatically by the runner.
- `RUNNER_WORKSPACE` is expected to be set to the workspace of the runner
- `GITHUB_WORKSPACE` is expected to be set to the workspace of the job
+457 -456
View File
File diff suppressed because it is too large Load Diff
+3 -3
View File
@@ -13,9 +13,9 @@
"author": "",
"license": "MIT",
"dependencies": {
"@actions/core": "^2.0.2",
"@actions/exec": "^2.0.0",
"@actions/io": "^2.0.0",
"@actions/core": "^1.11.1",
"@actions/exec": "^1.1.1",
"@actions/io": "^1.1.3",
"@kubernetes/client-node": "^1.3.0",
"hooklib": "file:../hooklib",
"js-yaml": "^4.1.0",
+48 -29
View File
@@ -1,5 +1,4 @@
import * as core from '@actions/core'
import * as io from '@actions/io'
import * as k8s from '@kubernetes/client-node'
import {
JobContainerInfo,
@@ -8,26 +7,33 @@ import {
writeToResponseFile,
ServiceContainerInfo
} from 'hooklib'
import path from 'path'
import {
containerPorts,
createPod,
createJobPod,
isPodContainerAlpine,
prunePods,
waitForPodPhases,
getPrepareJobTimeoutSeconds
getPrepareJobTimeoutSeconds,
execCpToPod,
execPodStep
} from '../k8s'
import {
containerVolumes,
CONTAINER_VOLUMES,
DEFAULT_CONTAINER_ENTRY_POINT,
DEFAULT_CONTAINER_ENTRY_POINT_ARGS,
generateContainerName,
mergeContainerWithOptions,
readExtensionFromFile,
PodPhase,
fixArgs
fixArgs,
prepareJobScript
} from '../k8s/utils'
import { CONTAINER_EXTENSION_PREFIX, JOB_CONTAINER_NAME } from './constants'
import {
CONTAINER_EXTENSION_PREFIX,
getJobPodName,
JOB_CONTAINER_NAME
} from './constants'
import { dirname } from 'path'
export async function prepareJob(
args: PrepareJobArgs,
@@ -40,7 +46,6 @@ export async function prepareJob(
await prunePods()
const extension = readExtensionFromFile()
await copyExternalsToRoot()
let container: k8s.V1Container | undefined = undefined
if (args.container?.image) {
@@ -70,7 +75,8 @@ export async function prepareJob(
let createdPod: k8s.V1Pod | undefined = undefined
try {
createdPod = await createPod(
createdPod = await createJobPod(
getJobPodName(),
container,
services,
args.container.registry,
@@ -90,6 +96,13 @@ export async function prepareJob(
`Job pod created, waiting for it to come online ${createdPod?.metadata?.name}`
)
const runnerWorkspace = dirname(process.env.RUNNER_WORKSPACE as string)
let prepareScript: { containerPath: string; runnerPath: string } | undefined
if (args.container?.userMountVolumes?.length) {
prepareScript = prepareJobScript(args.container.userMountVolumes || [])
}
try {
await waitForPodPhases(
createdPod.metadata.name,
@@ -102,6 +115,28 @@ export async function prepareJob(
throw new Error(`pod failed to come online with error: ${err}`)
}
await execCpToPod(createdPod.metadata.name, runnerWorkspace, '/__w')
if (prepareScript) {
await execPodStep(
['sh', '-e', prepareScript.containerPath],
createdPod.metadata.name,
JOB_CONTAINER_NAME
)
const promises: Promise<void>[] = []
for (const vol of args?.container?.userMountVolumes || []) {
promises.push(
execCpToPod(
createdPod.metadata.name,
vol.sourceVolumePath,
vol.targetVolumePath
)
)
}
await Promise.all(promises)
}
core.debug('Job pod is ready for traffic')
let isAlpine = false
@@ -145,10 +180,8 @@ function generateResponseFile(
const mainContainerContextPorts: ContextPorts = {}
if (mainContainer?.ports) {
for (const port of mainContainer.ports) {
if (port.containerPort && port.hostPort) {
mainContainerContextPorts[port.containerPort.toString()] =
port.hostPort.toString()
}
mainContainerContextPorts[port.containerPort] =
mainContainerContextPorts.hostPort
}
}
@@ -184,17 +217,6 @@ function generateResponseFile(
writeToResponseFile(responseFile, JSON.stringify(response))
}
async function copyExternalsToRoot(): Promise<void> {
const workspace = process.env['RUNNER_WORKSPACE']
if (workspace) {
await io.cp(
path.join(workspace, '../../externals'),
path.join(workspace, '../externals'),
{ force: true, recursive: true, copySourceDirectory: false }
)
}
}
export function createContainerSpec(
container: JobContainerInfo | ServiceContainerInfo,
name: string,
@@ -228,7 +250,7 @@ export function createContainerSpec(
container['environmentVariables'] || {}
)) {
if (value && key !== 'HOME') {
podContainer.env.push({ name: key, value: value })
podContainer.env.push({ name: key, value })
}
}
@@ -244,10 +266,7 @@ export function createContainerSpec(
})
}
podContainer.volumeMounts = containerVolumes(
container['userMountVolumes'],
jobContainer
)
podContainer.volumeMounts = CONTAINER_VOLUMES
if (!extension) {
return podContainer
+90 -91
View File
@@ -1,23 +1,31 @@
import * as core from '@actions/core'
import * as fs from 'fs'
import * as k8s from '@kubernetes/client-node'
import { RunContainerStepArgs } from 'hooklib'
import { dirname } from 'path'
import {
createJob,
createSecretForEnvs,
getContainerJobPodName,
getPodLogs,
getPodStatus,
waitForJobToComplete,
createContainerStepPod,
deletePod,
execCpFromPod,
execCpToPod,
execPodStep,
getPrepareJobTimeoutSeconds,
waitForPodPhases
} from '../k8s'
import {
containerVolumes,
fixArgs,
CONTAINER_VOLUMES,
mergeContainerWithOptions,
PodPhase,
readExtensionFromFile
readExtensionFromFile,
DEFAULT_CONTAINER_ENTRY_POINT_ARGS,
writeContainerStepScript
} from '../k8s/utils'
import { JOB_CONTAINER_EXTENSION_NAME, JOB_CONTAINER_NAME } from './constants'
import {
getJobPodName,
getStepPodName,
JOB_CONTAINER_EXTENSION_NAME,
JOB_CONTAINER_NAME
} from './constants'
export async function runContainerStep(
stepContainer: RunContainerStepArgs
@@ -26,118 +34,109 @@ export async function runContainerStep(
throw new Error('Building container actions is not currently supported')
}
let secretName: string | undefined = undefined
if (stepContainer.environmentVariables) {
try {
const envs = JSON.parse(
JSON.stringify(stepContainer.environmentVariables)
)
envs['GITHUB_ACTIONS'] = 'true'
if (!('CI' in envs)) {
envs.CI = 'true'
}
secretName = await createSecretForEnvs(envs)
} catch (err) {
core.debug(`createSecretForEnvs failed: ${JSON.stringify(err)}`)
const message = (err as any)?.response?.body?.message || err
throw new Error(`failed to create script environment: ${message}`)
}
if (!stepContainer.entryPoint) {
throw new Error(
'failed to start the container since the entrypoint is overwritten'
)
}
const envs = stepContainer.environmentVariables || {}
envs['GITHUB_ACTIONS'] = 'true'
if (!('CI' in envs)) {
envs.CI = 'true'
}
const extension = readExtensionFromFile()
core.debug(`Created secret ${secretName} for container job envs`)
const container = createContainerSpec(stepContainer, secretName, extension)
const container = createContainerSpec(stepContainer, extension)
let job: k8s.V1Job
let pod: k8s.V1Pod
try {
job = await createJob(container, extension)
pod = await createContainerStepPod(getStepPodName(), container, extension)
} catch (err) {
core.debug(`createJob failed: ${JSON.stringify(err)}`)
const message = (err as any)?.response?.body?.message || err
throw new Error(`failed to run script step: ${message}`)
}
if (!job.metadata?.name) {
if (!pod.metadata?.name) {
throw new Error(
`Expected job ${JSON.stringify(
job
pod
)} to have correctly set the metadata.name`
)
}
core.debug(`Job created, waiting for pod to start: ${job.metadata?.name}`)
const podName = pod.metadata.name
let podName: string
try {
podName = await getContainerJobPodName(job.metadata.name)
} catch (err) {
core.debug(`getContainerJobPodName failed: ${JSON.stringify(err)}`)
const message = (err as any)?.response?.body?.message || err
throw new Error(`failed to get container job pod name: ${message}`)
}
await waitForPodPhases(
podName,
new Set([
PodPhase.COMPLETED,
PodPhase.RUNNING,
PodPhase.SUCCEEDED,
PodPhase.FAILED
]),
new Set([PodPhase.PENDING, PodPhase.UNKNOWN])
)
core.debug('Container step is running or complete, pulling logs')
await getPodLogs(podName, JOB_CONTAINER_NAME)
core.debug('Waiting for container job to complete')
await waitForJobToComplete(job.metadata.name)
const status = await getPodStatus(podName)
if (status?.phase === 'Succeeded') {
return 0
}
if (!status?.containerStatuses?.length) {
core.error(
`Can't determine container status from response: ${JSON.stringify(
status
)}`
await waitForPodPhases(
podName,
new Set([PodPhase.RUNNING]),
new Set([PodPhase.PENDING, PodPhase.UNKNOWN]),
getPrepareJobTimeoutSeconds()
)
return 1
const runnerWorkspace = dirname(process.env.RUNNER_WORKSPACE as string)
const githubWorkspace = process.env.GITHUB_WORKSPACE as string
const parts = githubWorkspace.split('/').slice(-2)
if (parts.length !== 2) {
throw new Error(`Invalid github workspace directory: ${githubWorkspace}`)
}
const relativeWorkspace = parts.join('/')
core.debug(
`Copying files from pod ${getJobPodName()} to ${runnerWorkspace}/${relativeWorkspace}`
)
await execCpFromPod(getJobPodName(), `/__w`, `${runnerWorkspace}`)
const { containerPath, runnerPath } = writeContainerStepScript(
`${runnerWorkspace}/__w/_temp`,
githubWorkspace,
stepContainer.entryPoint,
stepContainer.entryPointArgs,
envs
)
await execCpToPod(podName, `${runnerWorkspace}/__w`, '/__w')
fs.rmSync(`${runnerWorkspace}/__w`, { recursive: true, force: true })
try {
core.debug(`Executing container step script in pod ${podName}`)
return await execPodStep(
['sh', '-e', containerPath],
pod.metadata.name,
JOB_CONTAINER_NAME
)
} catch (err) {
core.debug(`execPodStep failed: ${JSON.stringify(err)}`)
const message = (err as any)?.response?.body?.message || err
throw new Error(`failed to run script step: ${message}`)
} finally {
fs.rmSync(runnerPath, { force: true })
}
} catch (error) {
core.error(`Failed to run container step: ${error}`)
throw error
} finally {
await deletePod(podName).catch(err => {
core.error(`Failed to delete step pod ${podName}: ${err}`)
})
}
const exitCode =
status.containerStatuses[status.containerStatuses.length - 1].state
?.terminated?.exitCode
return Number(exitCode) || 1
}
function createContainerSpec(
container: RunContainerStepArgs,
secretName?: string,
extension?: k8s.V1PodTemplateSpec
): k8s.V1Container {
const podContainer = new k8s.V1Container()
podContainer.name = JOB_CONTAINER_NAME
podContainer.image = container.image
podContainer.workingDir = container.workingDirectory
podContainer.command = container.entryPoint
? [container.entryPoint]
: undefined
podContainer.args = container.entryPointArgs?.length
? fixArgs(container.entryPointArgs)
: undefined
podContainer.workingDir = '/__w'
podContainer.command = ['tail']
podContainer.args = DEFAULT_CONTAINER_ENTRY_POINT_ARGS
if (secretName) {
podContainer.envFrom = [
{
secretRef: {
name: secretName,
optional: false
}
}
]
}
podContainer.volumeMounts = containerVolumes(undefined, false, true)
podContainer.volumeMounts = CONTAINER_VOLUMES
if (!extension) {
return podContainer
+74 -6
View File
@@ -2,17 +2,19 @@
import * as fs from 'fs'
import * as core from '@actions/core'
import { RunScriptStepArgs } from 'hooklib'
import { execPodStep } from '../k8s'
import { writeEntryPointScript } from '../k8s/utils'
import { execCpFromPod, execCpToPod, execPodStep } from '../k8s'
import { writeRunScript, sleep, listDirAllCommand } from '../k8s/utils'
import { JOB_CONTAINER_NAME } from './constants'
import { dirname } from 'path'
import * as shlex from 'shlex'
export async function runScriptStep(
args: RunScriptStepArgs,
state,
responseFile?
state
): Promise<void> {
// Write the entrypoint first. This will be later coppied to the workflow pod
const { entryPoint, entryPointArgs, environmentVariables } = args
const { containerPath, runnerPath } = writeEntryPointScript(
const { containerPath, runnerPath } = writeRunScript(
args.workingDirectory,
entryPoint,
entryPointArgs,
@@ -20,6 +22,55 @@ export async function runScriptStep(
environmentVariables
)
const workdir = dirname(process.env.RUNNER_WORKSPACE as string)
const runnerTemp = `${workdir}/_temp`
const containerTemp = '/__w/_temp'
const containerTempSrc = '/__w/_temp_pre'
// Ensure base and staging dirs exist before copying
await execPodStep(
[
'sh',
'-c',
'mkdir -p /__w && mkdir -p /__w/_temp && mkdir -p /__w/_temp_pre'
],
state.jobPod,
JOB_CONTAINER_NAME
)
await execCpToPod(state.jobPod, runnerTemp, containerTempSrc)
// Copy GitHub directories from temp to /github
// Merge strategy:
// - Overwrite files in _runner_file_commands
// - Append files not already present elsewhere
const mergeCommands = [
'set -e',
'mkdir -p /__w/_temp /__w/_temp_pre',
'SRC=/__w/_temp_pre',
'DST=/__w/_temp',
// Overwrite _runner_file_commands
`find "$SRC" -type f ! -path "*/_runner_file_commands/*" -exec sh -c '
rel="\${1#$2/}"
target="$3/$rel"
mkdir -p "$(dirname "$target")"
cp -a "$1" "$target"
' _ {} "$SRC" "$DST" \\;`,
// Remove _temp_pre after merging
'rm -rf /__w/_temp_pre'
]
try {
await execPodStep(
['sh', '-c', mergeCommands.join(' && ')],
state.jobPod,
JOB_CONTAINER_NAME
)
} catch (err) {
core.debug(`Failed to merge temp directories: ${JSON.stringify(err)}`)
const message = (err as any)?.response?.body?.message || err
throw new Error(`failed to merge temp dirs: ${message}`)
}
// Execute the entrypoint script
args.entryPoint = 'sh'
args.entryPointArgs = ['-e', containerPath]
try {
@@ -33,6 +84,23 @@ export async function runScriptStep(
const message = (err as any)?.response?.body?.message || err
throw new Error(`failed to run script step: ${message}`)
} finally {
fs.rmSync(runnerPath)
try {
fs.rmSync(runnerPath, { force: true })
} catch (removeErr) {
core.debug(`Failed to remove file ${runnerPath}: ${removeErr}`)
}
}
try {
core.debug(
`Copying from job pod '${state.jobPod}' ${containerTemp} to ${runnerTemp}`
)
await execCpFromPod(
state.jobPod,
`${containerTemp}/_runner_file_commands`,
`${workdir}/_temp`
)
} catch (error) {
core.warning('Failed to copy _temp from pod')
}
}
+403 -130
View File
@@ -1,22 +1,29 @@
import * as core from '@actions/core'
import * as path from 'path'
import { spawn } from 'child_process'
import * as k8s from '@kubernetes/client-node'
import tar from 'tar-fs'
import * as stream from 'stream'
import { WritableStreamBuffer } from 'stream-buffers'
import { createHash } from 'crypto'
import type { ContainerInfo, Registry } from 'hooklib'
import {
getJobPodName,
getRunnerPodName,
getSecretName,
getStepPodName,
getVolumeClaimName,
JOB_CONTAINER_NAME,
RunnerInstanceLabel
} from '../hooks/constants'
import {
PodPhase,
mergePodSpecWithOptions,
mergeObjectMeta,
useKubeScheduler,
fixArgs
fixArgs,
listDirAllCommand,
sleep,
EXTERNALS_VOLUME_NAME,
GITHUB_VOLUME_NAME,
WORK_VOLUME
} from './utils'
import * as shlex from 'shlex'
const kc = new k8s.KubeConfig()
@@ -28,8 +35,6 @@ const k8sAuthorizationV1Api = kc.makeApiClient(k8s.AuthorizationV1Api)
const DEFAULT_WAIT_FOR_POD_TIME_SECONDS = 10 * 60 // 10 min
export const POD_VOLUME_NAME = 'work'
export const requiredPermissions = [
{
group: '',
@@ -49,12 +54,6 @@ export const requiredPermissions = [
resource: 'pods',
subresource: 'log'
},
{
group: 'batch',
verbs: ['get', 'list', 'create', 'delete'],
resource: 'jobs',
subresource: ''
},
{
group: '',
verbs: ['create', 'delete', 'get', 'list'],
@@ -63,7 +62,8 @@ export const requiredPermissions = [
}
]
export async function createPod(
export async function createJobPod(
name: string,
jobContainer?: k8s.V1Container,
services?: k8s.V1Container[],
registry?: Registry,
@@ -83,7 +83,7 @@ export async function createPod(
appPod.kind = 'Pod'
appPod.metadata = new k8s.V1ObjectMeta()
appPod.metadata.name = getJobPodName()
appPod.metadata.name = name
const instanceLabel = new RunnerInstanceLabel()
appPod.metadata.labels = {
@@ -93,19 +93,68 @@ export async function createPod(
appPod.spec = new k8s.V1PodSpec()
appPod.spec.containers = containers
appPod.spec.securityContext = {
fsGroup: 1001
}
// Extract working directory from GITHUB_WORKSPACE
// GITHUB_WORKSPACE is like /__w/repo-name/repo-name
const githubWorkspace = process.env.GITHUB_WORKSPACE
const workingDirPath = githubWorkspace?.split('/').slice(-2).join('/') ?? ''
const initCommands = [
'mkdir -p /mnt/externals',
'mkdir -p /mnt/work',
'mkdir -p /mnt/github',
'mv /home/runner/externals/* /mnt/externals/'
]
if (workingDirPath) {
initCommands.push(`mkdir -p /mnt/work/${workingDirPath}`)
}
appPod.spec.initContainers = [
{
name: 'fs-init',
image:
process.env.ACTIONS_RUNNER_IMAGE ||
'ghcr.io/actions/actions-runner:latest',
command: ['sh', '-c', initCommands.join(' && ')],
securityContext: {
runAsGroup: 1001,
runAsUser: 1001
},
volumeMounts: [
{
name: EXTERNALS_VOLUME_NAME,
mountPath: '/mnt/externals'
},
{
name: WORK_VOLUME,
mountPath: '/mnt/work'
},
{
name: GITHUB_VOLUME_NAME,
mountPath: '/mnt/github'
}
]
}
]
appPod.spec.restartPolicy = 'Never'
const nodeName = await getCurrentNodeName()
if (useKubeScheduler()) {
appPod.spec.affinity = await getPodAffinity(nodeName)
} else {
appPod.spec.nodeName = nodeName
}
const claimName = getVolumeClaimName()
appPod.spec.volumes = [
{
name: POD_VOLUME_NAME,
persistentVolumeClaim: { claimName }
name: EXTERNALS_VOLUME_NAME,
emptyDir: {}
},
{
name: GITHUB_VOLUME_NAME,
emptyDir: {}
},
{
name: WORK_VOLUME,
emptyDir: {}
}
]
@@ -133,90 +182,62 @@ export async function createPod(
})
}
export async function createJob(
export async function createContainerStepPod(
name: string,
container: k8s.V1Container,
extension?: k8s.V1PodTemplateSpec
): Promise<k8s.V1Job> {
const runnerInstanceLabel = new RunnerInstanceLabel()
): Promise<k8s.V1Pod> {
const appPod = new k8s.V1Pod()
const job = new k8s.V1Job()
job.apiVersion = 'batch/v1'
job.kind = 'Job'
job.metadata = new k8s.V1ObjectMeta()
job.metadata.name = getStepPodName()
job.metadata.labels = { [runnerInstanceLabel.key]: runnerInstanceLabel.value }
job.metadata.annotations = {}
appPod.apiVersion = 'v1'
appPod.kind = 'Pod'
job.spec = new k8s.V1JobSpec()
job.spec.ttlSecondsAfterFinished = 300
job.spec.backoffLimit = 0
job.spec.template = new k8s.V1PodTemplateSpec()
appPod.metadata = new k8s.V1ObjectMeta()
appPod.metadata.name = name
job.spec.template.spec = new k8s.V1PodSpec()
job.spec.template.metadata = new k8s.V1ObjectMeta()
job.spec.template.metadata.labels = {}
job.spec.template.metadata.annotations = {}
job.spec.template.spec.containers = [container]
job.spec.template.spec.restartPolicy = 'Never'
const nodeName = await getCurrentNodeName()
if (useKubeScheduler()) {
job.spec.template.spec.affinity = await getPodAffinity(nodeName)
} else {
job.spec.template.spec.nodeName = nodeName
const instanceLabel = new RunnerInstanceLabel()
appPod.metadata.labels = {
[instanceLabel.key]: instanceLabel.value
}
appPod.metadata.annotations = {}
const claimName = getVolumeClaimName()
job.spec.template.spec.volumes = [
appPod.spec = new k8s.V1PodSpec()
appPod.spec.containers = [container]
appPod.spec.restartPolicy = 'Never'
appPod.spec.volumes = [
{
name: POD_VOLUME_NAME,
persistentVolumeClaim: { claimName }
name: EXTERNALS_VOLUME_NAME,
emptyDir: {}
},
{
name: GITHUB_VOLUME_NAME,
emptyDir: {}
},
{
name: WORK_VOLUME,
emptyDir: {}
}
]
if (extension) {
if (extension.metadata) {
mergeObjectMeta(job, extension.metadata)
mergeObjectMeta(job.spec.template, extension.metadata)
}
if (extension.spec) {
mergePodSpecWithOptions(job.spec.template.spec, extension.spec)
}
if (extension?.metadata) {
mergeObjectMeta(appPod, extension.metadata)
}
return await k8sBatchV1Api.createNamespacedJob({
if (extension?.spec) {
mergePodSpecWithOptions(appPod.spec, extension.spec)
}
return await k8sApi.createNamespacedPod({
namespace: namespace(),
body: job
body: appPod
})
}
export async function getContainerJobPodName(jobName: string): Promise<string> {
const selector = `job-name=${jobName}`
const backOffManager = new BackOffManager(60)
while (true) {
const podList = await k8sApi.listNamespacedPod({
namespace: namespace(),
labelSelector: selector,
limit: 1
})
if (!podList.items?.length) {
await backOffManager.backOff()
continue
}
if (!podList.items[0].metadata?.name) {
throw new Error(
`Failed to determine the name of the pod for job ${jobName}`
)
}
return podList.items[0].metadata.name
}
}
export async function deletePod(podName: string): Promise<void> {
export async function deletePod(name: string): Promise<void> {
await k8sApi.deleteNamespacedPod({
name: podName,
name,
namespace: namespace(),
gracePeriodSeconds: 0
})
@@ -243,6 +264,7 @@ export async function execPodStep(
stdin ?? null,
false /* tty */,
resp => {
core.debug(`execPodStep response: ${JSON.stringify(resp)}`)
if (resp.status === 'Success') {
resolve(resp.code || 0)
} else {
@@ -260,6 +282,290 @@ export async function execPodStep(
})
}
export async function execCalculateOutputHashSorted(
podName: string,
containerName: string,
command: string[]
): Promise<string> {
const exec = new k8s.Exec(kc)
let output = ''
const outputWriter = new stream.Writable({
write(chunk, _enc, cb) {
try {
output += chunk.toString('utf8')
cb()
} catch (e) {
cb(e as Error)
}
}
})
await new Promise<void>((resolve, reject) => {
exec
.exec(
namespace(),
podName,
containerName,
command,
outputWriter, // capture stdout
process.stderr,
null,
false /* tty */,
resp => {
core.debug(`internalExecOutput response: ${JSON.stringify(resp)}`)
if (resp.status === 'Success') {
resolve()
} else {
core.debug(
JSON.stringify({
message: resp?.message,
details: resp?.details
})
)
reject(new Error(resp?.message || 'internalExecOutput failed'))
}
}
)
.catch(e => reject(e))
})
outputWriter.end()
// Sort lines for consistent ordering across platforms
const sortedOutput =
output
.split('\n')
.filter(line => line.length > 0)
.sort()
.join('\n') + '\n'
const hash = createHash('sha256')
hash.update(sortedOutput)
return hash.digest('hex')
}
export async function localCalculateOutputHashSorted(
commands: string[]
): Promise<string> {
return await new Promise<string>((resolve, reject) => {
const child = spawn(commands[0], commands.slice(1), {
stdio: ['ignore', 'pipe', 'ignore']
})
let output = ''
child.stdout.on('data', chunk => {
output += chunk.toString('utf8')
})
child.on('error', reject)
child.on('close', (code: number) => {
if (code === 0) {
// Sort lines for consistent ordering across distributions/platforms
const sortedOutput =
output
.split('\n')
.filter(line => line.length > 0)
.sort()
.join('\n') + '\n'
const hash = createHash('sha256')
hash.update(sortedOutput)
resolve(hash.digest('hex'))
} else {
reject(new Error(`child process exited with code ${code}`))
}
})
})
}
export async function execCpToPod(
podName: string,
runnerPath: string,
containerPath: string
): Promise<void> {
core.debug(`Copying ${runnerPath} to pod ${podName} at ${containerPath}`)
let attempt = 0
while (true) {
try {
const exec = new k8s.Exec(kc)
// Use tar to extract with --no-same-owner to avoid ownership issues.
// Then use find to fix permissions. The -m flag helps but we also need to fix permissions after.
const command = [
'sh',
'-c',
`tar xf - --no-same-owner -C ${shlex.quote(containerPath)} 2>/dev/null; ` +
`find ${shlex.quote(containerPath)} -type f -exec chmod u+rw {} \\; 2>/dev/null; ` +
`find ${shlex.quote(containerPath)} -type d -exec chmod u+rwx {} \\; 2>/dev/null`
]
const readStream = tar.pack(runnerPath)
const errStream = new WritableStreamBuffer()
await new Promise((resolve, reject) => {
exec
.exec(
namespace(),
podName,
JOB_CONTAINER_NAME,
command,
null,
errStream,
readStream,
false,
async status => {
if (errStream.size()) {
reject(
new Error(
`Error from execCpToPod - status: ${status.status}, details: \n ${errStream.getContentsAsString()}`
)
)
}
resolve(status)
}
)
.catch(e => reject(e))
})
break
} catch (error) {
core.debug(`cpToPod: Attempt ${attempt + 1} failed: ${error}`)
attempt++
if (attempt >= 30) {
throw new Error(
`cpToPod failed after ${attempt} attempts: ${JSON.stringify(error)}`
)
}
await sleep(1000)
}
}
let attempts = 15
const delay = 1000
for (let i = 0; i < attempts; i++) {
try {
const want = await localCalculateOutputHashSorted([
'sh',
'-c',
listDirAllCommand(runnerPath)
])
const got = await execCalculateOutputHashSorted(
podName,
JOB_CONTAINER_NAME,
['sh', '-c', listDirAllCommand(containerPath)]
)
if (got !== want) {
core.debug(
`The hash of the directory does not match the expected value; want='${want}' got='${got}'`
)
await sleep(delay)
continue
}
break
} catch (error) {
core.debug(`Attempt ${i + 1} failed: ${error}`)
await sleep(delay)
}
}
}
export async function execCpFromPod(
podName: string,
containerPath: string,
parentRunnerPath: string
): Promise<void> {
const targetRunnerPath = `${parentRunnerPath}/${path.basename(containerPath)}`
core.debug(
`Copying from pod ${podName} ${containerPath} to ${targetRunnerPath}`
)
let attempt = 0
while (true) {
try {
// make temporary directory
const exec = new k8s.Exec(kc)
const containerPaths = containerPath.split('/')
const dirname = containerPaths.pop() as string
const command = [
'tar',
'cf',
'-',
'-C',
containerPaths.join('/') || '/',
dirname
]
const writerStream = tar.extract(parentRunnerPath)
const errStream = new WritableStreamBuffer()
await new Promise((resolve, reject) => {
exec
.exec(
namespace(),
podName,
JOB_CONTAINER_NAME,
command,
writerStream,
errStream,
null,
false,
async status => {
if (errStream.size()) {
reject(
new Error(
`Error from cpFromPod - details: \n ${errStream.getContentsAsString()}`
)
)
}
resolve(status)
}
)
.catch(e => reject(e))
})
break
} catch (error) {
core.debug(`Attempt ${attempt + 1} failed: ${error}`)
attempt++
if (attempt >= 30) {
throw new Error(
`execCpFromPod failed after ${attempt} attempts: ${JSON.stringify(error)}`
)
}
await sleep(1000)
}
}
let attempts = 15
const delay = 1000
for (let i = 0; i < attempts; i++) {
try {
const want = await execCalculateOutputHashSorted(
podName,
JOB_CONTAINER_NAME,
['sh', '-c', listDirAllCommand(containerPath)]
)
const got = await localCalculateOutputHashSorted([
'sh',
'-c',
listDirAllCommand(targetRunnerPath)
])
if (got !== want) {
core.debug(
`The hash of the directory does not match the expected value; want='${want}' got='${got}'`
)
await sleep(delay)
continue
}
break
} catch (error) {
core.debug(`Attempt ${i + 1} failed: ${error}`)
await sleep(delay)
}
}
}
export async function waitForJobToComplete(jobName: string): Promise<void> {
const backOffManager = new BackOffManager()
while (true) {
@@ -343,9 +649,9 @@ export async function createSecretForEnvs(envs: {
return secretName
}
export async function deleteSecret(secretName: string): Promise<void> {
export async function deleteSecret(name: string): Promise<void> {
await k8sApi.deleteNamespacedSecret({
name: secretName,
name,
namespace: namespace()
})
}
@@ -362,7 +668,7 @@ export async function pruneSecrets(): Promise<void> {
await Promise.all(
secretList.items.map(
async secret =>
secret.metadata?.name && deleteSecret(secret.metadata.name)
secret.metadata?.name && (await deleteSecret(secret.metadata.name))
)
)
}
@@ -479,7 +785,7 @@ export async function prunePods(): Promise<void> {
await Promise.all(
podList.items.map(
async pod => pod.metadata?.name && deletePod(pod.metadata.name)
async pod => pod.metadata?.name && (await deletePod(pod.metadata.name))
)
)
}
@@ -525,7 +831,7 @@ export async function isPodContainerAlpine(
[
'sh',
'-c',
`'[ $(cat /etc/*release* | grep -i -e "^ID=*alpine*" -c) != 0 ] || exit 1'`
`[ $(cat /etc/*release* | grep -i -e "^ID=*alpine*" -c) != 0 ] || exit 1`
],
podName,
containerName
@@ -551,39 +857,6 @@ export function namespace(): string {
return context.namespace
}
async function getCurrentNodeName(): Promise<string> {
const resp = await k8sApi.readNamespacedPod({
name: getRunnerPodName(),
namespace: namespace()
})
const nodeName = resp.spec?.nodeName
if (!nodeName) {
throw new Error('Failed to determine node name')
}
return nodeName
}
async function getPodAffinity(nodeName: string): Promise<k8s.V1Affinity> {
const affinity = new k8s.V1Affinity()
affinity.nodeAffinity = new k8s.V1NodeAffinity()
affinity.nodeAffinity.requiredDuringSchedulingIgnoredDuringExecution =
new k8s.V1NodeSelector()
affinity.nodeAffinity.requiredDuringSchedulingIgnoredDuringExecution.nodeSelectorTerms =
[
{
matchExpressions: [
{
key: 'kubernetes.io/hostname',
operator: 'In',
values: [nodeName]
}
]
}
]
return affinity
}
class BackOffManager {
private backOffSeconds = 1
totalTime = 0
@@ -652,7 +925,7 @@ export function containerPorts(
return ports
}
export async function getPodByName(name: string): Promise<k8s.V1Pod> {
export async function getPodByName(name): Promise<k8s.V1Pod> {
return await k8sApi.readNamespacedPod({
name,
namespace: namespace()
+31 -127
View File
@@ -6,108 +6,31 @@ import { v1 as uuidv4 } from 'uuid'
import { CONTAINER_EXTENSION_PREFIX } from '../hooks/constants'
import * as shlex from 'shlex'
import { Mount } from 'hooklib'
import * as path from 'path'
import { POD_VOLUME_NAME } from './index'
export const DEFAULT_CONTAINER_ENTRY_POINT_ARGS = [`-f`, `/dev/null`]
export const DEFAULT_CONTAINER_ENTRY_POINT = 'tail'
export const ENV_HOOK_TEMPLATE_PATH = 'ACTIONS_RUNNER_CONTAINER_HOOK_TEMPLATE'
export const ENV_DISABLE_KUBE_SCHEDULER =
'ACTIONS_RUNNER_DISABLE_KUBE_SCHEDULER'
export const ENV_USE_KUBE_SCHEDULER = 'ACTIONS_RUNNER_USE_KUBE_SCHEDULER'
export function containerVolumes(
userMountVolumes: Mount[] = [],
jobContainer = true,
containerAction = false
): k8s.V1VolumeMount[] {
const mounts: k8s.V1VolumeMount[] = [
{
name: POD_VOLUME_NAME,
mountPath: '/__w'
}
]
export const EXTERNALS_VOLUME_NAME = 'externals'
export const GITHUB_VOLUME_NAME = 'github'
export const WORK_VOLUME = 'work'
const workspacePath = process.env.GITHUB_WORKSPACE as string
if (containerAction) {
const i = workspacePath.lastIndexOf('_work/')
const workspaceRelativePath = workspacePath.slice(i + '_work/'.length)
mounts.push(
{
name: POD_VOLUME_NAME,
mountPath: '/github/workspace',
subPath: workspaceRelativePath
},
{
name: POD_VOLUME_NAME,
mountPath: '/github/file_commands',
subPath: '_temp/_runner_file_commands'
},
{
name: POD_VOLUME_NAME,
mountPath: '/github/home',
subPath: '_temp/_github_home'
},
{
name: POD_VOLUME_NAME,
mountPath: '/github/workflow',
subPath: '_temp/_github_workflow'
}
)
return mounts
export const CONTAINER_VOLUMES: k8s.V1VolumeMount[] = [
{
name: EXTERNALS_VOLUME_NAME,
mountPath: '/__e'
},
{
name: WORK_VOLUME,
mountPath: '/__w'
},
{
name: GITHUB_VOLUME_NAME,
mountPath: '/github'
}
if (!jobContainer) {
return mounts
}
mounts.push(
{
name: POD_VOLUME_NAME,
mountPath: '/__e',
subPath: 'externals'
},
{
name: POD_VOLUME_NAME,
mountPath: '/github/home',
subPath: '_temp/_github_home'
},
{
name: POD_VOLUME_NAME,
mountPath: '/github/workflow',
subPath: '_temp/_github_workflow'
}
)
if (!userMountVolumes?.length) {
return mounts
}
for (const userVolume of userMountVolumes) {
let sourceVolumePath = ''
if (path.isAbsolute(userVolume.sourceVolumePath)) {
if (!userVolume.sourceVolumePath.startsWith(workspacePath)) {
throw new Error(
'Volume mounts outside of the work folder are not supported'
)
}
sourceVolumePath = userVolume.sourceVolumePath.slice(
workspacePath.length + 1
)
} else {
sourceVolumePath = userVolume.sourceVolumePath
}
mounts.push({
name: POD_VOLUME_NAME,
mountPath: userVolume.targetVolumePath,
subPath: sourceVolumePath,
readOnly: userVolume.readOnly
})
}
return mounts
}
]
export function prepareJobScript(userVolumeMounts: Mount[]): {
containerPath: string
@@ -131,38 +54,6 @@ mkdir -p ${mountDirs}
}
}
export function writeEntryPointScript(
workingDirectory: string,
entryPoint: string,
entryPointArgs?: string[],
prependPath?: string[],
environmentVariables?: { [key: string]: string }
): { containerPath: string; runnerPath: string } {
let exportPath = ''
if (prependPath?.length) {
const prepend =
typeof prependPath === 'string' ? prependPath : prependPath.join(':')
exportPath = `export PATH=${prepend}:$PATH`
}
const environmentPrefix = scriptEnv(environmentVariables)
const content = `#!/bin/sh -l
${exportPath}
cd ${workingDirectory} && \\
exec ${environmentPrefix} ${entryPoint} ${
entryPointArgs?.length ? entryPointArgs.join(' ') : ''
}
`
const filename = `${uuidv4()}.sh`
const entryPointPath = `${process.env.RUNNER_TEMP}/${filename}`
fs.writeFileSync(entryPointPath, content)
return {
containerPath: `/__w/_temp/${filename}`,
runnerPath: entryPointPath
}
}
export function writeRunScript(
workingDirectory: string,
entryPoint: string,
@@ -375,7 +266,7 @@ export function readExtensionFromFile(): k8s.V1PodTemplateSpec | undefined {
}
export function useKubeScheduler(): boolean {
return process.env[ENV_DISABLE_KUBE_SCHEDULER] !== 'true'
return process.env[ENV_USE_KUBE_SCHEDULER] === 'true'
}
export enum PodPhase {
@@ -397,5 +288,18 @@ function mergeLists<T>(base?: T[], from?: T[]): T[] {
}
export function fixArgs(args: string[]): string[] {
// Preserve shell command strings passed via `sh -c` without re-tokenizing.
// Retokenizing would split the script into multiple args, breaking `sh -c`.
if (args.length >= 2 && args[0] === 'sh' && args[1] === '-c') {
return args
}
return shlex.split(args.join(' '))
}
export async function sleep(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms))
}
export function listDirAllCommand(dir: string): string {
return `cd ${shlex.quote(dir)} && find . -not -path '*/_runner_hook_responses*' -exec stat -c '%s %n' {} \\;`
}
-137
View File
@@ -1,137 +0,0 @@
import * as fs from 'fs'
import { cleanupJob } from '../src/hooks'
import { prepareJob } from '../src/hooks/prepare-job'
import { TestHelper } from './test-setup'
import { getPodByName } from '../src/k8s'
import { ENV_DISABLE_KUBE_SCHEDULER } from '../src/k8s/utils'
jest.useRealTimers()
let testHelper: TestHelper
let prepareJobData: any
let prepareJobOutputFilePath: string
describe('RWO Affinity Behavior (Scheduler Mode)', () => {
beforeEach(async () => {
testHelper = new TestHelper()
await testHelper.initialize()
prepareJobData = testHelper.getPrepareJobDefinition()
prepareJobOutputFilePath = testHelper.createFile('prepare-job-output.json')
})
afterEach(async () => {
await cleanupJob()
await testHelper.cleanup()
delete process.env[ENV_DISABLE_KUBE_SCHEDULER]
})
it('should add nodeAffinity with hostname selector by default', async () => {
await prepareJob(prepareJobData.args, prepareJobOutputFilePath)
const content = JSON.parse(
fs.readFileSync(prepareJobOutputFilePath).toString()
)
const pod = await getPodByName(content.state.jobPod)
expect(pod.spec?.affinity).toBeDefined()
expect(pod.spec?.affinity?.nodeAffinity).toBeDefined()
const nodeAffinity = pod.spec?.affinity?.nodeAffinity
expect(
nodeAffinity?.requiredDuringSchedulingIgnoredDuringExecution
).toBeDefined()
const nodeSelectorTerms =
nodeAffinity?.requiredDuringSchedulingIgnoredDuringExecution
?.nodeSelectorTerms
expect(nodeSelectorTerms).toBeDefined()
expect(nodeSelectorTerms?.length).toBeGreaterThan(0)
const matchExpressions = nodeSelectorTerms?.[0].matchExpressions
expect(matchExpressions).toBeDefined()
expect(matchExpressions?.length).toBeGreaterThan(0)
const hostnameExpression = matchExpressions?.[0]
expect(hostnameExpression?.key).toBe('kubernetes.io/hostname')
expect(hostnameExpression?.operator).toBe('In')
expect(hostnameExpression?.values).toBeDefined()
expect(hostnameExpression?.values?.length).toBeGreaterThan(0)
expect(hostnameExpression?.values?.[0]).toBeTruthy()
})
it('should NOT add nodeAffinity when scheduler mode is disabled', async () => {
process.env[ENV_DISABLE_KUBE_SCHEDULER] = 'true'
await prepareJob(prepareJobData.args, prepareJobOutputFilePath)
const content = JSON.parse(
fs.readFileSync(prepareJobOutputFilePath).toString()
)
const pod = await getPodByName(content.state.jobPod)
if (pod.spec?.affinity) {
expect(pod.spec.affinity.nodeAffinity).toBeUndefined()
}
expect(pod.spec?.nodeName).toBeDefined()
})
it('should fail assertion if affinity block is missing by default', async () => {
await prepareJob(prepareJobData.args, prepareJobOutputFilePath)
const content = JSON.parse(
fs.readFileSync(prepareJobOutputFilePath).toString()
)
const pod = await getPodByName(content.state.jobPod)
expect(pod.spec?.affinity).toBeDefined()
expect(pod.spec?.affinity?.nodeAffinity).toBeDefined()
expect(
pod.spec?.affinity?.nodeAffinity
?.requiredDuringSchedulingIgnoredDuringExecution
).toBeDefined()
const nodeSelectorTerms =
pod.spec?.affinity?.nodeAffinity
?.requiredDuringSchedulingIgnoredDuringExecution?.nodeSelectorTerms
expect(nodeSelectorTerms?.[0]?.matchExpressions?.[0]?.key).toBe(
'kubernetes.io/hostname'
)
expect(nodeSelectorTerms?.[0]?.matchExpressions?.[0]?.operator).toBe('In')
expect(
nodeSelectorTerms?.[0]?.matchExpressions?.[0]?.values?.length
).toBeGreaterThan(0)
})
it('should use correct node name from runner pod in affinity values by default', async () => {
const runnerPodName = process.env.ACTIONS_RUNNER_POD_NAME
await prepareJob(prepareJobData.args, prepareJobOutputFilePath)
const content = JSON.parse(
fs.readFileSync(prepareJobOutputFilePath).toString()
)
const jobPod = await getPodByName(content.state.jobPod)
const runnerPod = await getPodByName(runnerPodName!)
const affinityValues =
jobPod.spec?.affinity?.nodeAffinity
?.requiredDuringSchedulingIgnoredDuringExecution?.nodeSelectorTerms?.[0]
?.matchExpressions?.[0]?.values
expect(affinityValues).toBeDefined()
expect(affinityValues?.length).toBeGreaterThan(0)
if (runnerPod.spec?.nodeName) {
expect(affinityValues).toContain(runnerPod.spec.nodeName)
}
})
})
@@ -1,28 +0,0 @@
import {
isRWXTestEnabled,
getRWXStorageClass,
RWX_SKIP_MESSAGE
} from './test-setup'
describe('RWX Test Contract Demo', () => {
const describeOrSkip = isRWXTestEnabled() ? describe : describe.skip
describeOrSkip('RWX volume tests', () => {
it('should use RWX storage class when enabled', () => {
const storageClass = getRWXStorageClass()
expect(storageClass).toBeDefined()
expect(typeof storageClass).toBe('string')
})
it('should verify both env vars are required', () => {
expect(process.env.ACTIONS_RUNNER_K8S_TEST_ENABLE_RWX).toBe('true')
expect(
process.env.ACTIONS_RUNNER_K8S_TEST_RWX_STORAGE_CLASS
).toBeDefined()
})
})
if (!isRWXTestEnabled()) {
it(RWX_SKIP_MESSAGE, () => {})
}
})
-119
View File
@@ -1,119 +0,0 @@
import * as k8s from '@kubernetes/client-node'
import * as fs from 'fs'
import { cleanupJob, prepareJob, runScriptStep } from '../src/hooks'
import {
TestHelper,
isRWXTestEnabled,
getRWXStorageClass,
RWX_SKIP_MESSAGE
} from './test-setup'
import { RunScriptStepArgs } from 'hooklib'
jest.useRealTimers()
const kc = new k8s.KubeConfig()
kc.loadFromDefault()
const k8sApi = kc.makeApiClient(k8s.CoreV1Api)
describe('RWX Volume Tests', () => {
const describeOrSkip = isRWXTestEnabled() ? describe : describe.skip
describeOrSkip('RWX volume integration', () => {
let testHelper: TestHelper
let rwxPvcName: string
let prepareJobData: any
let prepareJobOutputFilePath: string
beforeEach(async () => {
testHelper = new TestHelper()
await testHelper.initialize()
const podName = process.env.ACTIONS_RUNNER_POD_NAME
rwxPvcName = `${podName}-work-rwx`
const volumeClaim: k8s.V1PersistentVolumeClaim = {
metadata: {
name: rwxPvcName
},
spec: {
accessModes: ['ReadWriteMany'],
volumeMode: 'Filesystem',
storageClassName: getRWXStorageClass(),
resources: {
requests: {
storage: '1Gi'
}
}
}
}
await k8sApi.createNamespacedPersistentVolumeClaim({
namespace: 'default',
body: volumeClaim
})
process.env.ACTIONS_RUNNER_CLAIM_NAME = rwxPvcName
prepareJobData = testHelper.getPrepareJobDefinition()
prepareJobOutputFilePath = testHelper.createFile(
'prepare-job-output.json'
)
})
afterAll(async () => {
if (rwxPvcName) {
try {
await k8sApi.deleteNamespacedPersistentVolumeClaim({
name: rwxPvcName,
namespace: 'default'
})
} catch {
// Ignore cleanup errors - PVC may not exist
}
}
})
afterEach(async () => {
await testHelper.cleanup()
})
it('should successfully run hook flow with RWX volume', async () => {
await expect(
prepareJob(prepareJobData.args, prepareJobOutputFilePath)
).resolves.not.toThrow()
const prepareJobOutputJson = fs.readFileSync(prepareJobOutputFilePath)
const prepareJobOutputData = JSON.parse(prepareJobOutputJson.toString())
const scriptStepData = testHelper.getRunScriptStepDefinition()
await expect(
runScriptStep(
scriptStepData.args as RunScriptStepArgs,
prepareJobOutputData.state
)
).resolves.not.toThrow()
await expect(cleanupJob()).resolves.not.toThrow()
})
it('should verify RWX PVC was created with correct access mode', async () => {
const pvc = await k8sApi.readNamespacedPersistentVolumeClaim({
name: rwxPvcName,
namespace: 'default'
})
expect(pvc.spec?.accessModes).toContain('ReadWriteMany')
expect(pvc.spec?.storageClassName).toBe(getRWXStorageClass())
expect(pvc.spec?.volumeMode).toBe('Filesystem')
})
it('should verify RWX claim name is set correctly', () => {
expect(process.env.ACTIONS_RUNNER_CLAIM_NAME).toBe(rwxPvcName)
})
})
if (!isRWXTestEnabled()) {
it(RWX_SKIP_MESSAGE, () => {})
}
})
-142
View File
@@ -9,7 +9,6 @@ const kc = new k8s.KubeConfig()
kc.loadFromDefault()
const k8sApi = kc.makeApiClient(k8s.CoreV1Api)
const k8sStorageApi = kc.makeApiClient(k8s.StorageV1Api)
export class TestHelper {
private tempDirPath: string
@@ -47,7 +46,6 @@ export class TestHelper {
await this.cleanupK8sResources()
try {
await this.createTestVolume()
await this.createTestJobPod()
} catch (e) {
console.log(e)
@@ -64,24 +62,6 @@ export class TestHelper {
}
async cleanupK8sResources(): Promise<void> {
await k8sApi
.deleteNamespacedPersistentVolumeClaim({
name: `${this.podName}-work`,
namespace: 'default',
gracePeriodSeconds: 0
})
.catch((e: k8s.ApiException<any>) => {
if (e.code !== 404) {
console.error(JSON.stringify(e))
}
})
await k8sApi
.deletePersistentVolume({ name: `${this.podName}-pv` })
.catch((e: k8s.ApiException<any>) => {
if (e.code !== 404) {
console.error(JSON.stringify(e))
}
})
await k8sApi
.deleteNamespacedPod({
name: this.podName,
@@ -104,14 +84,6 @@ export class TestHelper {
console.error(JSON.stringify(e))
}
})
await k8sStorageApi
.deleteStorageClass({ name: `${this.podName}-storage` })
.catch((e: k8s.ApiException<any>) => {
if (e.code !== 404) {
console.error(JSON.stringify(e))
}
})
}
createFile(fileName?: string): string {
const filePath = `${this.tempDirPath}/${fileName || uuidv4()}`
@@ -148,58 +120,6 @@ export class TestHelper {
await k8sApi.createNamespacedPod({ namespace: 'default', body: pod })
}
async createTestVolume(): Promise<void> {
const storageClassName = `${this.podName}-storage`
const sc: k8s.V1StorageClass = {
metadata: {
name: storageClassName
},
provisioner: 'kubernetes.io/no-provisioner',
volumeBindingMode: 'Immediate'
}
await k8sStorageApi.createStorageClass({ body: sc })
const volume: k8s.V1PersistentVolume = {
metadata: {
name: `${this.podName}-pv`
},
spec: {
storageClassName,
capacity: {
storage: '2Gi'
},
volumeMode: 'Filesystem',
accessModes: ['ReadWriteOnce'],
hostPath: {
path: `${this.tempDirPath}/_work`
}
}
}
await k8sApi.createPersistentVolume({ body: volume })
const volumeClaim: k8s.V1PersistentVolumeClaim = {
metadata: {
name: `${this.podName}-work`
},
spec: {
accessModes: ['ReadWriteOnce'],
volumeMode: 'Filesystem',
storageClassName,
volumeName: `${this.podName}-pv`,
resources: {
requests: {
storage: '1Gi'
}
}
}
}
await k8sApi.createNamespacedPersistentVolumeClaim({
namespace: 'default',
body: volumeClaim
})
}
getPrepareJobDefinition(): HookData {
const prepareJob = JSON.parse(
fs.readFileSync(
@@ -243,65 +163,3 @@ export class TestHelper {
return runContainerStep
}
}
/**
* RWX Test Contract:
*
* Tests requiring ReadWriteMany (RWX) volumes MUST be gated by TWO environment variables:
* 1. ACTIONS_RUNNER_K8S_TEST_ENABLE_RWX=true (explicit opt-in)
* 2. ACTIONS_RUNNER_K8S_TEST_RWX_STORAGE_CLASS=<name> (storage class that supports RWX)
*
* If either variable is missing or ACTIONS_RUNNER_K8S_TEST_ENABLE_RWX is not "true",
* the test MUST be skipped with the exact message defined in this contract.
*
* This contract ensures:
* - RWX tests do not fail on clusters without RWX provisioners
* - Test requirements are explicit and documented
* - RWO affinity tests remain independent and always runnable
* - Skip behavior is deterministic (no dynamic cluster probing)
*
* Usage example:
* ```typescript
* import { isRWXTestEnabled, getRWXStorageClass, RWX_SKIP_MESSAGE } from './test-setup'
*
* describe('RWX Test Suite', () => {
* const describeOrSkip = isRWXTestEnabled() ? describe : describe.skip
*
* describeOrSkip('RWX volume tests', () => {
* it('should test RWX functionality', async () => {
* const storageClass = getRWXStorageClass()
* // ... test code using storageClass
* })
* })
*
* if (!isRWXTestEnabled()) {
* it(RWX_SKIP_MESSAGE, () => {})
* }
* })
* ```
*/
/**
* Checks if RWX tests should run based on environment variables.
* @returns true if both ACTIONS_RUNNER_K8S_TEST_ENABLE_RWX=true and ACTIONS_RUNNER_K8S_TEST_RWX_STORAGE_CLASS are set
*/
export function isRWXTestEnabled(): boolean {
const enabled = process.env.ACTIONS_RUNNER_K8S_TEST_ENABLE_RWX === 'true'
const storageClass = process.env.ACTIONS_RUNNER_K8S_TEST_RWX_STORAGE_CLASS
return enabled && !!storageClass
}
/**
* Gets the RWX storage class name from environment variable.
* @returns The storage class name, or undefined if not set
*/
export function getRWXStorageClass(): string | undefined {
return process.env.ACTIONS_RUNNER_K8S_TEST_RWX_STORAGE_CLASS
}
/**
* Skip message constant - DO NOT MODIFY
* This exact message must be used when skipping RWX tests
*/
export const RWX_SKIP_MESSAGE =
'RWX tests skipped: set ACTIONS_RUNNER_K8S_TEST_ENABLE_RWX=true and ACTIONS_RUNNER_K8S_TEST_RWX_STORAGE_CLASS'
+6 -12
View File
@@ -1,21 +1,15 @@
<!-- ## Features -->
## Features
- k8s: remove dependency on the runner's volume [#244]
## Bugs
- Change command to remove sudo to fix fs-init initial container [#263]
- Sort 'find' output before hashing for consistency [#267]
- feat: check if required binaries are present [#272]
- Allow non-root container [#264]
- Improve validation checks after copying [#285]
- Fix workingDir permissions issue by creating it within init container [#283]
- Fix event.json not being copied to /github/workflow in kubernetes-novolume mode [#287]
- Reduce the amount of data copied to the workflow pod [#293]
- Overwrite runner file commands [#298]
- docker: fix readOnly volumes in createContainer [#236]
## Misc
- Dependency updates [#276] [#277] [#278] [#279] [#304]
- Group dependabot updates [#289]
- bump all dependencies [#234] [#240] [#239] [#238]
- bump actions [#254]
## SHA-256 Checksums