Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .github/workflows/container-toolchain.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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}}')"
1 change: 1 addition & 0 deletions changelogs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
- Import shared spelling dictionary
- Add containerized documentation preview
- Generate reviewed Python release preparation
- Add container development toolchain (#33)

### 🐛 Fixed

Expand Down
1 change: 1 addition & 0 deletions changelogs/releases/v0.1.0.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
- Import shared spelling dictionary
- Add containerized documentation preview
- Generate reviewed Python release preparation
- Add container development toolchain (#33)

### 🐛 Fixed

Expand Down
8 changes: 7 additions & 1 deletion docs/container-toolchain.md
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -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.
31 changes: 29 additions & 2 deletions scripts/toolchain.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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 ]]
Expand All @@ -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
Expand All @@ -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" -- "$@"
;;
Expand Down
81 changes: 81 additions & 0 deletions tests/test_container_toolchain.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

from __future__ import annotations

import fcntl
import hashlib
import json
import os
import shutil
Expand Down Expand Up @@ -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'], "
Expand Down Expand Up @@ -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)
Loading