fix(ci): 컨테이너 래퍼가 TERM·INT·HUP에도 artifacts를 되가져오고 컨테이너를 지운다 #74

Merged
donghyeon.kang merged 2 commits from donghyeon.kang/fix/system-container-signal-copy-back AGit into main 2026-11-20 05:30:23 +00:00
4 changed files with 420 additions and 34 deletions
+1
View File
@@ -151,6 +151,7 @@ Gitea runner에서 merge 단계를 초록으로 만들고, worker를 늘리지
| 끊을 곳 없는 긴 RELEASE_ID·build id, 서버의 상관 ID(128자까지)와 item id가 320px 화면을 넘치지 않는다. 지원 참조는 새 `SupportReference` 하나가 그리고(`ui-support-reference`), 홈 런타임 요약·부팅 오류 화면의 값·상세 화면 메타데이터의 값은 `overflow-wrap: anywhere`를 쓴다. 홈은 grid 항목이라 고치기 전 세 엔진에서 594~641px로 넓어졌다. 기능 화면이 지원 참조를 직접 그렸으면 디자인 시스템 배럴의 컴포넌트에 넘긴다. 오류 화면은 `TerminalErrorSurface`·`StatusPage`의 `supportReference`로 넘긴다. `AsyncSurface`의 `supportReference`는 결과를 모르는 저장일 때만 그려지고(`useAppForm().supportReference`), 오류로 끝난 상태는 `failure.requestId`를 스스로 그린다. `SupportReference`는 배럴 밖이다 | `src/presentation/components/support-reference.tsx`, `src/presentation/components/async-surface.tsx`, `src/presentation/templates/page-templates.tsx`, `src/presentation/boundaries/`, `src/presentation/styles/theme/`, `tests/e2e/responsive.spec.ts`, `tests/e2e/generated-feature.spec.ts`, `tests/e2e/support/reflow.ts` | `953e1ca5` |
| `scripts/verify.sh`가 RELEASE_ID에 checkout 브랜치 이름을 넣지 않고 CI와 같은 꼴의 고정 ref(`refs/heads/verify-1-1`)를 쓴다. 같은 트리의 FE-GATE-008 결과가 브랜치 이름 길이로 갈렸다 | `scripts/verify.sh`, `scripts/tests/test_verify.py` | `4ab62f81` |
| 제거 drill의 사본 준비(`prepareRemovalFixture`)가 checkout에 없는 `optional` 등록부 항목(`recipes`)을 건너뛴다. 없는 필수 경로에서는 cp의 ENOENT 스택 대신, 사본 폴더를 비우기 전에 그 경로와 고르는 등록부 항목, 고칠 곳(경로를 되살리거나 항목을 지우거나 그 항목의 `setPaths`에서 빼기)을 대고 멈춘다. 등록부가 고르지 않는 경로도 이름으로 댄다. 매뉴얼 03 R1이 추적하는 항목도 drill 사본이나 제품 사본에 없을 수 있으면 `optional`로 적으라고 한다 | `scripts/lib/removal-fixture.ts`, `tests/unit/removal-fixture.test.ts`, `docs/manual/03-outside-feature-folder.md` | `44453592` |
| FE-GATE-013의 시스템 컨테이너 래퍼(`scripts/run-in-system-container.sh`)가 게이트 도중 TERM·INT·HUP(시간 초과, Ctrl-C, 터미널 끊김)을 받으면 그때까지 쌓인 `artifacts/`를 되가져오고 컨테이너를 지운 뒤 그 신호로 끝난다. 게이트 전에 받으면 컨테이너만 지우고 그 신호로 끝난다. 고치기 전에는 게이트 도중 TERM·HUP에 증거 없이 끝났고, 게이트 전 Ctrl-C에는 부팅·복사를 이어 가 게이트까지 돌았고, `docker run` 도중의 신호에는 컨테이너가 남았다. 컨테이너 이름은 `fe-system-container-<uuid>`이고 정리는 이름으로 지운다. 게이트 로그는 끝날 때 쓰므로 신호로 끊긴 실행에서는 오지 않는다. SIGKILL 뒤 남은 컨테이너를 찾아 지우는 명령은 운영 문서 FE-GATE-013 절에 있다 | `scripts/run-in-system-container.sh`, `tests/unit/ci-gate-host-environment.test.ts`, `docs/operations/ci-quality-gates.md` | `b5f28e52` |
## 미출시 — `8327e221` → 하네스와 작업 매뉴얼
+6
View File
@@ -261,6 +261,12 @@ runner의 Docker proxy가 안쪽 dind daemon에 컨테이너를 띄운다.
release 단계 provider job은 아직 job 컨테이너에서 돈다.
- runner가 privileged 컨테이너를 막는 설정(rootless dind 등)으로 바뀌면 이
길이 깨진다. 그때는 위 조건을 갖춘 전용 runner(VM 등)로 옮긴다.
- 게이트가 도는 동안 래퍼가 TERM·INT·HUP(시간 초과, Ctrl-C, 터미널 끊김)을 받으면
그때까지 쌓인 `artifacts/`를 되가져오고 컨테이너를 지운 뒤 그 신호로 끝난다(셸에는
128+신호 번호). 게이트 로그는 게이트가 끝날 때 쓰므로 이때는 오지 않는다. 게이트
전에 받으면 컨테이너만 지우고 그 신호로 끝난다. SIGKILL(job 강제 종료, OOM)은
잡을 수 없어 아무것도 되가져오지 못하고 컨테이너가 남는다.
`docker ps -a --filter name=fe-system-container-`로 찾아 `docker rm -f`로 지운다.
- 컨테이너의 첫 프로세스는 systemd를 띄우기 전에 root cgroup의 프로세스를
`init.scope`로 옮기고 root에 cgroup 제어기를 켠다. 그러지 않으면 부팅 중에
닿은 `docker exec`가 root cgroup에 들어가 systemd가 제어기를 넘기지 못하고,
+77 -14
View File
@@ -9,13 +9,17 @@
# The command runs as root there, so bubblewrap needs no unprivileged user namespace from the host kernel
# (Ubuntu 23.10+ refuses those to unconfined processes). Node and pnpm come from the caller, copied in with the
# working tree and its git history; artifacts/ is copied back and the container removed, whatever the result.
# A TERM, INT or HUP (a timeout, Ctrl-C, a closed terminal) while the command runs copies back what it wrote so
# far, removes the container and ends this script on that signal. Before that it only removes the container and
# ends on the signal. SIGKILL cannot be caught: the container (fe-system-container-<uuid>) stays.
# Docker: the CI job reaches the runner's own daemon through its Docker proxy
# (platform-core infrastructure/ci/gitea-runner); on desktop it is the host daemon.
# Environment: SYSTEM_CONTAINER_DOCKER (default docker), SYSTEM_CONTAINER_KEEP=1 keeps the container for debugging.
# Exit code: the command's, or 3 when the container could not be prepared.
# Exit code: the command's, or 3 when the container could not be prepared; on TERM, INT or HUP, death by that
# signal (128 + its number to a shell).
set -euo pipefail
[ $# -gt 0 ] || { sed -n '2,13p' "$0" | sed 's/^# \{0,1\}//' >&2; exit 2; }
[ $# -gt 0 ] || { sed -n '2,19p' "$0" | sed 's/^# \{0,1\}//' >&2; exit 2; }
docker=${SYSTEM_CONTAINER_DOCKER:-docker}
root=$(git rev-parse --show-toplevel)
cd "$root"
@@ -35,9 +39,40 @@ for name in PNPM_CONFIG_STORE_DIR PNPM_CONFIG_CACHE_DIR; do
fi
done
say() { echo "system-container: $*" >&2; }
# A message must not end the script: a closed terminal or a gone log reader makes the write fail.
say() { echo "system-container: $*" >&2 || :; }
fail() { say "$*"; exit 3; }
# The container's name, so the cleanup finds it even when a signal comes before `docker run` gives its id. A
# job container's PIDs start over, so the name is random.
container_name="fe-system-container-$(cat /proc/sys/kernel/random/uuid)"
# The cleanup's docker calls run in a session of their own: the docker CLI ends a call on Ctrl-C even when the
# shell ignores it (Go turns an ignored SIGINT back on), so a second Ctrl-C would cancel the copy or the removal.
own_session=()
if setsid -w true 2> /dev/null; then own_session=(setsid -w); fi
cleanup() {
# The boot step writes to the container log only when it gave up; say so whatever ends the run.
"${own_session[@]}" $docker logs "$container_name" 2>&1 | grep '^system-container:' >&2 || :
if [ "${SYSTEM_CONTAINER_KEEP:-0}" = 1 ]; then
say "kept container $container_name"
else
"${own_session[@]}" $docker rm -f "$container_name" > /dev/null 2>&1 || :
fi
}
# Before the command starts, a TERM or HUP ends the script at once (bash's default), and this trap removes the
# container: bash runs it when a signal ends it too. An INT is trapped, because bash carries on after a step
# that ends on Ctrl-C with a status of its own, as the docker CLI does; it ends the script once that step returns.
trap cleanup EXIT
early_signal() {
trap '' TERM INT HUP PIPE
say "SIG$1: ending before the command started"
cleanup
trap - EXIT "$1"
kill -s "$1" $$
exit $((128 + $2)) # only if the signal did not end it
}
trap 'early_signal INT 2' INT
if ! $docker image inspect "$tag" > /dev/null 2>&1; then
say "building $tag"
$docker build -q -t "$tag" -f "$dockerfile" config/ci > /dev/null || fail "image build failed"
@@ -63,14 +98,13 @@ if [ -n "$controllers" ]; then
done
fi
exec /sbin/init'
cid=$($docker run -d --privileged --cgroupns=private --tmpfs /run --tmpfs /run/lock "$tag" /bin/sh -c "$boot") \
# `docker run` makes the container before it hands back the id, and goes on when this script is gone, so a
# TERM or HUP meanwhile waits for it: a removal before the container exists would leave it behind.
trap 'early_signal TERM 15' TERM
trap 'early_signal HUP 1' HUP
cid=$($docker run -d --name "$container_name" --privileged --cgroupns=private --tmpfs /run --tmpfs /run/lock "$tag" /bin/sh -c "$boot") \
|| fail "container did not start"
cleanup() {
# The boot step writes to the container log only when it gave up; say so whatever ends the run.
$docker logs "$cid" 2>&1 | grep '^system-container:' >&2 || :
if [ "${SYSTEM_CONTAINER_KEEP:-0}" = 1 ]; then say "kept container $cid"; else $docker rm -f "$cid" > /dev/null 2>&1 || :; fi
}
trap cleanup EXIT
trap - TERM HUP
# systemd reaches a final state, then root's lingering user manager opens its bus. Until PID 1 has its own
# bus up, systemctl cannot connect and answers nothing, so ask again for up to a minute.
@@ -115,10 +149,39 @@ exec_env=(-e PATH=/opt/node/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bi
for name in "${pass_env[@]}"; do
[ -z "${!name+x}" ] || exec_env+=(-e "$name=${!name}")
done
copy_back() {
mkdir -p artifacts
"${own_session[@]}" $docker exec "$cid" sh -c '[ -d /work/artifacts ] && tar -C /work -cf - artifacts' \
| tar -C "$root" -xf - || say "copying artifacts back failed"
}
# While the command runs, a TERM, INT or HUP copies back what it wrote so far (the gate's own log comes at its
# end, so it is not there yet), removes the container, and ends the script on that signal itself, so a shell
# sees 128 + its number and ci:gate in the job names it. Another of them, or a gone stderr reader (PIPE),
# does not cut that short. Once the command has ended the copy below has begun: bash runs a trap only after
# the command in front, so the trap finds the copy done.
copying=0
on_signal() {
trap '' TERM INT HUP PIPE
if [ "$copying" = 0 ]; then
say "SIG$1: copying artifacts/ back, then ending"
copy_back
else
say "SIG$1: ending after the copy back"
fi
cleanup
# bash would run the EXIT trap again when the signal ends it.
trap - EXIT "$1"
kill -s "$1" $$
exit $((128 + $2)) # only if the signal did not end it
}
trap 'on_signal TERM 15' TERM
trap 'on_signal INT 2' INT
trap 'on_signal HUP 1' HUP
# In the background, so the trap runs at once: bash runs one only after the command in front ends.
rc=0
$docker exec -w /work "${exec_env[@]}" "$cid" "$@" || rc=$?
$docker exec -w /work "${exec_env[@]}" "$cid" "$@" &
wait $! || rc=$?
# The gate's log and evidence come back even when it failed.
mkdir -p artifacts
$docker exec "$cid" sh -c '[ -d /work/artifacts ] && tar -C /work -cf - artifacts' | tar -C "$root" -xf - \
|| say "copying artifacts back failed"
copying=1
copy_back
exit "$rc"
+336 -20
View File
@@ -1,9 +1,9 @@
import { spawnSync } from "node:child_process";
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 { describe, expect, it } from "vitest";
import { afterEach, describe, expect, it } from "vitest";
import { loadCiGateContract } from "../../scripts/contracts/ci-gates.ts";
import { renderCiWorkflow } from "../../scripts/generate-ci-workflow.ts";
@@ -20,6 +20,12 @@ import { childProcessTimeout } from "../helpers/child-process-timeout.ts";
* (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";
@@ -38,22 +44,48 @@ 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.
* 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"*) tar -cf - -T /dev/null ;;
*"-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
`;
@@ -84,6 +116,38 @@ function wrapperCheckout(root: string): string {
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));
@@ -227,27 +291,16 @@ describe("FE-GATE-013 in a merge job", { timeout: childProcessTimeout(GATE_STEP_
try {
const checkout = wrapperCheckout(root);
const calls = path.join(root, "docker-calls");
const result = spawnSync(CONTAINER_WRAPPER, ["corepack", "pnpm", "ci:gate", "--", GATE], {
const result = spawnSync(CONTAINER_WRAPPER, GATE_COMMAND, {
cwd: checkout,
encoding: "utf8",
env: {
...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: "",
CI: "true",
[PR_BASE_REF_VARIABLE]: "main",
},
env: wrapperEnvironment(root, calls, { CI: "true", [PR_BASE_REF_VARIABLE]: "main" }),
});
expect(result.status, result.stderr).toBe(0);
const gateCalls = readFileSync(calls, "utf8")
.split(`${CALL_END}\n`)
.map((call) => call.split("\n").filter((argument) => argument !== ""))
.filter((call) => call.join(" ").endsWith(`${STAND_IN_CONTAINER} corepack pnpm ci:gate -- ${GATE}`));
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"]);
@@ -262,3 +315,266 @@ describe("FE-GATE-013 in a merge job", { timeout: childProcessTimeout(GATE_STEP_
}
});
});
// 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 });
}
},
);
});