문제: FE-GATE-013을 감싸는 `scripts/run-in-system-container.sh`는 게이트의
`docker exec`를 앞에서 돌리고, 끝난 뒤에야 `artifacts/`를 되가져온다.
bash는 앞 명령이 끝나야 trap을 돌린다.
- 게이트 도중 TERM(시간 초과)·HUP(터미널 끊김)이 오면 EXIT trap이
컨테이너만 지우고 끝난다. 그때까지 쌓인 게이트 증거는 오지 않는다.
- 래퍼에만 온 INT는 게이트가 끝날 때까지 밀린다. 터미널의 Ctrl-C는 docker
단계가 자기 상태 코드로 끝나서 bash가 다음 줄로 간다. 게이트 전이면
부팅·복사를 이어 가 게이트까지 돈다.
- 정리 trap은 `docker run`이 id를 돌려준 뒤에 걸린다. 그 전에 온 신호는
컨테이너를 남긴다.
- 정리의 docker 호출은 두 번째 Ctrl-C에 끊긴다. Go로 된 docker CLI는
셸이 무시한 SIGINT를 다시 켠다.
고른 방법:
- 게이트는 `docker exec … &` + `wait`로 띄운다. 그래야 trap이 바로 돈다.
- 게이트가 도는 동안 TERM·INT·HUP을 받으면 `on_signal`이 아래를 한다.
- 다른 신호와 PIPE를 무시한다(두 번째 Ctrl-C, 사라진 로그 독자).
- 그때까지 쓴 `artifacts/`를 되가져오고 컨테이너를 지운다.
- EXIT trap을 지우고 같은 신호로 자기를 죽인다(셸에는 128+번호,
`ci:gate`는 신호 이름을 댄다). 그래도 살아 있으면 `exit 128+번호`.
- 게이트가 끝나 되가져오는 중에 온 신호는 다시 복사하지 않는다
(`copying=1`). bash가 그 복사가 끝난 뒤 trap을 돌리므로 복사는 끝나 있다.
- 컨테이너 이름을 `fe-system-container-<uuid>`로 미리 정해 `--name`으로
준다. 정리는 id 없이 이름으로 지운다. 같은 daemon을 쓰는 job
컨테이너들은 PID가 각자 작게 시작해 `$$`·`$RANDOM`으로 지은 이름이 겹칠
수 있고, 겹치면 남의 컨테이너를 지운다.
- `trap cleanup EXIT`를 이미지 build 전에 건다. 게이트 전의 TERM·HUP은
bash 기본 동작대로 바로 끝나고, EXIT trap이 컨테이너를 지운다. INT만
`early_signal`로 받는다. docker 단계가 Ctrl-C에 상태 코드로 끝나면 bash가
계속 가기 때문이다. `early_signal`도 컨테이너를 지운 뒤 그 신호로 끝난다.
- `docker run -d` 동안만 TERM·HUP도 `early_signal`로 미룬다. run은 래퍼가
죽어도 계속 돌아 컨테이너를 만든다. 그 전에 지우면 남는다.
- 정리와 되가져오기의 docker 호출은 `setsid -w`로 자기 세션에서 돈다.
`setsid -w`를 못 쓰는 호스트에서는 그냥 돈다.
- `say`는 stderr 쓰기가 실패해도(터미널 끊김) 스크립트를 끝내지 않는다.
- 운영 문서 FE-GATE-013 절에 신호 때 동작과, SIGKILL 뒤 남은 컨테이너를
찾아 지우는 명령을 적는다.
버린 것:
- `exit 128+번호`로만 끝내기: 셸은 같은 값을 보지만, 프로세스로 부른
쪽(`ci:gate`)은 신호로 죽은 것과 그 상태 코드로 끝난 것을 구분하지
못한다. Ctrl-C를 받은 셸 스크립트를 부른 셸도 신호로 죽은 자식을 봐야
멈춘다.
- 처음부터 `on_signal`을 걸기: 게이트 전 단계(작업 트리 복사 등)가 길면
trap은 그 단계가 끝난 뒤에야 돈다. 되가져올 것도 없는데 TERM·HUP이 그
단계 끝까지 밀린다.
- 신호를 컨테이너 안 게이트에 넘기기: 게이트가 신호를 받아 자기 로그를
쓰게 하려면 안쪽 `ci:gate`에도 신호 처리가 필요하고, 시간 초과 뒤
SIGKILL 전 유예 안에 끝난다는 보장도 없다. 이 변경은 그때까지 쓴 것을
되가져오는 데서 멈춘다.
위험·한계:
- SIGKILL(job 강제 종료, OOM)은 잡을 수 없다. 아무것도 되가져오지 못하고
컨테이너가 남는다. 운영 문서에 `docker ps -a --filter
name=fe-system-container-`와 `docker rm -f`를 적었다.
- 게이트 도중 되가져오는 tar는 게이트가 그때 쓰고 있는 파일을 덜 쓴 채로
가져올 수 있다.
- 게이트 로그(`artifacts/quality/gates/FE-GATE-013.txt`)는 게이트가 끝날
때 쓰므로, 신호로 끊긴 실행에서는 오지 않는다.
- `setsid -w`가 없는 호스트에서는 두 번째 Ctrl-C가 정리를 끊어 컨테이너가
남을 수 있다. 이름은 Linux의 `/proc/sys/kernel/random/uuid`로 짓는다.
- CI run 취소가 래퍼에 어떤 신호로 닿는지는 실제로 취소해 보지 않았다.
runner가 job 컨테이너를 SIGKILL로 끝내면 첫 항목이다.
검증(desktop `scripts/verify.sh`, 깨끗한 worktree):
- RED: 기준 cbed9467 래퍼 + 새 시험 → 새 신호 시험 10개가 모두 실패,
나머지는 통과.
- 변이 16건, 각자 겨눈 시험이 실패:
- on_signal에서 되가져오기를 뺌, 게이트를 앞에서 돌림, on_signal의
자기 kill을 뺌, on_signal이 EXIT trap을 남김 → 게이트 중 신호 시험들.
- `copying` 확인을 뺌, `copying=1`을 뺌 → 게이트 뒤 되가져오는 중 신호.
- 처리기의 신호 무시를 뺌 → 두 번째 신호·독자 없는 SIGHUP.
- `say`의 `|| :`를 뺌 → 독자 없는 SIGHUP. `setsid -w`를 뺌 → 두 번째
신호.
- on_signal을 처음부터 검, INT의 early_signal을 뺌, early_signal의 자기
kill이나 EXIT trap 해제를 뺌 → 작업 트리 복사 중 Ctrl-C.
- id로 지움 → 신호 시험 10개 전부. run 동안의 TERM·HUP trap을 뺌 →
docker run 중 SIGHUP. `trap - TERM HUP`을 뺌 → 작업 트리 복사 중
TERM·HUP.
- 실제 docker(desktop daemon, 실제 이미지)에서 래퍼를 돌려 신호를 보냄:
게이트 중 TERM → SIGTERM으로 끝나고 게이트가 쓴 파일이 옴. 게이트 중
Ctrl-C 두 번 → SIGINT, 파일이 옴. 컨테이너가 생긴 뒤 게이트 전의
Ctrl-C → SIGINT, HUP → SIGHUP. 네 경우 모두 남은 컨테이너 0개.
- GREEN: `tests/unit/ci-gate-host-environment.test.ts` 3회 연속 15 통과.
`lint`·`check:types` rc=0. 신호 시험 timeout은 FE-GATE-005 test:unit에서
잰 최장 1135ms(부하 2.7, test:coverage는 더 짧음).
- merge 단계 게이트는 PR 본문에 적는다.
Refs: fe-ci-next (3b)
581 lines
25 KiB
TypeScript
581 lines
25 KiB
TypeScript
import { spawn, spawnSync } from "node:child_process";
|
|
import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
import { tmpdir } from "node:os";
|
|
import path from "node:path";
|
|
|
|
import { afterEach, describe, expect, it } from "vitest";
|
|
|
|
import { loadCiGateContract } from "../../scripts/contracts/ci-gates.ts";
|
|
import { renderCiWorkflow } from "../../scripts/generate-ci-workflow.ts";
|
|
import { FIXTURE_PNPM_ENVIRONMENT } from "../../scripts/lib/fixture-node-modules.ts";
|
|
import {
|
|
PR_BASE_REF_VARIABLE,
|
|
PR_GATE_SELECTION_PATH,
|
|
SKIPPED_GATE_LINE,
|
|
} from "../../scripts/lib/pr-gate-selection.ts";
|
|
import { childProcessTimeout } from "../helpers/child-process-timeout.ts";
|
|
|
|
/**
|
|
* Longest desktop run of a test below: in FE-GATE-005's test:unit at load 14
|
|
* (2026-11-20). Alone or in test:coverage they took 1.0 to 1.5 s.
|
|
*/
|
|
const GATE_STEP_MS = 3688;
|
|
/**
|
|
* Longest desktop run of a test below: the one on SIGHUP while docker run starts
|
|
* the container, in FE-GATE-005's test:unit at load 2.7 (2026-11-20); its
|
|
* test:coverage run there was shorter, and the others took 0.1 to 0.3 s.
|
|
*/
|
|
const SIGNAL_MS = 1135;
|
|
|
|
const repository = process.cwd();
|
|
const GATE = "FE-GATE-013";
|
|
const STARTED = "container-started";
|
|
/**
|
|
* Stands in for scripts/run-in-system-container.sh: it adds a line for each
|
|
* container that would start, with its command, and exits with the code the
|
|
* test asks for (the real one exits with the command's code), or dies on the
|
|
* signal it asks for (the job's OOM kill, a cancelled run).
|
|
*/
|
|
const STAND_IN_WRAPPER = `#!/bin/sh
|
|
printf '%s\\n' "$*" >> ${STARTED}
|
|
[ -z "\${STAND_IN_SIGNAL:-}" ] || kill -s "$STAND_IN_SIGNAL" $$
|
|
exit "\${STAND_IN_EXIT:-0}"
|
|
`;
|
|
const CONTAINER_WRAPPER = "scripts/run-in-system-container.sh";
|
|
const STAND_IN_CONTAINER = "stand-in-container";
|
|
const CALL_END = "<end>";
|
|
const HELD_CALL_ENDED = "<held call ended>";
|
|
/**
|
|
* Stands in for docker under the real wrapper (SYSTEM_CONTAINER_DOCKER): it
|
|
* writes each call's arguments one per line, then CALL_END, starts a
|
|
* container that is at once running, takes what is piped in, and hands back
|
|
* an empty artifacts archive. For the signal tests: STAND_IN_ARTIFACTS is a
|
|
* folder whose artifacts/ it hands back instead; the first call with
|
|
* STAND_IN_HOLD_CALL in its arguments creates the file STAND_IN_HOLD, waits
|
|
* until STAND_IN_HOLD.sent exists (or STAND_IN_HOLD_TICKS times 50 ms), then
|
|
* creates STAND_IN_HOLD.released and writes HELD_CALL_ENDED as a call; on an
|
|
* INT it ends with status 1 instead, as the docker CLI does on Ctrl-C. With
|
|
* STAND_IN_GATE the gate creates that file and runs until the container is
|
|
* removed. Each call also adds its first argument and its session id to
|
|
* DOCKER_CALLS.sessions.
|
|
*/
|
|
const STAND_IN_DOCKER = `#!/bin/sh
|
|
for argument in "$@"; do printf '%s\\n' "$argument"; done >> "$DOCKER_CALLS"
|
|
echo '${CALL_END}' >> "$DOCKER_CALLS"
|
|
echo "$1 $(cut -d ' ' -f 6 /proc/$$/stat)" >> "$DOCKER_CALLS.sessions"
|
|
case "$1 $2" in
|
|
"run -d") echo ${STAND_IN_CONTAINER} ;;
|
|
"exec -i") cat > /dev/null ;;
|
|
esac
|
|
case "\${STAND_IN_HOLD:+hold} $*" in
|
|
"hold "*"\${STAND_IN_HOLD_CALL:-}"*)
|
|
if [ ! -f "$STAND_IN_HOLD" ]; then
|
|
trap 'exit 1' INT
|
|
: > "$STAND_IN_HOLD"
|
|
i=0
|
|
while [ ! -f "$STAND_IN_HOLD.sent" ] && [ $i -lt "\${STAND_IN_HOLD_TICKS:-600}" ]; do sleep 0.05; i=$((i + 1)); done
|
|
: > "$STAND_IN_HOLD.released"
|
|
printf '%s\\n' '${HELD_CALL_ENDED}' '${CALL_END}' >> "$DOCKER_CALLS"
|
|
fi ;;
|
|
esac
|
|
case "$*" in
|
|
*is-system-running*) echo running ;;
|
|
*"-cf - artifacts"*)
|
|
if [ -n "\${STAND_IN_ARTIFACTS:-}" ]; then tar -C "$STAND_IN_ARTIFACTS" -cf - artifacts; else tar -cf - -T /dev/null; fi ;;
|
|
*"${STAND_IN_CONTAINER} corepack pnpm ci:gate -- "*)
|
|
if [ -n "\${STAND_IN_GATE:-}" ]; then echo $$ > "$STAND_IN_GATE.pid"; : > "$STAND_IN_GATE"; exec sleep 600; fi ;;
|
|
"rm -f "*)
|
|
if [ -n "\${STAND_IN_GATE:-}" ] && [ -f "$STAND_IN_GATE.pid" ]; then kill "$(cat "$STAND_IN_GATE.pid")" 2> /dev/null || :; fi ;;
|
|
esac
|
|
exit 0
|
|
`;
|
|
|
|
function executable(file: string, content: string): void {
|
|
mkdirSync(path.dirname(file), { recursive: true });
|
|
writeFileSync(file, content);
|
|
chmodSync(file, 0o755);
|
|
}
|
|
|
|
/**
|
|
* A checkout with the real container wrapper and its Dockerfile, the docker
|
|
* stand-in, and a node whose install is one small file: the wrapper copies the
|
|
* caller's node into the container.
|
|
*/
|
|
function wrapperCheckout(root: string): string {
|
|
const checkout = path.join(root, "checkout");
|
|
for (const file of [CONTAINER_WRAPPER, "config/ci/system-container.Dockerfile"]) {
|
|
mkdirSync(path.dirname(path.join(checkout, file)), { recursive: true });
|
|
writeFileSync(path.join(checkout, file), readFileSync(path.join(repository, file)));
|
|
}
|
|
chmodSync(path.join(checkout, CONTAINER_WRAPPER), 0o755);
|
|
git(checkout, "init", "--quiet");
|
|
git(checkout, "add", ".");
|
|
git(checkout, "commit", "--quiet", "-m", "wrapper");
|
|
executable(path.join(root, "docker"), STAND_IN_DOCKER);
|
|
executable(path.join(root, "node/bin/node"), "#!/bin/sh\nexit 0\n");
|
|
return checkout;
|
|
}
|
|
|
|
const GATE_COMMAND = ["corepack", "pnpm", "ci:gate", "--", GATE];
|
|
|
|
/**
|
|
* The environment the real wrapper runs in under wrapperCheckout: the node
|
|
* stand-in first on PATH, the docker stand-in writing its calls to `calls`,
|
|
* and no corepack cache or pnpm store to copy in.
|
|
*/
|
|
function wrapperEnvironment(
|
|
root: string,
|
|
calls: string,
|
|
extra: Readonly<Record<string, string>>,
|
|
): NodeJS.ProcessEnv {
|
|
return {
|
|
...process.env,
|
|
PATH: `${path.join(root, "node/bin")}${path.delimiter}${process.env["PATH"] ?? ""}`,
|
|
SYSTEM_CONTAINER_DOCKER: path.join(root, "docker"),
|
|
DOCKER_CALLS: calls,
|
|
COREPACK_HOME: path.join(root, "no-corepack"),
|
|
PNPM_CONFIG_STORE_DIR: "",
|
|
PNPM_CONFIG_CACHE_DIR: "",
|
|
...extra,
|
|
};
|
|
}
|
|
|
|
/** Each docker call the stand-in wrote, as its arguments. */
|
|
function dockerCalls(calls: string): string[][] {
|
|
return readFileSync(calls, "utf8")
|
|
.split(`${CALL_END}\n`)
|
|
.map((call) => call.split("\n").filter((argument) => argument !== ""))
|
|
.filter((call) => call.length > 0);
|
|
}
|
|
|
|
/** The merge job's run line for FE-GATE-013, as the generated workflow has it. */
|
|
async function gateRunLine(): Promise<string> {
|
|
const workflow = renderCiWorkflow(await loadCiGateContract(repository));
|
|
const lines = workflow.split("\n").filter((line) => line.includes(`ci:gate -- ${GATE}`));
|
|
expect(lines).toHaveLength(1);
|
|
return lines[0]!.replace(/^ +run: /u, "");
|
|
}
|
|
|
|
function git(cwd: string, ...args: string[]): void {
|
|
const result = spawnSync(
|
|
"git",
|
|
["-c", "user.name=t", "-c", "user.email=t@example.invalid", "-c", "init.defaultBranch=main", ...args],
|
|
{ cwd, encoding: "utf8" },
|
|
);
|
|
if (result.status !== 0) throw new Error(`git ${args.join(" ")}: ${result.stderr}`);
|
|
}
|
|
|
|
/**
|
|
* A shallow PR checkout like a merge job's: this repository's gate contract
|
|
* and path table on main, the PR's one file on top, `ci:gate` running this
|
|
* repository's runner, and the stand-in container wrapper.
|
|
*/
|
|
function prCheckout(root: string, prFile: string): string {
|
|
const origin = path.join(root, "origin");
|
|
for (const file of ["config/ci/gates.json", PR_GATE_SELECTION_PATH]) {
|
|
mkdirSync(path.dirname(path.join(origin, file)), { recursive: true });
|
|
writeFileSync(path.join(origin, file), readFileSync(path.join(repository, file)));
|
|
}
|
|
const packageDocument = JSON.parse(readFileSync(path.join(repository, "package.json"), "utf8")) as {
|
|
scripts: Record<string, string>;
|
|
};
|
|
// The contract loader refuses a package without the gates' scripts, so the
|
|
// checkout keeps them all; only `ci:gate` points at this repository's runner.
|
|
packageDocument.scripts["ci:gate"] = `node ${path.join(repository, "scripts/run-ci-gate.ts")}`;
|
|
writeFileSync(path.join(origin, "package.json"), `${JSON.stringify(packageDocument)}\n`);
|
|
executable(path.join(origin, CONTAINER_WRAPPER), STAND_IN_WRAPPER);
|
|
git(origin, "init", "--quiet");
|
|
git(origin, "add", ".");
|
|
git(origin, "commit", "--quiet", "-m", "base");
|
|
git(origin, "switch", "--quiet", "-c", "pr");
|
|
mkdirSync(path.dirname(path.join(origin, prFile)), { recursive: true });
|
|
writeFileSync(path.join(origin, prFile), "x\n");
|
|
git(origin, "add", ".");
|
|
git(origin, "commit", "--quiet", "-m", "pr");
|
|
git(root, "clone", "--quiet", "--depth", "1", "--branch", "pr", `file://${origin}`, "checkout");
|
|
return path.join(root, "checkout");
|
|
}
|
|
|
|
function run(command: string, cwd: string, environment: Readonly<Record<string, string>>) {
|
|
return spawnSync("sh", ["-c", command], {
|
|
cwd,
|
|
encoding: "utf8",
|
|
env: { ...process.env, ...FIXTURE_PNPM_ENVIRONMENT, CI: "false", ...environment },
|
|
});
|
|
}
|
|
|
|
// fe-ci-next (2). The container wrapper got only the gate's own environment,
|
|
// not the PR's base branch, so the PR selection inside it always ran
|
|
// FE-GATE-013: a PR the path table keeps away from the gate still started the
|
|
// system container and ran it (3 to 5 runner minutes). Handing the base
|
|
// branch in would let a `git fetch` without a timeout hang the job from
|
|
// inside the container. The job decides first, where the base branch is.
|
|
describe("FE-GATE-013 in a merge job", { timeout: childProcessTimeout(GATE_STEP_MS) }, () => {
|
|
it("skips the gate in the job for a PR the path table keeps away, and starts no container", async () => {
|
|
const root = mkdtempSync(path.join(tmpdir(), "ci-gate-host-environment-"));
|
|
try {
|
|
const checkout = prCheckout(root, "docs/only.md");
|
|
const result = run(await gateRunLine(), checkout, { [PR_BASE_REF_VARIABLE]: "main" });
|
|
|
|
expect(existsSync(path.join(checkout, STARTED))).toBe(false);
|
|
expect(result.status).toBe(0);
|
|
const skipped = result.stdout.split("\n").filter((line) => SKIPPED_GATE_LINE.test(line));
|
|
expect(skipped).toEqual([expect.stringMatching(new RegExp(`^건너뜀: ${GATE} — `, "u"))]);
|
|
expect(readFileSync(path.join(checkout, "artifacts/quality/gates/FE-GATE-013.txt"), "utf8")).toBe(
|
|
`${skipped[0]}\n`,
|
|
);
|
|
} finally {
|
|
rmSync(root, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
it("runs the gate in the container for a PR that reaches it, with the container's exit code", async () => {
|
|
const root = mkdtempSync(path.join(tmpdir(), "ci-gate-host-environment-"));
|
|
try {
|
|
const checkout = prCheckout(root, "src/reaches-the-gate.ts");
|
|
const result = run(await gateRunLine(), checkout, {
|
|
[PR_BASE_REF_VARIABLE]: "main",
|
|
STAND_IN_EXIT: "7",
|
|
});
|
|
|
|
expect(readFileSync(path.join(checkout, STARTED), "utf8")).toBe(`corepack pnpm ci:gate -- ${GATE}\n`);
|
|
expect(result.status).toBe(7);
|
|
expect(result.stdout).not.toMatch(/^건너뜀: /mu);
|
|
} finally {
|
|
rmSync(root, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
it("enters the container once from ci:gate in the job and hands back its exit code", () => {
|
|
const root = mkdtempSync(path.join(tmpdir(), "ci-gate-host-environment-"));
|
|
try {
|
|
// A main run: no PR base branch, so the gate runs.
|
|
const checkout = prCheckout(root, "docs/only.md");
|
|
const result = run(
|
|
`corepack pnpm ci:gate -- ${GATE} --enter-host-environment`,
|
|
checkout,
|
|
{ [PR_BASE_REF_VARIABLE]: "", STAND_IN_EXIT: "3" },
|
|
);
|
|
|
|
expect(readFileSync(path.join(checkout, STARTED), "utf8")).toBe(`corepack pnpm ci:gate -- ${GATE}\n`);
|
|
expect(result.status).toBe(3);
|
|
} finally {
|
|
rmSync(root, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
it("names the signal a container entry died on and ends as a shell would", () => {
|
|
const root = mkdtempSync(path.join(tmpdir(), "ci-gate-host-environment-"));
|
|
try {
|
|
const checkout = prCheckout(root, "docs/only.md");
|
|
const result = run(
|
|
`corepack pnpm ci:gate -- ${GATE} --enter-host-environment`,
|
|
checkout,
|
|
{ [PR_BASE_REF_VARIABLE]: "", STAND_IN_SIGNAL: "TERM" },
|
|
);
|
|
|
|
expect(readFileSync(path.join(checkout, STARTED), "utf8")).toBe(`corepack pnpm ci:gate -- ${GATE}\n`);
|
|
expect(result.stderr).toContain(`${GATE}: ${CONTAINER_WRAPPER} ended on SIGTERM`);
|
|
expect(result.status).toBe(128 + 15);
|
|
} finally {
|
|
rmSync(root, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
// The container must not select again: with the base branch it would fetch
|
|
// from inside, where a `git fetch` without a timeout can hang the job.
|
|
// ci:gate hands the wrapper the job's whole environment, so what the
|
|
// container gets is what the wrapper's `docker exec` passes.
|
|
it("hands the container the job's gate environment and no PR base branch", () => {
|
|
const root = mkdtempSync(path.join(tmpdir(), "ci-gate-host-environment-"));
|
|
try {
|
|
const checkout = wrapperCheckout(root);
|
|
const calls = path.join(root, "docker-calls");
|
|
const result = spawnSync(CONTAINER_WRAPPER, GATE_COMMAND, {
|
|
cwd: checkout,
|
|
encoding: "utf8",
|
|
env: wrapperEnvironment(root, calls, { CI: "true", [PR_BASE_REF_VARIABLE]: "main" }),
|
|
});
|
|
expect(result.status, result.stderr).toBe(0);
|
|
|
|
const gateCalls = dockerCalls(calls).filter((call) =>
|
|
call.join(" ").endsWith(`${STAND_IN_CONTAINER} ${GATE_COMMAND.join(" ")}`),
|
|
);
|
|
expect(gateCalls).toHaveLength(1);
|
|
const [call] = gateCalls as [string[]];
|
|
expect(call.slice(0, 3)).toEqual(["exec", "-w", "/work"]);
|
|
const options = call.slice(3, call.indexOf(STAND_IN_CONTAINER));
|
|
// Every option is `-e NAME=value`, so the names below are all it passes.
|
|
expect(options.filter((_, index) => index % 2 === 0).every((option) => option === "-e")).toBe(true);
|
|
const names = options.filter((_, index) => index % 2 === 1).map((pair) => pair.split("=", 1)[0]);
|
|
expect(names).toContain("CI");
|
|
expect(names).not.toContain(PR_BASE_REF_VARIABLE);
|
|
} finally {
|
|
rmSync(root, { recursive: true, force: true });
|
|
}
|
|
});
|
|
});
|
|
|
|
// fe-ci-next (3b). A timeout's TERM, Ctrl-C (INT) or a closed terminal (HUP)
|
|
// ended the wrapper before it copied artifacts/ back: the copy came only after
|
|
// the gate, and a running gate kept the shell from reaching a trap. Now, while
|
|
// the gate runs, such a signal copies back what it wrote so far, removes the
|
|
// container, and ends the wrapper on that signal, so a shell that ran it sees
|
|
// 128 + its number and ci:gate in the job names it. Before the gate the
|
|
// wrapper still ends at once. Each run is the real wrapper on the docker
|
|
// stand-in, in its own process group so that nothing it started outlives the
|
|
// test.
|
|
describe("the container wrapper on a signal", { timeout: childProcessTimeout(SIGNAL_MS) }, () => {
|
|
const SIGNALS = ["SIGTERM", "SIGINT", "SIGHUP"] as const;
|
|
const groups: number[] = [];
|
|
|
|
afterEach(() => {
|
|
for (const group of groups.splice(0)) {
|
|
try {
|
|
process.kill(-group, "SIGKILL");
|
|
} catch {
|
|
// Everything in it has ended.
|
|
}
|
|
}
|
|
});
|
|
|
|
type Step = {
|
|
/** The file the stand-in creates when it holds a call. */
|
|
held: string;
|
|
signal: NodeJS.Signals;
|
|
/** Creates `held`.sent after the signal, so the held call goes on (default true). */
|
|
release?: boolean;
|
|
/** Sends the signal to the wrapper's process group, as Ctrl-C does, instead of to the wrapper alone. */
|
|
group?: boolean;
|
|
};
|
|
|
|
/**
|
|
* Starts the real wrapper on the gate command and, for each step in turn,
|
|
* sends its signal once its `held` file appears; gives how the wrapper ended.
|
|
* With `closeStderr`, the wrapper's stderr has no reader by the first signal.
|
|
*/
|
|
async function signalled(
|
|
root: string,
|
|
steps: readonly Step[],
|
|
extra: Record<string, string>,
|
|
{ closeStderr = false } = {},
|
|
) {
|
|
const checkout = wrapperCheckout(root);
|
|
const calls = path.join(root, "docker-calls");
|
|
const child = spawn(CONTAINER_WRAPPER, GATE_COMMAND, {
|
|
cwd: checkout,
|
|
env: wrapperEnvironment(root, calls, extra),
|
|
stdio: ["ignore", "ignore", "pipe"],
|
|
detached: true,
|
|
});
|
|
groups.push(child.pid!);
|
|
let stderr = "";
|
|
child.stderr.setEncoding("utf8").on("data", (chunk: string) => (stderr += chunk));
|
|
let exit: { code: number | null; signal: NodeJS.Signals | null } | undefined;
|
|
const ended = new Promise<NonNullable<typeof exit>>((resolve) =>
|
|
child.on("exit", (code, signal) => resolve((exit = { code, signal }))),
|
|
);
|
|
for (const { held, signal, release = true, group = false } of steps) {
|
|
while (!existsSync(held)) {
|
|
if (exit) throw new Error(`the wrapper ended before ${path.basename(held)}: ${stderr}`);
|
|
await new Promise((resolve) => setTimeout(resolve, 20));
|
|
}
|
|
if (closeStderr && !child.stderr.destroyed) child.stderr.destroy();
|
|
if (group) process.kill(-child.pid!, signal);
|
|
else child.kill(signal);
|
|
if (release) writeFileSync(`${held}.sent`, "");
|
|
}
|
|
const result = await ended;
|
|
const sessions = readFileSync(`${calls}.sessions`, "utf8")
|
|
.split("\n")
|
|
.filter((line) => line !== "")
|
|
.map((line) => line.split(" "));
|
|
return { ...result, stderr, checkout, calls: dockerCalls(calls), sessions, pid: child.pid! };
|
|
}
|
|
|
|
/** The container's work folder as the docker stand-in hands it back: one artifact the gate wrote before the signal. */
|
|
function containerWork(root: string): string {
|
|
const written = path.join(root, "container-work");
|
|
mkdirSync(path.join(written, "artifacts/quality"), { recursive: true });
|
|
writeFileSync(path.join(written, "artifacts/quality/partial.txt"), "written before the signal\n");
|
|
return written;
|
|
}
|
|
|
|
const copiedBack = (checkout: string) => readFileSync(path.join(checkout, "artifacts/quality/partial.txt"), "utf8");
|
|
const copiesBack = (call: readonly string[]) => call.join(" ").includes("-cf - artifacts");
|
|
const removes = (call: readonly string[]) =>
|
|
call.length === 3 && call[0] === "rm" && call[1] === "-f" && /^fe-system-container-[0-9a-f-]{36}$/u.test(call[2]!);
|
|
const runsGate = (call: readonly string[]) => call.join(" ").endsWith(`${STAND_IN_CONTAINER} ${GATE_COMMAND.join(" ")}`);
|
|
|
|
it.each(SIGNALS)("on %s while the gate runs, copies artifacts/ back, removes the container, and ends on it", async (signal) => {
|
|
const root = mkdtempSync(path.join(tmpdir(), "ci-gate-host-environment-"));
|
|
try {
|
|
const gate = path.join(root, "gate-running");
|
|
const result = await signalled(root, [{ held: gate, signal }], {
|
|
STAND_IN_GATE: gate,
|
|
STAND_IN_ARTIFACTS: containerWork(root),
|
|
});
|
|
|
|
expect(result.signal, result.stderr).toBe(signal);
|
|
expect(result.code).toBeNull();
|
|
expect(copiedBack(result.checkout)).toBe("written before the signal\n");
|
|
expect(result.calls.filter(copiesBack)).toHaveLength(1);
|
|
expect(result.calls.filter(removes)).toHaveLength(1);
|
|
expect(result.calls.findIndex(removes)).toBeGreaterThan(result.calls.findIndex(copiesBack));
|
|
expect(result.stderr).toContain(`system-container: ${signal}: copying artifacts/ back, then ending`);
|
|
} finally {
|
|
rmSync(root, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
// A closed terminal or a gone log reader: writing the message fails.
|
|
it("on SIGHUP with no reader left on stderr, still copies back and removes the container", async () => {
|
|
const root = mkdtempSync(path.join(tmpdir(), "ci-gate-host-environment-"));
|
|
try {
|
|
const gate = path.join(root, "gate-running");
|
|
const result = await signalled(
|
|
root,
|
|
[{ held: gate, signal: "SIGHUP" }],
|
|
{ STAND_IN_GATE: gate, STAND_IN_ARTIFACTS: containerWork(root) },
|
|
{ closeStderr: true },
|
|
);
|
|
|
|
expect(result.signal).toBe("SIGHUP");
|
|
expect(copiedBack(result.checkout)).toBe("written before the signal\n");
|
|
expect(result.calls.filter(removes)).toHaveLength(1);
|
|
} finally {
|
|
rmSync(root, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
// Ctrl-C pressed twice: the second one does not start the copy and the
|
|
// removal again.
|
|
it("on a second signal while it copies back, copies back and removes the container once", async () => {
|
|
const root = mkdtempSync(path.join(tmpdir(), "ci-gate-host-environment-"));
|
|
try {
|
|
const gate = path.join(root, "gate-running");
|
|
const copying = path.join(root, "copying-back");
|
|
const result = await signalled(
|
|
root,
|
|
[
|
|
{ held: gate, signal: "SIGINT" },
|
|
{ held: copying, signal: "SIGINT" },
|
|
],
|
|
{
|
|
STAND_IN_GATE: gate,
|
|
STAND_IN_ARTIFACTS: containerWork(root),
|
|
STAND_IN_HOLD: copying,
|
|
STAND_IN_HOLD_CALL: "-cf - artifacts",
|
|
},
|
|
);
|
|
|
|
expect(result.signal, result.stderr).toBe("SIGINT");
|
|
expect(copiedBack(result.checkout)).toBe("written before the signal\n");
|
|
expect(result.calls.filter(copiesBack)).toHaveLength(1);
|
|
expect(result.calls.filter(removes)).toHaveLength(1);
|
|
// The docker CLI turns an ignored SIGINT back on, so the copy and the
|
|
// removal must be out of the reach of the terminal's Ctrl-C: each runs
|
|
// in a session of its own. The wrapper leads its own (detached).
|
|
const late = result.sessions.filter(([command]) => command === "rm" || command === "exec").slice(-2);
|
|
expect(late.map(([command]) => command)).toEqual(["exec", "rm"]);
|
|
for (const [, session] of late) expect(session).not.toBe(String(result.pid));
|
|
} finally {
|
|
rmSync(root, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
// The gate has ended and its copy is under way: the signal waits for it
|
|
// instead of copying again.
|
|
it("on a signal while it copies back after the gate, copies back once and ends on it", async () => {
|
|
const root = mkdtempSync(path.join(tmpdir(), "ci-gate-host-environment-"));
|
|
try {
|
|
const copying = path.join(root, "copying-back");
|
|
const result = await signalled(root, [{ held: copying, signal: "SIGTERM" }], {
|
|
STAND_IN_ARTIFACTS: containerWork(root),
|
|
STAND_IN_HOLD: copying,
|
|
STAND_IN_HOLD_CALL: "-cf - artifacts",
|
|
});
|
|
|
|
expect(result.signal, result.stderr).toBe("SIGTERM");
|
|
expect(copiedBack(result.checkout)).toBe("written before the signal\n");
|
|
expect(result.calls.filter(copiesBack)).toHaveLength(1);
|
|
expect(result.calls.filter(removes)).toHaveLength(1);
|
|
expect(result.stderr).toContain("system-container: SIGTERM: ending after the copy back");
|
|
} finally {
|
|
rmSync(root, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
// Ctrl-C reaches the step in front too, and a docker step ends on it with a
|
|
// status of its own; bash would carry on after it.
|
|
it("on Ctrl-C while it copies the working tree in, ends on SIGINT and removes the container", async () => {
|
|
const root = mkdtempSync(path.join(tmpdir(), "ci-gate-host-environment-"));
|
|
try {
|
|
const copyingIn = path.join(root, "copying-in");
|
|
const result = await signalled(root, [{ held: copyingIn, signal: "SIGINT", release: false, group: true }], {
|
|
STAND_IN_HOLD: copyingIn,
|
|
STAND_IN_HOLD_CALL: "mkdir -p /work &&",
|
|
});
|
|
|
|
expect(result.signal, result.stderr).toBe("SIGINT");
|
|
expect(result.calls.some(runsGate)).toBe(false);
|
|
expect(result.calls.filter(removes)).toHaveLength(1);
|
|
expect(result.stderr).toContain("system-container: SIGINT: ending before the command started");
|
|
} finally {
|
|
rmSync(root, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
// `docker run` makes the container before it hands its id back, and goes on
|
|
// without the wrapper: the cleanup waits for it, then removes the container
|
|
// by the name the wrapper gave it. The held run ends by itself after 1 s.
|
|
it("on SIGHUP while docker run starts the container, removes it by its name once the run returns", async () => {
|
|
const root = mkdtempSync(path.join(tmpdir(), "ci-gate-host-environment-"));
|
|
try {
|
|
const starting = path.join(root, "starting");
|
|
const result = await signalled(root, [{ held: starting, signal: "SIGHUP", release: false }], {
|
|
STAND_IN_HOLD: starting,
|
|
STAND_IN_HOLD_CALL: "run -d",
|
|
STAND_IN_HOLD_TICKS: "20",
|
|
});
|
|
|
|
expect(result.signal, result.stderr).toBe("SIGHUP");
|
|
const run = result.calls.find((call) => call[0] === "run")!;
|
|
const name = run[run.indexOf("--name") + 1];
|
|
expect(result.calls.filter(removes)).toEqual([["rm", "-f", name]]);
|
|
expect(result.calls.findIndex(removes)).toBeGreaterThan(
|
|
result.calls.findIndex((call) => call[0] === HELD_CALL_ENDED),
|
|
);
|
|
expect(result.calls.findIndex((call) => call[0] === HELD_CALL_ENDED)).toBeGreaterThan(-1);
|
|
} finally {
|
|
rmSync(root, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
// Before the gate there is nothing to copy back, and a step such as copying
|
|
// the working tree in can take long: the wrapper ends at once, not after the
|
|
// step, and still removes the container. A signal to the wrapper alone, as a
|
|
// parent process sends it (Ctrl-C reaches the step too).
|
|
it.each(["SIGTERM", "SIGHUP"] as const)(
|
|
"on %s while it copies the working tree in, ends at once and removes the container",
|
|
async (signal) => {
|
|
const root = mkdtempSync(path.join(tmpdir(), "ci-gate-host-environment-"));
|
|
try {
|
|
const copyingIn = path.join(root, "copying-in");
|
|
const result = await signalled(root, [{ held: copyingIn, signal, release: false }], {
|
|
STAND_IN_HOLD: copyingIn,
|
|
STAND_IN_HOLD_CALL: "mkdir -p /work &&",
|
|
});
|
|
|
|
expect(result.signal, result.stderr).toBe(signal);
|
|
expect(existsSync(`${copyingIn}.released`)).toBe(false);
|
|
expect(result.calls.some(copiesBack)).toBe(false);
|
|
expect(result.calls.some(runsGate)).toBe(false);
|
|
expect(result.calls.filter(removes)).toHaveLength(1);
|
|
} finally {
|
|
rmSync(root, { recursive: true, force: true });
|
|
}
|
|
},
|
|
);
|
|
});
|