Merge pull request #2305 from kirigayakazima/fix/linux-boot-inner-configure-safety

linux-boot: harden boot-inner.sh and configure-worktree.sh
This commit is contained in:
MoonEyes
2026-11-28 20:41:23 +01:00
committed by GitHub
3 changed files with 397 additions and 23 deletions

View File

@ -1,44 +1,125 @@
#!/bin/bash
# Runs inside the leonida-boot-* unit (see run-boot.sh). Waits for memory, takes the locks, samples resources, boots.
set -u
WORK=/opt/leonida/work/$BOOT_AGENT; N=$BOOT_N; LOG=$WORK/boot-$N.log; RES=$WORK/boot-$N.resources.tsv
die() {
echo "ERROR: $*" >&2
exit 2
}
OUT=${LEONIDA_BOOT_ROOT:-${LEONIDA_OUT:-/opt/leonida}}
BOOT_AGENT=${BOOT_AGENT:-}
BOOT_N=${BOOT_N:-}
BOOT_SECS=${BOOT_SECS:-}
GTA6RT=${GTA6RT:-}
BOOT_SH=${BOOT_SH:-$OUT/boot.sh}
NVIDIA_SMI=${NVIDIA_SMI:-nvidia-smi}
PROC_MEMINFO=${LEONIDA_MEMINFO_PATH:-/proc/meminfo}
CGROUP_SELF=${LEONIDA_SELF_CGROUP_PATH:-/proc/self/cgroup}
CGROUP_ROOT=${LEONIDA_CGROUP_ROOT:-/sys/fs/cgroup}
WAIT_SLEEP=${LEONIDA_WAIT_SLEEP_SECS:-15}
SAMPLE_SLEEP=${LEONIDA_SAMPLE_SLEEP_SECS:-2}
WAIT_ITERS=${LEONIDA_WAIT_ITERS:-40}
[ -n "$BOOT_AGENT" ] || die "BOOT_AGENT must be set"
[ -n "$BOOT_N" ] || die "BOOT_N must be set"
[ -n "$BOOT_SECS" ] || die "BOOT_SECS must be set"
[ -n "$GTA6RT" ] || die "GTA6RT must be set"
case "$BOOT_AGENT" in
.|..|*/*|*\\*|*..*) die "BOOT_AGENT must be a single path segment: $BOOT_AGENT" ;;
esac
case "$BOOT_N" in
.|..|*/*|*\\*|*..*) die "BOOT_N must be a single path segment: $BOOT_N" ;;
esac
[[ "$BOOT_SECS" =~ ^[0-9]+$ ]] || die "BOOT_SECS must be a non-negative integer: $BOOT_SECS"
[[ "$WAIT_ITERS" =~ ^[0-9]+$ ]] || die "WAIT_ITERS must be a non-negative integer: $WAIT_ITERS"
NEED=${LEONIDA_BOOT_MIN_FREE_MB:-6500}
[[ "$NEED" =~ ^[0-9]+$ ]] || die "LEONIDA_BOOT_MIN_FREE_MB must be a non-negative integer: $NEED"
WORK=${LEONIDA_BOOT_WORK:-$OUT/work/$BOOT_AGENT}; N=$BOOT_N; LOG=$WORK/boot-$N.log; RES=$WORK/boot-$N.resources.tsv
META=$WORK/boot-$N.meta
mkdir -p "$OUT" "$WORK" || die "cannot create work directory: $WORK"
: > "$LOG"
echo "start_epoch=$(date +%s)" > "$META"
echo "unit=leonida-boot-$BOOT_AGENT-$N gta6rt=$GTA6RT secs=$BOOT_SECS" >> "$META"
env | grep -E '^(LEONIDA_|WINEDEBUG=)' | sort >> "$META"
env | grep -E '^(LEONIDA_|WINEDEBUG=)' | sort >> "$META" || true
mem_free_mb() { # RAM available plus a third of free zram swap (zram pages cost RAM, roughly 3:1)
awk '/^MemAvailable:/{a=$2} /^SwapFree:/{s=$2} END{printf "%d", (a + s/3)/1024}' /proc/meminfo
[ -r "$PROC_MEMINFO" ] || { echo 0; return; }
awk 'BEGIN{a=0; s=0} /^MemAvailable:/{a=$2} /^SwapFree:/{s=$2} END{printf "%d", (a + s/3)/1024}' "$PROC_MEMINFO"
}
swap_pct() {
[ -r "$PROC_MEMINFO" ] || { echo 0; return; }
awk 'BEGIN{t=0; f=0} /^SwapTotal:/{t=$2} /^SwapFree:/{f=$2} END{pct=(t>0 ? (t-f)*100/t : 0); printf "%d", pct}' "$PROC_MEMINFO"
}
read_uint() {
local v=""
if [ -r "$1" ]; then
v=$(cat "$1" 2>/dev/null || true)
v=${v//$'\r'/}
fi
[[ "$v" =~ ^[0-9]+$ ]] || v=0
printf '%s' "$v"
}
NEED=${LEONIDA_BOOT_MIN_FREE_MB:-6500}
swap_pct() { awk '/^SwapTotal:/{t=$2} /^SwapFree:/{f=$2} END{printf "%d", t ? (t-f)*100/t : 0}' /proc/meminfo; }
exec 8>/opt/leonida/.gpu.lock; flock 8 # one boot at a time
SAMPLER=""
cleanup() {
if [ -n "${SAMPLER:-}" ]; then
kill "$SAMPLER" 2>/dev/null || true
wait "$SAMPLER" 2>/dev/null || true
SAMPLER=""
fi
}
trap cleanup EXIT INT TERM
exec 8>"$OUT/.gpu.lock"
if command -v flock >/dev/null 2>&1; then flock 8; fi # one boot at a time
echo "[run-boot] $(date +%T) got the GPU lock" >> "$LOG"
for i in $(seq 1 40); do # up to 10 min for memory headroom
for ((i = 1; i <= WAIT_ITERS; i++)); do # up to 10 min for memory headroom
f=$(mem_free_mb); sp=$(swap_pct); [ "$f" -ge "$NEED" ] && [ "$sp" -lt 70 ] && break
echo "[run-boot] $(date +%T) waiting for memory: ${f} MB free (need ${NEED}), swap ${sp}% (need < 70%)" >> "$LOG"; sleep 15
echo "[run-boot] $(date +%T) waiting for memory: ${f} MB free (need ${NEED}), swap ${sp}% (need < 70%)" >> "$LOG"; sleep "$WAIT_SLEEP"
done
echo "[run-boot] $(date +%T) memory before boot: $(mem_free_mb) MB free, swap $(swap_pct)%" >> "$LOG"
exec 9>/opt/leonida/.build.lock; flock 9 # no compiles while the game runs
exec 9>"$OUT/.build.lock"
if command -v flock >/dev/null 2>&1; then flock 9; fi # no compiles while the game runs
echo "[run-boot] $(date +%T) got the build lock; booting" >> "$LOG"
echo "boot_epoch=$(date +%s)" >> "$META"
CG=/sys/fs/cgroup$(cut -d: -f3 /proc/self/cgroup)
( printf 'time\tmem_avail_mb\tswap_used_mb\tunit_mem_mb\tunit_swap_mb\tgpu_mem_mb\tgpu_util\n'
cg_rel=""
if [ -r "$CGROUP_SELF" ]; then
cg_rel=$(awk -F: '$1=="0"{print $3; exit}' "$CGROUP_SELF" 2>/dev/null || true)
[ -n "$cg_rel" ] || cg_rel=$(awk -F: 'NF>=3{p=$3} END{print p}' "$CGROUP_SELF" 2>/dev/null || true)
cg_rel=${cg_rel//$'\r'/}
fi
CG=$CGROUP_ROOT$cg_rel
( trap 'kill "${sleep_pid:-}" 2>/dev/null || true; exit 0' TERM INT
sleep_pid=""
printf 'time\tmem_avail_mb\tswap_used_mb\tunit_mem_mb\tunit_swap_mb\tgpu_mem_mb\tgpu_util\n'
while :; do
read -r ma su < <(awk '/^MemAvailable:/{a=$2} /^SwapTotal:/{t=$2} /^SwapFree:/{f=$2} END{print int(a/1024), int((t-f)/1024)}' /proc/meminfo)
um=$(( $(cat "$CG/memory.current" 2>/dev/null || echo 0) / 1048576 )); us=$(( $(cat "$CG/memory.swap.current" 2>/dev/null || echo 0) / 1048576 ))
g=$(nvidia-smi --query-gpu=memory.used,utilization.gpu --format=csv,noheader,nounits 2>/dev/null | tr -d ' ' | tr ',' '\t')
ma=0; su=0
if [ -r "$PROC_MEMINFO" ]; then
read -r ma su < <(awk 'BEGIN{a=0; t=0; f=0} /^MemAvailable:/{a=$2} /^SwapTotal:/{t=$2} /^SwapFree:/{f=$2} END{u=(t>f ? t-f : 0); print int(a/1024), int(u/1024)}' "$PROC_MEMINFO")
fi
um=$(( $(read_uint "$CG/memory.current") / 1048576 ))
us=$(( $(read_uint "$CG/memory.swap.current") / 1048576 ))
g=$("$NVIDIA_SMI" --query-gpu=memory.used,utilization.gpu --format=csv,noheader,nounits 2>/dev/null | head -n 1 | tr -d ' \r' | tr ',' '\t')
printf '%s\t%s\t%s\t%s\t%s\t%s\n' "$(date +%T)" "$ma" "$su" "$um" "$us" "${g:-? ?}"
sleep 2
sleep "$SAMPLE_SLEEP" &
sleep_pid=$!
wait "$sleep_pid" 2>/dev/null || break
sleep_pid=""
done ) > "$RES" 2>/dev/null &
SAMPLER=$!
/opt/leonida/boot.sh run "$BOOT_SECS" >> "$LOG" 2>&1
rc=$?
kill $SAMPLER 2>/dev/null
if [ -f "$BOOT_SH" ]; then
"$BOOT_SH" run "$BOOT_SECS" >> "$LOG" 2>&1
rc=$?
else
echo "[run-boot] missing boot script: $BOOT_SH" >> "$LOG"
rc=127
fi
cleanup
echo "[run-boot] $(date +%T) boot.sh exit $rc" >> "$LOG"
# boot.sh stops the title with timeout(1) at the time limit: 124 means it ran the whole time, which is success here.
[ "$rc" = 124 ] && { echo "[run-boot] time limit reached" >> "$LOG"; rc=0; }

View File

@ -2,8 +2,49 @@
# usage: configure-worktree.sh <worktree>
# Configures a Windows build of the runtime on Linux with clang-cl and an xwin SDK (XWIN_DIR, default
# ~/.local/share/xwin-sdk). SDL3_SRC=<an SDL3 source tree> makes the configure work offline.
set -eu; W=$(realpath "$1")
cmake -S "$W/runtime" -B "$W/runtime/build/boot" -G Ninja -DCMAKE_BUILD_TYPE=Release \
-DCMAKE_TOOLCHAIN_FILE="$W/runtime/cmake/clang-cl-xwin.cmake" -DXWIN_DIR="${XWIN_DIR:-$HOME/.local/share/xwin-sdk}" \
-DLEONIDA_BUILD_WINDOWS_RUNTIME=ON -DLEONIDA_SDL3=ON \
${SDL3_SRC:+-DFETCHCONTENT_SOURCE_DIR_SDL3="$SDL3_SRC"}
set -eu
usage() {
echo "usage: configure-worktree.sh <worktree>"
}
die() {
echo "ERROR: $*" >&2
exit 2
}
if [ "$#" -ge 1 ] && { [ "$1" = "-h" ] || [ "$1" = "--help" ]; }; then
usage
exit 0
fi
[ "$#" -eq 1 ] || { usage >&2; exit 2; }
[ -n "$1" ] || die "worktree path must not be empty"
[ -d "$1" ] || die "worktree directory does not exist: $1"
W=$(realpath "$1")
[ -f "$W/runtime/CMakeLists.txt" ] || die "not a runtime worktree (missing runtime/CMakeLists.txt): $W"
[ -f "$W/runtime/cmake/clang-cl-xwin.cmake" ] || die "missing toolchain file: $W/runtime/cmake/clang-cl-xwin.cmake"
CMAKE=${CMAKE:-cmake}
command -v "$CMAKE" >/dev/null 2>&1 || die "cmake executable not found: $CMAKE"
if [ -n "${SDL3_SRC:-}" ] && [ ! -d "$SDL3_SRC" ]; then
die "SDL3_SRC directory does not exist: $SDL3_SRC"
fi
cmake_args=(
-S "$W/runtime"
-B "$W/runtime/build/boot"
-G Ninja
-DCMAKE_BUILD_TYPE=Release
-DCMAKE_TOOLCHAIN_FILE="$W/runtime/cmake/clang-cl-xwin.cmake"
-DXWIN_DIR="${XWIN_DIR:-$HOME/.local/share/xwin-sdk}"
-DLEONIDA_BUILD_WINDOWS_RUNTIME=ON
-DLEONIDA_SDL3=ON
)
if [ -n "${SDL3_SRC:-}" ]; then
cmake_args+=(-DFETCHCONTENT_SOURCE_DIR_SDL3="$SDL3_SRC")
fi
"$CMAKE" "${cmake_args[@]}"

View File

@ -0,0 +1,252 @@
"""Unit tests for scripts/linux-boot/boot-inner.sh and configure-worktree.sh.
python -I tests/test_linux_boot_inner_and_configure.py
"""
from __future__ import annotations
import os
import shutil
import subprocess
import tempfile
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
BOOT_INNER = ROOT / "scripts" / "linux-boot" / "boot-inner.sh"
CONFIG_WT = ROOT / "scripts" / "linux-boot" / "configure-worktree.sh"
def _find_bash() -> str | None:
if os.name == "nt":
for root in (
os.environ.get("ProgramFiles", r"C:\Program Files"),
os.environ.get("ProgramFiles(x86)", r"C:\Program Files (x86)"),
):
if not root:
continue
for rel in (r"Git\bin\bash.exe", r"Git\usr\bin\bash.exe"):
cand = Path(root) / rel
if cand.is_file():
return str(cand)
return None
return shutil.which("bash")
def _to_bash_path(path: Path) -> str:
s = str(path.resolve())
if os.name == "nt" and len(s) >= 2 and s[1] == ":":
return "/" + s[0].lower() + s[2:].replace("\\", "/")
return s.replace("\\", "/")
def _write_lf(path: Path, text: str, executable: bool = False) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(text.encode("utf-8"))
if executable:
path.chmod(0o755)
class LinuxBootInnerAndConfigureTests(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
cls.bash = _find_bash()
def _require_bash(self) -> str:
if not self.bash:
self.skipTest("bash not available on host")
return self.bash
def _run_bash(
self,
script: Path,
args: list[str] | None = None,
extra_env: dict[str, str] | None = None,
strip_vars: tuple[str, ...] = (),
) -> subprocess.CompletedProcess[str]:
bash = self._require_bash()
env = os.environ.copy()
for key in strip_vars:
for existing in [k for k in env if k.upper() == key.upper()]:
env.pop(existing, None)
if extra_env:
env.update(extra_env)
return subprocess.run(
[bash, _to_bash_path(script), *(args or [])],
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
env=env,
timeout=30,
)
def test_lf_line_endings_and_bash_syntax(self) -> None:
for script in (BOOT_INNER, CONFIG_WT):
with self.subTest(script=script.name):
self.assertNotIn(b"\r\n", script.read_bytes())
bash = self._require_bash()
res = subprocess.run(
[bash, "-n", _to_bash_path(script)],
capture_output=True,
text=True,
encoding="utf-8",
timeout=15,
)
self.assertEqual(res.returncode, 0, res.stderr)
def test_boot_inner_rejects_missing_or_invalid_env_vars_before_writing(self) -> None:
with tempfile.TemporaryDirectory() as td:
root = Path(td)
out_dir = root / "opt"
base = {
"LEONIDA_BOOT_ROOT": _to_bash_path(out_dir),
"BOOT_AGENT": "agentA",
"BOOT_N": "1",
"BOOT_SECS": "5",
"GTA6RT": "/fake/gta6rt.exe",
}
for missing in ("BOOT_AGENT", "BOOT_N", "BOOT_SECS", "GTA6RT"):
with self.subTest(missing=missing):
env = dict(base)
env.pop(missing)
res = self._run_bash(
BOOT_INNER,
extra_env=env,
strip_vars=("BOOT_AGENT", "BOOT_N", "BOOT_SECS", "GTA6RT"),
)
self.assertEqual(res.returncode, 2, res.stderr)
self.assertIn("ERROR:", res.stderr)
for bad_key, bad_val in (("BOOT_AGENT", "../escape"), ("BOOT_SECS", "notanint")):
with self.subTest(bad_key=bad_key, bad_val=bad_val):
env = dict(base)
env[bad_key] = bad_val
res = self._run_bash(BOOT_INNER, extra_env=env)
self.assertEqual(res.returncode, 2, res.stderr)
self.assertFalse((out_dir / "work" / "agentA" / "boot-1.meta").exists())
def test_boot_inner_handles_cgroup_max_and_timeout_exit_124(self) -> None:
with tempfile.TemporaryDirectory() as td:
root = Path(td)
out_dir = root / "opt"
meminfo = root / "proc" / "meminfo"
self_cgroup = root / "proc" / "self_cgroup"
cg_dir = root / "sys_cgroup" / "user.slice" / "unit.scope"
cg_dir.mkdir(parents=True)
_write_lf(meminfo, "MemAvailable: 16777216 kB\nSwapTotal: 4194304 kB\nSwapFree: 4194304 kB\n")
_write_lf(self_cgroup, "12:freezer:/\n0::/user.slice/unit.scope\n")
_write_lf(cg_dir / "memory.current", "2097152\n")
_write_lf(cg_dir / "memory.swap.current", "max\n")
nvidia_smi = root / "bin" / "nvidia-smi"
_write_lf(nvidia_smi, "#!/bin/bash\nprintf '128, 35\\n'\n", executable=True)
res_file = out_dir / "work" / "agentA" / "boot-1.resources.tsv"
boot_sh = out_dir / "boot.sh"
_write_lf(
boot_sh,
"#!/bin/bash\n"
"i=0\n"
"while [ \"$i\" -lt 100 ]; do\n"
" if [ -f \"$TEST_RES\" ] && [ \"$(wc -l < \"$TEST_RES\")\" -ge 2 ]; then break; fi\n"
" i=$((i + 1))\n"
" sleep 0.05\n"
"done\n"
"echo 'stub boot invoked'\n"
"exit \"${STUB_BOOT_EXIT:-124}\"\n",
executable=True,
)
env = {
"LEONIDA_BOOT_ROOT": _to_bash_path(out_dir),
"LEONIDA_MEMINFO_PATH": _to_bash_path(meminfo),
"LEONIDA_SELF_CGROUP_PATH": _to_bash_path(self_cgroup),
"LEONIDA_CGROUP_ROOT": _to_bash_path(root / "sys_cgroup"),
"NVIDIA_SMI": _to_bash_path(nvidia_smi),
"BOOT_SH": _to_bash_path(boot_sh),
"LEONIDA_WAIT_SLEEP_SECS": "0",
"LEONIDA_SAMPLE_SLEEP_SECS": "1",
"LEONIDA_WAIT_ITERS": "1",
"BOOT_AGENT": "agentA",
"BOOT_N": "1",
"BOOT_SECS": "3",
"GTA6RT": "/fake/gta6rt.exe",
"TEST_RES": _to_bash_path(res_file),
"STUB_BOOT_EXIT": "124",
}
res = self._run_bash(BOOT_INNER, extra_env=env)
self.assertEqual(res.returncode, 0, res.stderr)
meta = (out_dir / "work" / "agentA" / "boot-1.meta").read_text(encoding="utf-8")
self.assertIn("unit=leonida-boot-agentA-1", meta)
self.assertIn("boot_epoch=", meta)
log = (out_dir / "work" / "agentA" / "boot-1.log").read_text(encoding="utf-8")
self.assertIn("stub boot invoked", log)
self.assertIn("time limit reached", log)
tsv_lines = res_file.read_text(encoding="utf-8").splitlines()
self.assertGreaterEqual(len(tsv_lines), 2)
self.assertTrue(tsv_lines[1].endswith("\t2\t0\t128\t35"), tsv_lines)
env["BOOT_N"] = "2"
env["TEST_RES"] = _to_bash_path(out_dir / "work" / "agentA" / "boot-2.resources.tsv")
env["STUB_BOOT_EXIT"] = "9"
res_fail = self._run_bash(BOOT_INNER, extra_env=env)
self.assertEqual(res_fail.returncode, 9, res_fail.stderr)
def test_configure_worktree_help_validation_and_spaced_paths(self) -> None:
help_res = self._run_bash(CONFIG_WT, ["--help"])
self.assertEqual(help_res.returncode, 0, help_res.stderr)
self.assertIn("usage: configure-worktree.sh", help_res.stdout)
with tempfile.TemporaryDirectory() as td:
root = Path(td)
cmake_log = root / "cmake.args"
fake_cmake = root / "fake-cmake"
_write_lf(
fake_cmake,
"#!/bin/bash\n"
": > \"$CMAKE_ARGS_OUT\"\n"
"for arg in \"$@\"; do printf '%s\\n' \"$arg\" >> \"$CMAKE_ARGS_OUT\"; done\n",
executable=True,
)
no_wt = root / "empty dir"
no_wt.mkdir()
for args in ([], [""], [str(root / "missing")], [_to_bash_path(no_wt)]):
with self.subTest(args=args):
bad = self._run_bash(
CONFIG_WT,
args=args,
extra_env={"CMAKE": _to_bash_path(fake_cmake), "CMAKE_ARGS_OUT": _to_bash_path(cmake_log)},
)
self.assertEqual(bad.returncode, 2, bad.stderr)
self.assertFalse(cmake_log.exists())
wt = root / "my worktree"
(wt / "runtime" / "cmake").mkdir(parents=True)
_write_lf(wt / "runtime" / "CMakeLists.txt", "# dummy\n")
_write_lf(wt / "runtime" / "cmake" / "clang-cl-xwin.cmake", "# dummy\n")
sdl3 = root / "sdl3 source"
sdl3.mkdir()
ok = self._run_bash(
CONFIG_WT,
args=[_to_bash_path(wt)],
extra_env={
"CMAKE": _to_bash_path(fake_cmake),
"CMAKE_ARGS_OUT": _to_bash_path(cmake_log),
"SDL3_SRC": _to_bash_path(sdl3),
"XWIN_DIR": "/opt/xwin",
},
)
self.assertEqual(ok.returncode, 0, ok.stderr)
recorded = cmake_log.read_text(encoding="utf-8").splitlines()
wt_bash = _to_bash_path(wt)
sdl_bash = _to_bash_path(sdl3)
self.assertIn(f"{wt_bash}/runtime", recorded)
self.assertIn(f"{wt_bash}/runtime/build/boot", recorded)
self.assertIn(f"-DCMAKE_TOOLCHAIN_FILE={wt_bash}/runtime/cmake/clang-cl-xwin.cmake", recorded)
self.assertIn(f"-DFETCHCONTENT_SOURCE_DIR_SDL3={sdl_bash}", recorded)
if __name__ == "__main__":
unittest.main()