Files
clean-architecture-frontend…/scripts/run-in-system-container.sh
DongHyeonka b5f28e5236 fix(ci): 컨테이너 래퍼가 TERM·INT·HUP에도 artifacts를 되가져오고 컨테이너를 지운다
문제: 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)
2026-11-20 13:13:25 +09:00

188 lines
9.9 KiB
Bash
Executable File

#!/usr/bin/env bash
# Runs one command in a disposable systemd container, for a gate whose host requirements a CI job
# container or a developer shell does not meet (config/ci/gates.json `hostEnvironment: "system-container"`,
# FE-GATE-013's provider sandbox: bubblewrap, a systemd user manager, delegated cgroup v2).
#
# scripts/run-in-system-container.sh <command…> e.g. corepack pnpm ci:gate -- FE-GATE-013
#
# The container is privileged with its own cgroup namespace and boots systemd (config/ci/system-container.Dockerfile).
# 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; on TERM, INT or HUP, death by that
# signal (128 + its number to a shell).
set -euo pipefail
[ $# -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"
dockerfile=config/ci/system-container.Dockerfile
tag="fe-system-container:$(sha256sum "$dockerfile" | cut -c1-16)"
node_root=$(dirname "$(dirname "$(command -v node)")")
corepack_home=${COREPACK_HOME:-$HOME/.cache/node/corepack}
# The environment the gate reads (scripts/verify.sh ci_env, the workflow's global env).
pass_env=(CI VITE_BUILD_ID VITE_COMMIT_SHA RELEASE_ID CI_RUNNER_IMAGE SOURCE_DATE_EPOCH APP_PROFILE RELEASE_TARGET)
# A merge job's dependency cache (scripts/contracts/ci-gates.ts DEPENDENCY_CACHE): pnpm's store and metadata
# cache go in at the same paths, so the install in here reuses what the job's install fetched.
pnpm_dirs=()
for name in PNPM_CONFIG_STORE_DIR PNPM_CONFIG_CACHE_DIR; do
if [ -n "${!name:-}" ] && [ -d "${!name}" ]; then
pass_env+=("$name")
pnpm_dirs+=("${!name}")
fi
done
# 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"
fi
# systemd hands the cgroup controllers the provider scope needs (cpu, memory, pids) down from the container's
# root cgroup. A `docker exec` that arrives while systemd starts, before it has enabled controllers there,
# joins that root cgroup, and while any process sits in it the kernel refuses to enable controllers on it
# (cgroup v2: a cgroup that hands controllers to children holds no processes). systemd then delegates
# nothing, every later exec joins the root cgroup too, and each provider scope lacks memory.max, so the
# provider cgroup gate exits 125 (1 run in 4 on desktop, 2026-11-14). So the container's first process
# moves every process out of the root cgroup and enables its controllers before it execs systemd, as
# moby's hack/dind does. From then on an exec cannot join the root cgroup and lands in PID 1's.
boot='cg=/sys/fs/cgroup
controllers=$(cat $cg/cgroup.controllers 2> /dev/null) || controllers=
if [ -n "$controllers" ]; then
mkdir -p $cg/init.scope
enable=$(printf "+%s " $controllers)
tries=0
until { xargs -rn1 < $cg/cgroup.procs > $cg/init.scope/cgroup.procs; echo "$enable" > $cg/cgroup.subtree_control; } 2> /dev/null; do
tries=$((tries + 1))
[ $tries -lt 50 ] || { echo "system-container: cannot enable the root cgroup controllers" >&2; break; }
sleep 0.1
done
fi
exec /sbin/init'
# `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"
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.
state=""
for _ in $(seq 1 120); do
state=$($docker exec "$cid" systemctl is-system-running --wait 2>/dev/null || :)
case "$state" in running | degraded) break ;; esac
sleep 0.5
done
case "$state" in running | degraded) ;; *) fail "systemd did not start (state: ${state:-none})" ;; esac
$docker exec "$cid" sh -c 'for i in $(seq 1 120); do [ -S /run/user/0/bus ] && exit 0; sleep 0.5; done; exit 1' \
|| fail "the root user manager did not start"
# The working tree as it is (node_modules included) and its history. A linked worktree's .git is a file
# naming a directory outside the tree, so the history goes in as a bundle of HEAD instead.
tar -C "$root" --exclude=./.git --exclude=./.tmp -cf - . | $docker exec -i "$cid" sh -c 'mkdir -p /work && tar -C /work --no-same-owner -xf -' \
|| fail "copying the working tree failed"
if [ -d .git ]; then
tar -C "$root" -cf - .git | $docker exec -i "$cid" tar -C /work --no-same-owner -xf - || fail "copying .git failed"
else
bundle=$(mktemp)
git bundle create -q "$bundle" HEAD
$docker exec -i "$cid" sh -c 'cat > /tmp/head.bundle' < "$bundle"
rm -f "$bundle"
$docker exec -w /work "$cid" sh -c 'git init -q . && git fetch -q /tmp/head.bundle HEAD && git update-ref HEAD FETCH_HEAD && git reset -q' \
|| fail "restoring the git history failed"
fi
tar -C "$node_root" -cf - . | $docker exec -i "$cid" sh -c 'mkdir -p /opt/node && tar -C /opt/node --no-same-owner -xf -' \
|| fail "copying node failed"
for dir in "${pnpm_dirs[@]}"; do
tar -C "$dir" -cf - . | $docker exec -i "$cid" sh -c "mkdir -p '$dir' && tar -C '$dir' --no-same-owner -xf -" \
|| fail "copying $dir failed"
done
if [ -d "$corepack_home" ]; then
tar -C "$corepack_home" -cf - . | $docker exec -i "$cid" sh -c 'mkdir -p /opt/corepack && tar -C /opt/corepack --no-same-owner -xf -' \
|| fail "copying the corepack cache failed"
fi
exec_env=(-e PATH=/opt/node/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
-e COREPACK_HOME=/opt/corepack -e HOME=/root
-e XDG_RUNTIME_DIR=/run/user/0 -e DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/0/bus)
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" "$@" &
wait $! || rc=$?
# The gate's log and evidence come back even when it failed.
copying=1
copy_back
exit "$rc"