From f2bdcc001c89e09d783682fe545b46522182bebd Mon Sep 17 00:00:00 2001 From: jcook3701 Date: Wed, 2 Dec 2026 02:26:55 -0800 Subject: [PATCH] fix: reclaim idle container toolchain networks --- .github/workflows/container-toolchain.yml | 4 ++ changelogs/CHANGELOG.md | 1 + changelogs/releases/v0.1.0.md | 1 + docs/container-toolchain.md | 8 ++- scripts/toolchain.sh | 31 ++++++++- tests/test_container_toolchain.py | 81 +++++++++++++++++++++++ 6 files changed, 123 insertions(+), 3 deletions(-) diff --git a/.github/workflows/container-toolchain.yml b/.github/workflows/container-toolchain.yml index 296a056..f976b73 100644 --- a/.github/workflows/container-toolchain.yml +++ b/.github/workflows/container-toolchain.yml @@ -72,3 +72,7 @@ jobs: exit 1 fi test -z "$(find . -uid 0 -print -quit)" + project="cc-toolchain-$(printf '%s' "$(pwd -P)" | sha256sum | cut -c1-12)" + test -z "$(docker network ls --filter "name=^${project}_default$" --format '{{.Name}}')" + scripts/toolchain.sh run true + test -z "$(docker network ls --filter "name=^${project}_default$" --format '{{.Name}}')" diff --git a/changelogs/CHANGELOG.md b/changelogs/CHANGELOG.md index 37e180f..4060d33 100644 --- a/changelogs/CHANGELOG.md +++ b/changelogs/CHANGELOG.md @@ -12,6 +12,7 @@ - Import shared spelling dictionary - Add containerized documentation preview - Generate reviewed Python release preparation +- Add container development toolchain (#33) ### 🐛 Fixed diff --git a/changelogs/releases/v0.1.0.md b/changelogs/releases/v0.1.0.md index a1e7098..cce005e 100644 --- a/changelogs/releases/v0.1.0.md +++ b/changelogs/releases/v0.1.0.md @@ -12,6 +12,7 @@ - Import shared spelling dictionary - Add containerized documentation preview - Generate reviewed Python release preparation +- Add container development toolchain (#33) ### 🐛 Fixed diff --git a/docs/container-toolchain.md b/docs/container-toolchain.md index f8d6553..8a31a59 100644 --- a/docs/container-toolchain.md +++ b/docs/container-toolchain.md @@ -1,7 +1,7 @@ # Container development toolchain The root Compose service is separate from the Jekyll website preview. -Use Docker Engine, Docker Compose v2, Git and Make on the host. +Use Docker Engine, Docker Compose v2, Git, Make and flock (util-linux) on the host. No host Python, Ruby or project virtual environment is required for the container targets. This first release is opt-in while the real container acceptance checks run. @@ -64,3 +64,9 @@ excluded from source discovery; existing backups are not deleted. The wrapper ignores implicit Compose dotenv loading. Public package and hook downloads require network access. The existing native targets remain available with TOOLCHAIN=native. + +Commands are serialized per checkout using a Git-directory lock. After a +run or hook finishes, the wrapper removes only its exact idle Compose +default network, verified by name, Compose labels and network ID. Active +and unrelated networks are left alone; cleanup errors preserve the command +exit status. A forcibly killed wrapper may leave an idle network behind. diff --git a/scripts/toolchain.sh b/scripts/toolchain.sh index 4e6ebdd..2ea6090 100755 --- a/scripts/toolchain.sh +++ b/scripts/toolchain.sh @@ -31,6 +31,31 @@ if [[ -n "${GIT_INDEX_FILE:-}" ]]; then environment+=(-e "GIT_INDEX_FILE=$index") fi +# Serialize commands for this checkout, not the whole Docker daemon. +if [[ -L "$root/.git/container-toolchain.lock" ]]; then + echo "Refusing a symlinked toolchain lock." >&2 + exit 1 +fi +exec 9>"$root/.git/container-toolchain.lock" +flock -x 9 + +cleanup_network() { + local status=$? info id name owner logical active extra + trap - EXIT + if info=$(docker network inspect "${project}_default" --format \ + '{{.Id}} {{.Name}} {{index .Labels "com.docker.compose.project"}} {{index .Labels "com.docker.compose.network"}} {{len .Containers}}' 2>/dev/null); then + read -r id name owner logical active extra <<< "$info" + if [[ "$id" =~ ^[a-f0-9]{64}$ && "$name" == "${project}_default" && + "$owner" == "$project" && "$logical" == default && + "$active" == 0 && -z "$extra" ]]; then + if ! docker network rm "$id" >/dev/null; then + echo "Toolchain network was not removed; it may still be in use." >&2 + fi + fi + fi + exit "$status" +} + case "${1:-}" in build) [[ "$#" == 1 ]] @@ -39,7 +64,8 @@ case "${1:-}" in run) shift [[ "$#" -gt 0 ]] - exec "${compose[@]}" run --rm --build -T --no-deps "${environment[@]}" toolchain "$@" + trap cleanup_network EXIT + "${compose[@]}" run --rm --build -T --no-deps "${environment[@]}" toolchain "$@" ;; hook) shift @@ -48,7 +74,8 @@ case "${1:-}" in *) echo "Unsupported hook type." >&2; exit 1 ;; esac shift - exec "${compose[@]}" run --rm --build -T --no-deps "${environment[@]}" toolchain \ + trap cleanup_network EXIT + "${compose[@]}" run --rm --build -T --no-deps "${environment[@]}" toolchain \ pre-commit hook-impl --config .pre-commit-config.yaml \ --hook-type "$hook" --hook-dir "$root/.git/hooks" -- "$@" ;; diff --git a/tests/test_container_toolchain.py b/tests/test_container_toolchain.py index ab2f5e3..6a3a229 100644 --- a/tests/test_container_toolchain.py +++ b/tests/test_container_toolchain.py @@ -4,6 +4,8 @@ from __future__ import annotations +import fcntl +import hashlib import json import os import shutil @@ -47,6 +49,16 @@ def checkout(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: docker.write_text( f"#!{sys.executable}\n" "import json, os, sys\n" + "if sys.argv[1:3] == ['network', 'inspect']:\n" + " with open(os.environ['DOCKER_TEST_LOG'] + '.network', 'a') as stream:\n" + " stream.write(json.dumps(sys.argv[1:]) + '\\n')\n" + " info = os.environ.get('DOCKER_TEST_NETWORK', '')\n" + " if info: print(info)\n" + " sys.exit(0 if info else 1)\n" + "if sys.argv[1:3] == ['network', 'rm']:\n" + " with open(os.environ['DOCKER_TEST_LOG'] + '.network', 'a') as stream:\n" + " stream.write(json.dumps(sys.argv[1:]) + '\\n')\n" + " sys.exit(int(os.environ.get('DOCKER_TEST_REMOVE_EXIT', '0')))\n" "with open(os.environ['DOCKER_TEST_LOG'], 'a') as stream:\n" " stream.write(json.dumps({'args': sys.argv[1:], " "'uid': os.environ['LOCAL_UID'], 'gid': os.environ['LOCAL_GID'], " @@ -260,3 +272,72 @@ def test_container_discovery_excludes_host_caches(checkout: Path) -> None: str(checkout / "pyproject.toml"), str(checkout / "rendered/pyproject.toml"), } + + +@pytest.mark.parametrize( + "active,owner_matches,remove", + [(0, True, True), (1, True, False), (0, False, False)], +) +def test_network_cleanup_is_scoped( + checkout: Path, + monkeypatch: pytest.MonkeyPatch, + active: int, + owner_matches: bool, + remove: bool, +) -> None: + + project = ( + "cc-toolchain-" + + hashlib.sha256(str(checkout.resolve()).encode()).hexdigest()[:12] + ) + network_id = "a" * 64 + owner = project if owner_matches else "unrelated" + monkeypatch.setenv( + "DOCKER_TEST_NETWORK", + f"{network_id} {project}_default {owner} default {active}", + ) + monkeypatch.setenv("DOCKER_TEST_EXIT", "17") + result = invoke(checkout, "scripts/toolchain.sh", "run", "false") + assert result.returncode == 17 + log = checkout / ".git/engine.log.network" + calls = [json.loads(line) for line in log.read_text().splitlines()] + assert calls[0][:3] == ["network", "inspect", project + "_default"] + assert calls[1:] == ([["network", "rm", network_id]] if remove else []) + + +def test_cleanup_failure_preserves_success( + checkout: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + project = ( + "cc-toolchain-" + + hashlib.sha256(str(checkout.resolve()).encode()).hexdigest()[:12] + ) + monkeypatch.setenv( + "DOCKER_TEST_NETWORK", f"{'b' * 64} {project}_default {project} default 0" + ) + monkeypatch.setenv("DOCKER_TEST_REMOVE_EXIT", "1") + result = invoke(checkout, "scripts/toolchain.sh", "run", "true") + assert result.returncode == 0 + assert "may still be in use" in result.stderr + + +def test_wrapper_waits_for_checkout_lock(checkout: Path) -> None: + lock = checkout / ".git/container-toolchain.lock" + with lock.open("a") as stream: + fcntl.flock(stream, fcntl.LOCK_EX) + with subprocess.Popen( + ["scripts/toolchain.sh", "run", "true"], + cwd=checkout, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + ) as process: + try: + with pytest.raises(subprocess.TimeoutExpired): + process.communicate(timeout=0.25) + assert not (checkout / ".git/engine.log").exists() + finally: + fcntl.flock(stream, fcntl.LOCK_UN) + process.communicate(timeout=10) + assert process.returncode == 0 + assert engine_calls(checkout)