diff --git a/compose/swarm/playbook.yml b/compose/swarm/playbook.yml index 90ccd50f40..7a6846194d 100644 --- a/compose/swarm/playbook.yml +++ b/compose/swarm/playbook.yml @@ -92,7 +92,7 @@ timeout: 30 register: lab_pacman_cache_script - - name: layer the node pacman caches before the first install, host cache read-only first and the shared cache second + - name: layer the node pacman caches before the first install, host cache read-only first, the node download dir second and the shared cache third command: argv: - /usr/local/bin/pacman-cache.sh diff --git a/docs/contributing/environment/cache.md b/docs/contributing/environment/cache.md index 4c5c5efb1d..eba9177258 100644 --- a/docs/contributing/environment/cache.md +++ b/docs/contributing/environment/cache.md @@ -49,7 +49,7 @@ One host folder, `INFINITO_CACHE_SHARED_HOST_PATH` (default `/shared` | Subfolder | Tool | How the consumer points at it | |---|---|---| -| `pacman/` | pacman | second `CacheDir` in `/etc/pacman.conf`, written by [pacman.sh](../../../scripts/docker/cache/pacman.sh) | +| `pacman/` | pacman | last `CacheDir` in `/etc/pacman.conf`, written by [pacman.sh](../../../scripts/docker/cache/pacman.sh); each node downloads into its own `pacman/node-XXXXXX/` | | `pip/` | pip | `PIP_CACHE_DIR` | | `npm/` | npm | `npm_config_cache` | | `ms-playwright/` | Playwright browsers | `PLAYWRIGHT_BROWSERS_PATH` | @@ -60,7 +60,7 @@ The consumers in this repository are wired as follows: - Swarm lab nodes: `01_bootstrap.sh` layers [compose/swarm/shared-cache.override.yml](../../../compose/swarm/shared-cache.override.yml) next to the cache override when the variable is set. It mounts the folder and `pacman.sh` into the manager, both workers, the NFS server and the backup host, and [playbook.yml](../../../compose/swarm/playbook.yml) runs `pacman.sh` on each node that has it. - Core Playwright runs take their browsers from the `mcr.microsoft.com/playwright` image, so they leave `ms-playwright/` empty. -pacman on an arch stack reads up to two cache directories. `INFINITO_CACHE_HOST_PACMAN_PATH`, written by [host_pacman_path.py](../../../utils/env/handlers/infinito/cache/host_pacman_path.py), is the first `CacheDir` of the host's `pacman-conf`, and only on a host whose `/etc/os-release` `ID` is exactly `arch` running an arch stack. On Manjaro, EndeavourOS and every other host, and on every stack that does not run pacman, the variable is empty and pacman uses the shared layer alone. When it is set, [compose/pacman.override.yml](../../../compose/pacman.override.yml) and [compose/swarm/pacman.override.yml](../../../compose/swarm/pacman.override.yml) mount it read-only at the same path, layered only together with the shared folder. `pacman.sh` lists it as the first `CacheDir` and `/pacman/` as the second. pacman finds a package in either directory and downloads a missing one into `/pacman/`, the first one it can write. The disc-space cleanup runs `pacman -Sc` per writable `CacheDir`, so it never touches the read-only layer. +pacman on an arch stack reads up to three cache directories. `INFINITO_CACHE_HOST_PACMAN_PATH`, written by [host_pacman_path.py](../../../utils/env/handlers/infinito/cache/host_pacman_path.py), is the first `CacheDir` of the host's `pacman-conf`, and only on a host whose `/etc/os-release` `ID` is exactly `arch` running an arch stack. On Manjaro, EndeavourOS and every other host, and on every stack that does not run pacman, the variable is empty and pacman uses the shared layer alone. When it is set, [compose/pacman.override.yml](../../../compose/pacman.override.yml) and [compose/swarm/pacman.override.yml](../../../compose/swarm/pacman.override.yml) mount it read-only at the same path, layered only together with the shared folder. `pacman.sh` lists it as the first `CacheDir`, the node's own download directory `/pacman/node-XXXXXX/` as the second and `/pacman/` as the third. `pacman.sh` creates the node download directory with `mktemp` on its first run and reuses the one already listed in `pacman.conf` on every later run. pacman finds a package in any of the three directories and downloads a missing one, `.part` file included, into the node download directory, the first one it can write. The `PostTransaction` hook `pacman.sh` writes to `pacman.d/hooks/infinito-shared-cache.hook` beside `pacman.conf` then renames every finished package and signature from the node download directory into `/pacman/` and leaves `.part` files there for the next resume. `pacman.sh` fails when `pacman.conf` sets `HookDir`. The disc-space cleanup runs `pacman -Sc` per writable `CacheDir`, so it never touches the read-only layer. apt and dnf keep their per-container caches. Their downloads come through the `apt-*` and `yum-*` proxies of the package cache, which store each file once for the whole host. diff --git a/docs/requirements/065-shared-stack-caches.md b/docs/requirements/065-shared-stack-caches.md index 21307b633e..6891df150a 100644 --- a/docs/requirements/065-shared-stack-caches.md +++ b/docs/requirements/065-shared-stack-caches.md @@ -12,9 +12,9 @@ As an operator who runs several compose slots, swarm lab clusters and GUI lanes - [ ] With `INFINITO_CACHE_SHARED_HOST_PATH` and `INFINITO_CACHE_HOST_PACMAN_PATH` empty or missing from `.env`, a compose slot renders and starts without the cache mounts and the cache environment, and `docker compose config` of its services is byte-identical to the render of the same `.env` before this change. - [ ] `make dotenv` writes the host's pacman cache directory to `INFINITO_CACHE_HOST_PACMAN_PATH` only when the host's `/etc/os-release` `ID` is exactly `arch` and the stack runs arch; on Manjaro and every other host or stack the value is empty and pacman uses the shared folder alone. - [ ] With `INFINITO_CACHE_HOST_PACMAN_PATH` and `INFINITO_CACHE_SHARED_HOST_PATH` set, the rendered compose slot and every rendered swarm lab node mount the host pacman cache read-only at the same path. -- [ ] `scripts/docker/cache/pacman.sh` rewrites `[options]` of a `pacman.conf` so that the read-only host cache is the first `CacheDir` and `/pacman/` the second, removes every other `CacheDir` line, gives the same result when run twice, and leaves a system without `pacman.conf` untouched. +- [ ] `scripts/docker/cache/pacman.sh` rewrites `[options]` of a `pacman.conf` so that the read-only host cache is the first `CacheDir`, the node's own download directory `/pacman/node-XXXXXX/` the second and `/pacman/` the third, gives two nodes on one shared folder different download directories, removes every other `CacheDir` line, writes a `PostTransaction` hook that renames finished downloads from the node download directory into `/pacman/`, gives the same result when run twice, and leaves a system without `pacman.conf` untouched. - [ ] `make compose-up` and the swarm node bootstrap run that script in every arch runner and arch lab node that mounts the shared folder. -- [ ] A package pacman downloads on an arch runner or lab node lands in `/pacman/`, and the host cache directory stays byte-identical. +- [ ] A package pacman downloads on an arch runner or lab node lands in `/pacman/` once its transaction completes, two nodes that download the same package at the same time never write the same file, and the host cache directory stays byte-identical. - [ ] apt and dnf keep their per-container caches and reach the package cache proxies as before; `docs/contributing/environment/cache.md` states this next to the folder layout. - [ ] `docs/contributing/environment/cache.md` documents the folder layout, both variables and the mount contract a GUI lane follows. - [ ] Images keep reaching every inner daemon through `infinito-registry-cache`; no compose file shares a docker data root between daemons. diff --git a/scripts/docker/cache/pacman.sh b/scripts/docker/cache/pacman.sh index 0279c29df4..82fc892989 100755 --- a/scripts/docker/cache/pacman.sh +++ b/scripts/docker/cache/pacman.sh @@ -1,6 +1,6 @@ #!/usr/bin/env bash -# Param: $1 pacman.conf to rewrite; a missing file means no pacman, nothing is layered -# Param: $2 shared infinito cache root; pacman writes below /pacman/ +# Param: $1 pacman.conf to rewrite; a missing file means no pacman, nothing is layered; the publish hook goes to pacman.d/hooks/ beside it +# Param: $2 shared infinito cache root; pacman downloads into /pacman/node-XXXXXX/ and publishes into /pacman/ # Param: $3 read-only host pacman cache, mounted at the same path; empty leaves that layer out set -euo pipefail @@ -18,6 +18,11 @@ grep -qx '\[options\]' "${CONF}" || { exit 1 } +if grep -qE '^[[:space:]]*HookDir[[:space:]]*=' "${CONF}"; then + echo "[pacman-cache] ${CONF} sets HookDir, so pacman would not read the publish hook in its default hook directory" >&2 + exit 1 +fi + if [ -n "${HOST}" ] && [ ! -d "${HOST}" ]; then echo "[pacman-cache] host cache ${HOST} is not mounted" >&2 exit 1 @@ -26,16 +31,42 @@ fi OWN="${SHARED%/}/pacman" mkdir -p "${OWN}" +STAGE="$(awk -v prefix="CacheDir = ${OWN}/node-" ' + index($0, prefix) == 1 { line = substr($0, 12); sub(/\/$/, "", line); print line; exit } +' "${CONF}")" +if [ -n "${STAGE}" ]; then + mkdir -p "${STAGE}" +else + STAGE="$(mktemp -d "${OWN}/node-XXXXXX")" +fi +chmod 0755 "${STAGE}" + layered="$(mktemp)" trap 'rm -f "${layered}"' EXIT -awk -v host="${HOST%/}" -v own="${OWN}" ' +awk -v host="${HOST%/}" -v stage="${STAGE}" -v own="${OWN}" ' /^[[:space:]]*CacheDir[[:space:]]*=/ { next } { print } $0 == "[options]" { if (host != "") print "CacheDir = " host "/" + print "CacheDir = " stage "/" print "CacheDir = " own "/" } ' "${CONF}" >"${layered}" cat "${layered}" >"${CONF}" -echo "[pacman-cache] CacheDir: ${HOST:+${HOST%/}/ (read-only), }${OWN}/" >&2 +HOOKS="$(dirname "${CONF}")/pacman.d/hooks" +mkdir -p "${HOOKS}" +printf '%s\n' \ + '[Trigger]' \ + 'Operation = Install' \ + 'Operation = Upgrade' \ + 'Type = Package' \ + 'Target = *' \ + '' \ + '[Action]' \ + 'Description = Publishing downloaded packages to the shared pacman cache...' \ + 'When = PostTransaction' \ + "Exec = /usr/bin/find \"${STAGE}\" -maxdepth 1 -type f ! -name *.part -exec /usr/bin/mv -f -t \"${OWN}\" {} +" \ + >"${HOOKS}/infinito-shared-cache.hook" + +echo "[pacman-cache] CacheDir: ${HOST:+${HOST%/}/ (read-only), }${STAGE}/ (downloads), ${OWN}/" >&2 diff --git a/tests/unit/python/scripts/docker/cache/test_pacman.py b/tests/unit/python/scripts/docker/cache/test_pacman.py index 6d756410fc..edf960b341 100644 --- a/tests/unit/python/scripts/docker/cache/test_pacman.py +++ b/tests/unit/python/scripts/docker/cache/test_pacman.py @@ -1,7 +1,6 @@ -"""pacman.sh layers the read-only host cache first and the shared cache second.""" - from __future__ import annotations +import shlex import subprocess import tempfile import unittest @@ -20,6 +19,7 @@ Architecture = auto [core] Include = /etc/pacman.d/mirrorlist """ +HOOK = Path("pacman.d") / "hooks" / "infinito-shared-cache.hook" def layer(conf: Path, shared: Path, host: str) -> subprocess.CompletedProcess: @@ -54,18 +54,34 @@ class TestPacmanCacheLayering(unittest.TestCase): def _text(self) -> str: return self.conf.read_text() # nocheck: cache-read the script rewrites it + def _hook(self) -> str: + hook = self.tmp / HOOK + return hook.read_text() # nocheck: cache-read the script writes it + def _options(self) -> list[str]: lines = self._text().splitlines() return lines[: lines.index("") if "" in lines else len(lines)] - def test_host_cache_comes_first_and_shared_cache_second(self) -> None: + def _stage(self, conf: Path) -> Path: + prefix = f"CacheDir = {self.shared}/pacman/node-" + text = conf.read_text() # nocheck: cache-read the script rewrites it + lines = text.splitlines() + stages = [line for line in lines if line.startswith(prefix)] + self.assertEqual(len(stages), 1, lines) + self.assertTrue(stages[0].endswith("/"), stages[0]) + return Path(stages[0].removeprefix("CacheDir = ").rstrip("/")) + + def test_host_cache_comes_first_then_the_node_download_dir_then_the_shared_cache( + self, + ) -> None: done = layer(self.conf, self.shared, str(self.host)) self.assertEqual(done.returncode, 0, done.stderr) self.assertEqual( - self._options()[:3], + self._options()[:4], [ "[options]", f"CacheDir = {self.host}/", + f"CacheDir = {self._stage(self.conf)}/", f"CacheDir = {self.shared}/pacman/", ], ) @@ -77,34 +93,121 @@ class TestPacmanCacheLayering(unittest.TestCase): self.assertIn("#CacheDir = /var/cache/pacman/pkg/", text) self.assertIn("[core]\nInclude = /etc/pacman.d/mirrorlist\n", text) - def test_the_shared_pacman_dir_is_created(self) -> None: + def test_the_shared_pacman_dir_and_a_traversable_node_download_dir_are_created( + self, + ) -> None: layer(self.conf, self.shared, str(self.host)) + stage = self._stage(self.conf) self.assertTrue((self.shared / "pacman").is_dir()) + self.assertTrue(stage.is_dir()) + self.assertEqual(stage.parent, self.shared / "pacman") + self.assertEqual(stage.stat().st_mode & 0o777, 0o755) def test_a_second_run_changes_nothing(self) -> None: layer(self.conf, self.shared, str(self.host)) + first, first_hook = self._text(), self._hook() + done = layer(self.conf, self.shared, str(self.host)) + self.assertEqual(done.returncode, 0, done.stderr) + self.assertEqual(self._text(), first) + self.assertEqual(self._hook(), first_hook) + self.assertEqual(len(list((self.shared / "pacman").glob("node-*"))), 1) + + def test_a_second_run_recreates_a_removed_node_download_dir_under_its_name( + self, + ) -> None: + layer(self.conf, self.shared, str(self.host)) + stage = self._stage(self.conf) + stage.rmdir() first = self._text() layer(self.conf, self.shared, str(self.host)) self.assertEqual(self._text(), first) + self.assertTrue(stage.is_dir()) - def test_an_empty_host_cache_leaves_only_the_shared_layer(self) -> None: + def test_two_nodes_on_one_shared_folder_download_into_different_dirs(self) -> None: + other = self.tmp / "other" / "pacman.conf" + other.parent.mkdir() + other.write_text(CONF) + layer(self.conf, self.shared, str(self.host)) + layer(other, self.shared, str(self.host)) + self.assertNotEqual(self._stage(self.conf), self._stage(other)) + self.assertTrue(self._stage(other).is_dir()) + + def test_an_empty_host_cache_leaves_the_node_download_dir_and_the_shared_layer( + self, + ) -> None: layer(self.conf, self.shared, "") self.assertEqual( - self._options()[:2], ["[options]", f"CacheDir = {self.shared}/pacman/"] + self._options()[:3], + [ + "[options]", + f"CacheDir = {self._stage(self.conf)}/", + f"CacheDir = {self.shared}/pacman/", + ], ) self.assertEqual( - sum(line.startswith("CacheDir") for line in self._options()), 1 + sum(line.startswith("CacheDir") for line in self._options()), 2 ) + def test_the_hook_runs_after_every_install_and_upgrade(self) -> None: + layer(self.conf, self.shared, str(self.host)) + hook = self._hook().splitlines() + for line in ( + "Operation = Install", + "Operation = Upgrade", + "Type = Package", + "Target = *", + "When = PostTransaction", + ): + self.assertIn(line, hook) + + def test_the_hook_publishes_finished_downloads_and_keeps_partials(self) -> None: + layer(self.conf, self.shared, str(self.host)) + stage = self._stage(self.conf) + own = self.shared / "pacman" + for name in ("a-1-1-any.pkg.tar.zst", "a-1-1-any.pkg.tar.zst.sig"): + (stage / name).write_text(name) + (stage / "b-1-1-any.pkg.tar.zst.part").write_text("partial") + (own / "a-1-1-any.pkg.tar.zst").write_text("stale") + (exec_line,) = [ + line for line in self._hook().splitlines() if line.startswith("Exec = ") + ] + done = subprocess.run( + shlex.split(exec_line.removeprefix("Exec = ")), + capture_output=True, + text=True, + check=False, + ) + self.assertEqual(done.returncode, 0, done.stderr) + self.assertEqual( + sorted(path.name for path in stage.iterdir()), + ["b-1-1-any.pkg.tar.zst.part"], + ) + published = own / "a-1-1-any.pkg.tar.zst" + self.assertEqual( + published.read_text(), # nocheck: cache-read the hook moves it + "a-1-1-any.pkg.tar.zst", + ) + self.assertTrue((own / "a-1-1-any.pkg.tar.zst.sig").is_file()) + def test_a_system_without_pacman_conf_is_left_alone(self) -> None: done = layer(self.tmp / "absent.conf", self.shared, str(self.host)) self.assertEqual(done.returncode, 0, done.stderr) self.assertFalse(self.shared.exists()) + self.assertFalse((self.tmp / HOOK).exists()) def test_a_host_cache_that_is_not_mounted_fails(self) -> None: done = layer(self.conf, self.shared, str(self.tmp / "missing")) self.assertNotEqual(done.returncode, 0) self.assertEqual(self._text(), CONF) + self.assertFalse((self.tmp / HOOK).exists()) + + def test_a_hook_dir_override_fails(self) -> None: + conf = CONF.replace("[options]\n", "[options]\nHookDir = /srv/hooks/\n") + self.conf.write_text(conf) + done = layer(self.conf, self.shared, str(self.host)) + self.assertNotEqual(done.returncode, 0) + self.assertEqual(self._text(), conf) + self.assertFalse(self.shared.exists()) def test_a_missing_shared_root_fails(self) -> None: done = subprocess.run(