Files
clean-architecture-frontend…/scripts/run-in-system-container.sh
T
DongHyeonka 13b40934d5 fix(ci): 시스템 컨테이너가 systemd 전에 root cgroup 제어기를 켠다
문제: run-in-system-container.sh는 `docker run -d` 직후 docker exec로
systemd 부팅을 기다린다. systemd는 시작할 때 root cgroup의 프로세스를
init.scope로 옮긴 뒤 root에 제어기를 켜는데, 그 사이에 닿은 exec는 root
cgroup에 들어간다. cgroup v2는 프로세스가 있는 cgroup에 자식용 제어기를
켜지 못하게 하므로 systemd는 cpu·memory·pids를 user manager까지 넘기지
못하고, 그 뒤 exec도 계속 root cgroup에 들어가 회차 내내 그대로다. 그
컨테이너의 provider scope에는 memory.max가 없어 cgroup 강제 게이트가
모든 provider를 exit 125로 멈춘다(ci-artifact-contract 671줄부터 18개,
desktop 4회 중 1회).

고른 방법: 컨테이너의 첫 프로세스가 root cgroup의 프로세스를 전부
init.scope로 옮기고 root에 쓸 수 있는 제어기를 켠 뒤 /sbin/init를
exec한다. moby의 hack/dind가 같은 방법을 쓴다. 그 뒤로 exec는 root
cgroup에 들어갈 수 없고 PID 1의 cgroup(init.scope)에 들어간다. 옮기는
사이에 들어온 프로세스 때문에 쓰기가 실패하면 0.1초 간격으로 50번까지
다시 한다. 끝내 못 켜면 그 사실을 컨테이너 로그에 쓰고, 래퍼가 어떤 끝에서든
컨테이너를 지우기 전에 그 줄을 stderr로 옮긴다. 빠진 제어기는 test:system 사전 점검이 이름으로 댄다.
버린 대안: 첫 exec 전에 정한 시간 기다리기는 시간 가정이고 창을 줄일
뿐이다. is-system-running을 --wait 없이 짧게 묻기도 짧은 exec가 그
순간에 걸리면 같다. Dockerfile CMD에 넣기는 동작이 같지만 이미지를 다시
만들어야 하고, 경합을 만드는 쪽은 exec를 부르는 이 스크립트다.

위험·한계: privileged·cgroupns=private·cgroup v2를 가정한다(전과 같은
가정). cgroup v2가 아니면 옮기기를 건너뛰고 전처럼 부팅한다. 쓸 수 있는
제어기를 모두 켜고, systemd가 쓰지 않는 것(cpuset, io)은 systemd가 끈다.
root에 들어갈 수 없을 때 runc가 exec를 PID 1의 cgroup에 넣는 동작에
기댄다. desktop runc 1.3.6에서 봤고, runner에서도 통과한 run은 같은
상태에서 exec가 됐다. CPU를 소모하는 부하 아래 반복은 하지 않았다
(runner가 같은 desktop에서 돈다). 고침이 시간 창이 아니라 순서를
보장해 부하와 상관없다.

검증: desktop에서 컨테이너를 띄우자마자 docker exec 15개를 세우는
탐침이 옛 부팅으로 6/6 root 제어기 없음·scope memory.max 없음(RED),
새 부팅으로 6/6 root에 cpu memory pids 포함·exec가 init.scope·
memory.max=1073741824(GREEN). 고친 부팅으로 ci-artifact-contract 파일
전체를 새 컨테이너마다 16회 돌려 16/16 통과(exit=125 0회), 회차마다
root subtree_control에 cpu memory pids가 있고 exec는 init.scope였다.
2026-11-14 06:04:30 +09:00

125 lines
6.8 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.
# 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.
set -euo pipefail
[ $# -gt 0 ] || { sed -n '2,13p' "$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
say() { echo "system-container: $*" >&2; }
fail() { say "$*"; exit 3; }
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'
cid=$($docker run -d --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
# 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
rc=0
$docker exec -w /work "${exec_env[@]}" "$cid" "$@" || 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"
exit "$rc"