Files
clean-architecture-frontend…/scripts/run-in-system-container.sh
T
DongHyeonka 7ed0af3d29 ci(gates): merge job 셋이 의존성 캐시에서 설치를 시작하고 main만 저장한다
문제: merge job 셋은 runner의 새 컨테이너에서 매번 Node(GitHub
다운로드), corepack의 pnpm, 패키지 404개를 내려받고, pnpm 11은 lockfile
542개 항목의 공급망 정책을 레지스트리에 물어 검증한다. run 169에서 job마다
setup-node 11~18초, 설치 12~29초였고 설치 시간의 대부분은 정책 검증의
메타데이터 요청이었다(10.1~27.9초). FE-GATE-013의 시스템 컨테이너는 같은
설치를 한 번 더 한다. merge 25분 목표에 0.8분 모자랐다.

고친 것(권하는 안으로 정함 2026-11-13, 총괄):
- job 단계 `dependency-cache`를 더한다. setup-node 앞에서 Node toolcache와
  `/tmp/fe-dependency-cache`(corepack, pnpm store, pnpm 메타데이터 캐시)를
  `.nvmrc`·`pnpm-lock.yaml` 해시 키로 복원한다. main run은 actions/cache로
  복원·저장하고, 그 밖의 ref는 actions/cache/restore로 복원만 한다. pin은
  짝 백엔드의 JDK·Gradle·Trivy 캐시와 같다(v4.3.0).
- 생성기가 그 job에 `COREPACK_HOME`·`PNPM_CONFIG_STORE_DIR`·
  `PNPM_CONFIG_CACHE_DIR`를 주어 job의 모든 pnpm 호출이 같은 곳을 본다.
  frozen install 단계는 그대로이고 캐시와 관계없이 돈다.
- PR run은 main이 저장한 항목을 같은 키로 읽기만 한다. 저장할 수 있는
  actions/cache 단계는 `refs/heads/main` 조건 아래에만 있고, 그 밖의 ref가
  타는 actions/cache/restore에는 저장하는 post 단계가 없다(시험으로 고정).
- 계약: merge job 셋만 이 단계를 가진다(release·promotion·provider·main
  job은 거절, 단계 순서 고정에 반영). 그 env를 job이 따로 묶으면 거절한다.
  키 입력은 `config/repository-layout.json`의 새 집합
  `dependency-cache-key`(`.nvmrc`, `pnpm-lock.yaml`)에서 고른다.
- `scripts/run-in-system-container.sh`가 그 env가 있으면 store와 메타데이터
  캐시를 같은 경로로 컨테이너에 넘긴다. 없으면(desktop) 지금과 같다.
- 결정 색인, ci-quality-gates.md, O1 출처 문구를 총괄이 정한 말로 맞춘다.

버린 대안:
- CI 이미지에 의존성 굽기: 레지스트리 쓰기 토큰이 든다.
- 브랜치 run도 저장하기: 캐시 항목은 다음 run이 믿는 입력이다. pnpm은
  같은 lockfile의 공급망 검증 기록이 캐시에 있으면 다시 검증하지 않으므로,
  브랜치가 쓴 항목이 main의 검증을 건너뛰게 할 수 있다.
- `cache-hit`일 때 설치를 건너뛰기: 결과가 캐시 상태에 달린다.
- apt 글꼴 캐시: 캐시가 없을 때 새 패키지 버전이 깔려 시각 결과가 달라질
  수 있다.

위험·한계:
- PR run은 main이 같은 키(또는 restore-keys로 앞 항목)를 저장한 뒤에야
  hit한다. 이 PR 자신의 run은 비어서 시작한다.
- runner 캐시 저장소(5GB)는 짝 백엔드와 같이 쓴다. 항목 하나는 Node·store·
  메타데이터로 압축 전 약 0.7GB다. lockfile이 바뀔 때마다 새 항목이 생긴다.
- Node toolcache 경로(`/opt/hostedtoolcache`)가 job 이미지와 다르면 그
  부분만 효과가 없고 setup-node가 내려받는다.

검증(desktop):
- 설치 실험(같은 lockfile, 새 폴더): 빈 캐시 13.9·17.2초, 캐시 있음 1.6초,
  store 파일 40개·메타데이터 40개를 망가뜨린 캐시 3.6초(27개만 다시 받음).
  다섯 번 모두 node_modules 트리 해시가 같다. pnpm 11은 대문자
  `PNPM_CONFIG_STORE_DIR`·`PNPM_CONFIG_CACHE_DIR`를 읽는다.
- FE-GATE-013 흐름을 캐시 env로 재현: 빈 캐시 설치 13.7초, 캐시 설치
  2.6초, 시스템 컨테이너 안 설치 1.5초(`Recreating node_modules` 없음, 지금은
  31.3초). 그 실행의 FE-GATE-013은 provider 묶음 시험 하나가 손 timeout
  30초에 걸려 실패했다(캐시와 무관, PR #39가 고치는 문제).
- RED: 계약·생성기를 둔 채 gates.json에서 캐시 단계를 빼면 새 시험 6개
  실패. 키 입력을 코드에 직접 적은 첫 판은 repository-layout R2 시험이
  잡았다. GREEN: repository-layout·ci-workflow-generation 456개 통과,
  check:ci·check:types·eslint rc=0, verify:documentation rc=0, 노트북
  `scripts/verify.sh docs` OK.
2026-11-13 08:26:13 +09:00

102 lines
5.4 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
cid=$($docker run -d --privileged --cgroupns=private --tmpfs /run --tmpfs /run/lock "$tag") \
|| fail "container did not start"
cleanup() {
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"