diff --git a/Dockerfile b/Dockerfile index 3f5b0010a5..b3ac4fb1be 100644 --- a/Dockerfile +++ b/Dockerfile @@ -3,8 +3,12 @@ # scripts/image/build.sh. # Example values: # INFINITO_PARENT_IMAGE=ghcr.io/kevinveenbirkenbach/pkgmgr-arch:stable +# INFINITO_LINT_RUNNER (host|docker, SPOT default.env) selects the stage `full` +# builds on: lint-docker with the lint toolchain, lint-host without it. ARG INFINITO_PARENT_IMAGE -FROM ${INFINITO_PARENT_IMAGE} AS full +# nocheck: dockerfile-arg-default +ARG INFINITO_LINT_RUNNER=host +FROM ${INFINITO_PARENT_IMAGE} AS base ARG NIX_CONFIG @@ -57,6 +61,44 @@ RUN set -euo pipefail; \ ANSIBLE_COLLECTIONS_DIR="${HOME}/.ansible/collections" \ bash "${INFINITO_SRC_DIR}/scripts/install/ansible.sh" +FROM base AS lint-host + +FROM base AS lint-docker + +SHELL ["/bin/bash", "-o", "pipefail", "-lc"] + +COPY packaging ${INFINITO_SRC_DIR}/packaging +COPY roles/sys-svc-container/files/shell ${INFINITO_SRC_DIR}/roles/sys-svc-container/files/shell +COPY roles/sys-lint/meta/services.yml ${INFINITO_SRC_DIR}/roles/sys-lint/meta/services.yml +COPY utils/cache/__init__.py ${INFINITO_SRC_DIR}/utils/cache/__init__.py +COPY utils/cache/files.py ${INFINITO_SRC_DIR}/utils/cache/files.py +COPY utils/cache/gitignore.py ${INFINITO_SRC_DIR}/utils/cache/gitignore.py +COPY utils/roles/__init__.py ${INFINITO_SRC_DIR}/utils/roles/__init__.py +COPY utils/roles/custom.py ${INFINITO_SRC_DIR}/utils/roles/custom.py +COPY utils/roles/mapping.py ${INFINITO_SRC_DIR}/utils/roles/mapping.py +COPY utils/install ${INFINITO_SRC_DIR}/utils/install + +# hadolint ignore=DL3008,DL3033,DL3041,SC1090 +RUN set -euo pipefail; \ + source <(grep -hE '^INFINITO_(PYTHON|DOCKER_CLI|PACKAGE|INTERPRETERS)_INSTALL_SCRIPT=' "${INFINITO_SRC_DIR}/default.env"); \ + /bin/bash "${INFINITO_SRC_DIR}/${INFINITO_PYTHON_INSTALL_SCRIPT:?}"; \ + /bin/bash "${INFINITO_SRC_DIR}/${INFINITO_DOCKER_CLI_INSTALL_SCRIPT:?}"; \ + /bin/bash "${INFINITO_SRC_DIR}/${INFINITO_PACKAGE_INSTALL_SCRIPT:?}"; \ + /bin/bash "${INFINITO_SRC_DIR}/${INFINITO_INTERPRETERS_INSTALL_SCRIPT:?}" + +SHELL ["/bin/bash", "-o", "pipefail", "-c"] + +RUN PYTHONPATH="${INFINITO_SRC_DIR}" python3 -m utils.install.lint action ansible python php ruby shellcheck dockerfile markdown mermaid makefile + +# hadolint ignore=DL3006 +FROM lint-${INFINITO_LINT_RUNNER} AS full + +ARG NIX_CONFIG +ARG INFINITO_SRC_DIR +ARG INFINITO_VENV_DIR + +SHELL ["/bin/bash", "-o", "pipefail", "-lc"] + COPY . ${INFINITO_SRC_DIR} # hadolint ignore=DL3008,DL3033,DL3041,SC1090 diff --git a/cli/administration/deploy/dedicated/apps.py b/cli/administration/deploy/dedicated/apps.py index 154bda63fa..3402bc9fe7 100644 --- a/cli/administration/deploy/dedicated/apps.py +++ b/cli/administration/deploy/dedicated/apps.py @@ -1,30 +1,6 @@ from __future__ import annotations import sys -from pathlib import Path - - -def _dump_inventory_full(inventory: str) -> None: - """ - Print the full inventory file content (raw) to simplify CI debugging. - """ - - print("\n[DEBUG] Full inventory dump:") - print(f"[DEBUG] inventory path: {inventory}") - - if not Path(inventory).exists(): - print("[DEBUG] inventory file does not exist") - return - - try: - with Path(inventory).open(encoding="utf-8", errors="replace") as f: - content = f.read() - - print("\n===== BEGIN INVENTORY FILE =====") - print(content.rstrip("\n")) - print("===== END INVENTORY FILE =====\n") - except Exception as exc: - print(f"[DEBUG] failed to read inventory: {exc}") def validate_application_ids(inventory: str, app_ids: list[str]) -> None: @@ -40,7 +16,7 @@ def validate_application_ids(inventory: str, app_ids: list[str]) -> None: if not invalid: return - print("\n[ERROR] Some application_ids are invalid for this inventory:\n") + print(f"\n[ERROR] Some application_ids are invalid for inventory {inventory}:\n") for app_id, status in invalid.items(): reasons = [] if not status.get("in_roles", True): @@ -49,5 +25,4 @@ def validate_application_ids(inventory: str, app_ids: list[str]) -> None: reasons.append("not present in inventory") print(f" - {app_id}: {', '.join(reasons)}") - _dump_inventory_full(inventory) sys.exit(1) diff --git a/compose.yml b/compose.yml index 51a4a3bd36..69ed6243ff 100644 --- a/compose.yml +++ b/compose.yml @@ -26,6 +26,7 @@ services: dockerfile: Dockerfile args: INFINITO_PARENT_IMAGE: ${INFINITO_PARENT_IMAGE:?Run 'make dotenv' to generate the .env single source of truth} + INFINITO_LINT_RUNNER: ${INFINITO_LINT_RUNNER:?Run 'make dotenv' to generate the .env single source of truth} INFINITO_SRC_DIR: ${INFINITO_SRC_DIR:?Run 'make dotenv' to generate the .env single source of truth} INFINITO_PACKAGE_INSTALL_SCRIPT: ${INFINITO_PACKAGE_INSTALL_SCRIPT:?Run 'make dotenv' to generate the .env single source of truth} INFINITO_PYTHON_INSTALL_SCRIPT: ${INFINITO_PYTHON_INSTALL_SCRIPT:?Run 'make dotenv' to generate the .env single source of truth} diff --git a/default.env b/default.env index 48ce2bb018..9bf1183b89 100644 --- a/default.env +++ b/default.env @@ -280,7 +280,7 @@ INFINITO_LIMIT_HOST=localhost # Git ref whose merge-base with HEAD bounds local file lints to the files changed since; empty, a missing ref or CI lints every file. INFINITO_LINT_DIFF_BASE=origin/main -# Where scripts/lint/wrapper.sh executes 'make lint*' / 'make autoformat': host | docker. +# Where scripts/lint/wrapper.sh executes 'make lint*' / 'make autoformat': host | docker (also bakes the lint tools); GHA/act default host. INFINITO_LINT_RUNNER=docker # Public FQDN of a reachable mail server; when set, the provider asserts its live DNS/TLS/SMTP hard facts. Empty disables the check. diff --git a/docs/contributing/artefact/files/compose.yml.md b/docs/contributing/artefact/files/compose.yml.md index 6a9995bc82..4d080cda4a 100644 --- a/docs/contributing/artefact/files/compose.yml.md +++ b/docs/contributing/artefact/files/compose.yml.md @@ -32,6 +32,7 @@ The per-variable default + comment lives next to the key in [default.env](../../ | `INFINITO_IMAGE` | Image reference used by the `infinito` service. Composed at runtime by the env generator on GHA, empty locally so the `build:` block builds from source. | | `INFINITO_BUILD` | `1` builds the `infinito` image from source before `up`; the env generator sets `0` on GHA, where the service runs the published `INFINITO_IMAGE`, unless the job sets it. | | `INFINITO_PULL_POLICY` | Compose `pull_policy`, also exported into the `infinito` container. Defaults to `never` for local builds, generator overrides to `always` on GHA. | +| `INFINITO_LINT_RUNNER` | Build-arg naming the stage the image builds on: `docker` adds the lint toolchain through the cached `lint-docker` layer below `COPY .`, `host` builds on `lint-host` without it. The generator defaults it to `host` on GHA and act unless the job sets it, and CI's [push.sh](../../../../scripts/image/push.sh) passes nothing, so CI images stay without the toolchain. | | `INFINITO_CONTAINER` | Used directly as `container_name`. Derived from `INFINITO_DISTRO` by [container.py](../../../../utils/env/handlers/infinito/container.py). | | `NIX_CONFIG` | Build-arg forwarded to the Dockerfile for Nix configuration. Pass-through if set in the calling shell. | diff --git a/scripts/image/build.sh b/scripts/image/build.sh index e7032eece8..42bb43ca09 100755 --- a/scripts/image/build.sh +++ b/scripts/image/build.sh @@ -9,6 +9,7 @@ _build_script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" source "${_build_script_dir}/../meta/env/load.sh" : "${INFINITO_PARENT_IMAGE:?Missing INFINITO_PARENT_IMAGE; source scripts/meta/env/load.sh}" +: "${INFINITO_LINT_RUNNER:?Missing INFINITO_LINT_RUNNER; source scripts/meta/env/load.sh}" NO_CACHE=0 MISSING_ONLY=0 @@ -207,6 +208,7 @@ echo "[build] Building image" echo "distro = ${INFINITO_DISTRO}" echo "target = ${TARGET}" echo "INFINITO_PARENT_IMAGE = ${INFINITO_PARENT_IMAGE}" +echo "INFINITO_LINT_RUNNER = ${INFINITO_LINT_RUNNER}" if [[ "${NO_CACHE}" == "1" ]]; then echo "cache = disabled"; fi if [[ "${PUSH}" == "1" ]]; then echo "push = enabled"; fi if [[ "${PUBLISH}" == "1" ]]; then @@ -230,6 +232,7 @@ echo "------------------------------------------------------------" : "${INFINITO_DOCKER_CLI_INSTALL_SCRIPT:?INFINITO_DOCKER_CLI_INSTALL_SCRIPT must be set; source scripts/meta/env/load.sh}" build_args=( --build-arg "INFINITO_PARENT_IMAGE=${INFINITO_PARENT_IMAGE}" + --build-arg "INFINITO_LINT_RUNNER=${INFINITO_LINT_RUNNER}" --build-arg "INFINITO_SRC_DIR=${INFINITO_SRC_DIR}" --build-arg "INFINITO_VENV_DIR=${INFINITO_VENV_DIR}" --build-arg "INFINITO_PACKAGE_INSTALL_SCRIPT=${INFINITO_PACKAGE_INSTALL_SCRIPT}" diff --git a/tests/unit/python/cli/administration/deploy/dedicated/test_apps.py b/tests/unit/python/cli/administration/deploy/dedicated/test_apps.py index 2883326e77..959aaa42dd 100644 --- a/tests/unit/python/cli/administration/deploy/dedicated/test_apps.py +++ b/tests/unit/python/cli/administration/deploy/dedicated/test_apps.py @@ -1,7 +1,11 @@ from __future__ import annotations +import contextlib +import io +import tempfile import unittest import unittest.mock +from pathlib import Path from cli.administration.deploy.dedicated import apps @@ -30,6 +34,25 @@ class TestValidateApplicationIds(unittest.TestCase): ["web-app-foo", "web-app-bar"], ) + @unittest.mock.patch("utils.roles.validation.deploy_id.ValidDeployId") + def test_invalid_ids_never_print_the_inventory_content(self, mock_vdi_cls): + mock_vdi_cls.return_value.validate.return_value = { + "web-app-typo": {"in_roles": False} + } + with tempfile.TemporaryDirectory() as tmp: + inventory = Path(tmp) / "devices.yml" + inventory.write_text( + "all:\n vars:\n ansible_become_password: s3cr3t-marker\n", + encoding="utf-8", + ) + out = io.StringIO() + with contextlib.redirect_stdout(out), self.assertRaises(SystemExit): + apps.validate_application_ids(str(inventory), ["web-app-typo"]) + + self.assertIn(str(inventory), out.getvalue()) + self.assertIn("web-app-typo: not defined as a role", out.getvalue()) + self.assertNotIn("s3cr3t-marker", out.getvalue()) + @unittest.mock.patch("utils.roles.validation.deploy_id.ValidDeployId") def test_valid_ids_do_not_exit(self, mock_vdi_cls): instance = mock_vdi_cls.return_value diff --git a/tests/unit/python/utils/env/handlers/infinito/test_lint_runner.py b/tests/unit/python/utils/env/handlers/infinito/test_lint_runner.py new file mode 100644 index 0000000000..ea851776fa --- /dev/null +++ b/tests/unit/python/utils/env/handlers/infinito/test_lint_runner.py @@ -0,0 +1,45 @@ +from __future__ import annotations + +import os +import unittest +from pathlib import Path +from unittest.mock import patch + +from utils.env.builder import BuildContext, EnvBuilder +from utils.env.handlers.infinito import lint_runner as handler + + +def _ctx(*, on_gha: bool, on_act: bool) -> BuildContext: + return BuildContext( + static={}, + static_comments={}, + repo_root=Path("/repo"), + on_gha=on_gha, + on_act=on_act, + ) + + +def _apply(ctx: BuildContext) -> str | None: + eb = EnvBuilder() + handler.apply(eb, ctx) + return eb.values.get(handler.KEY) + + +@patch.dict(os.environ, {handler.KEY: ""}) +class TestLintRunner(unittest.TestCase): + def test_a_github_runner_lints_on_the_host(self) -> None: + self.assertEqual(_apply(_ctx(on_gha=True, on_act=False)), "host") + + def test_act_lints_on_the_host(self) -> None: + self.assertEqual(_apply(_ctx(on_gha=False, on_act=True)), "host") + + def test_a_developer_machine_keeps_the_static_value(self) -> None: + self.assertIsNone(_apply(_ctx(on_gha=False, on_act=False))) + + def test_a_github_job_that_sets_the_runner_keeps_it(self) -> None: + with patch.dict(os.environ, {handler.KEY: "docker"}): + self.assertEqual(_apply(_ctx(on_gha=True, on_act=False)), "docker") + + +if __name__ == "__main__": # pragma: no cover + unittest.main() diff --git a/tests/unit/python/utils/install/lint/test_main.py b/tests/unit/python/utils/install/lint/test_main.py index be096bf743..3aebb625b4 100644 --- a/tests/unit/python/utils/install/lint/test_main.py +++ b/tests/unit/python/utils/install/lint/test_main.py @@ -2,15 +2,33 @@ from __future__ import annotations +import contextlib +import functools import os +import re +import subprocess +import sys import time import unittest import unittest.mock as mock from pathlib import Path from tempfile import TemporaryDirectory +from tests.utils import image_slice +from utils.cache.files import read_text from utils.install.lint import __main__ as cli +_IN_TREE_GROUPS = frozenset({"javascript", "playwright"}) +_BAKE = re.compile(r"^RUN .*-m utils\.install\.lint (?P[a-z ]+)$") + + +def _baked_groups() -> list[str]: + for line in read_text(str(image_slice.DOCKERFILE)).splitlines(): + match = _BAKE.match(line.strip()) + if match: + return match.group("groups").split() + return [] + def _make_repo_root(tmp: str, *, stamp_age_offset: float | None = None) -> Path: root = Path(tmp) @@ -203,5 +221,69 @@ class TestGroupDispatch(unittest.TestCase): self.assertEqual(rc, 1) +class TestImageBake(unittest.TestCase): + def test_the_lint_stage_bakes_every_all_mode_group_outside_the_tree(self) -> None: + called: list[str] = [] + with contextlib.ExitStack() as stack: + for group, name in cli._GROUP_FN_NAMES.items(): + stack.enter_context( + mock.patch.object( + cli, name, side_effect=functools.partial(called.append, group) + ) + ) + cli._install_all() + self.assertEqual( + _baked_groups(), + [group for group in called if group not in _IN_TREE_GROUPS], + "the Dockerfile's lint-docker stage must install every all-mode " + "group except the ones the bind-mounted tree replaces, in order", + ) + + def test_the_lint_stage_runs_the_full_stage_system_step_before_the_bake( + self, + ) -> None: + lint_runs = image_slice.stage_runs("lint-docker") + self.assertEqual( + lint_runs[:1], + image_slice.stage_runs("full")[:1], + "the lint-docker stage must open with the full stage's system " + "package step, so the bake resolves packages in the order a " + "runtime install does", + ) + self.assertRegex(lint_runs[-1], _BAKE) + + def test_the_installer_runs_on_the_slice_the_lint_stage_copies(self) -> None: + tmp = TemporaryDirectory() + self.addCleanup(tmp.cleanup) + slice_root = Path(tmp.name) + image_slice.materialise(slice_root, frozenset({"base", "lint-docker"})) + + result = subprocess.run( + [sys.executable, "-S", "-m", "utils.install.lint", "no-such-group"], + cwd=str(slice_root), + capture_output=True, + text=True, + check=False, + ) + + self.assertNotIn( + "ModuleNotFoundError", + result.stderr, + "utils.install.lint reached for a module the lint-docker stage " + "does not copy; copy it there or keep the installer off it", + ) + self.assertEqual(result.returncode, 1, result.stderr) + self.assertIn("Usage:", result.stderr) + + interpreters = subprocess.run( + [sys.executable, "-S", "-c", "import utils.install.interpreters"], + cwd=str(slice_root), + capture_output=True, + text=True, + check=False, + ) + self.assertEqual(interpreters.returncode, 0, interpreters.stderr) + + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/utils/install/test_collections.py b/tests/unit/python/utils/install/test_collections.py index 8ff53e96cb..b16264e042 100644 --- a/tests/unit/python/utils/install/test_collections.py +++ b/tests/unit/python/utils/install/test_collections.py @@ -1,54 +1,15 @@ import json -import re -import shutil import subprocess import sys import unittest from pathlib import Path from tempfile import TemporaryDirectory +from tests.utils import image_slice from utils import PROJECT_ROOT -from utils.cache.files import read_text from utils.cache.yaml import load_yaml_any from utils.install.collections import declared_pins, unsatisfied -_DOCKERFILE = PROJECT_ROOT / "Dockerfile" -_COPY = re.compile(r"^COPY\s+(?P\S+)\s+\$\{INFINITO_SRC_DIR\}/(?P\S+)$") - - -def _materialise_image_slice(destination: Path) -> None: - """Reproduce what the image holds when it first runs the collection check. - - The Dockerfile copies a handful of paths, runs ``scripts/install/ansible.sh`` - against them, and only afterwards copies the rest of the tree. Anything - ``utils.install.collections`` imports beyond that slice is absent in the - layer that executes it, which no import inside a full checkout can show. - The list is read from the Dockerfile rather than restated here, so a COPY - added or dropped moves this probe with it. - - The caller must run the slice under ``python -S``. This repository installs - ``utils`` into site-packages, so without it the interpreter resolves every - submodule from the checkout however the slice is built, and the probe - passes on a module that cannot import inside the image. - - Args: - destination: an empty directory to build the slice in. - """ - for line in read_text(str(_DOCKERFILE)).splitlines(): - if line.startswith("COPY . "): - return - match = _COPY.match(line.strip()) - if not match: - continue - source = PROJECT_ROOT / match.group("source") - target = destination / match.group("target") - target.parent.mkdir(parents=True, exist_ok=True) - if source.is_dir(): - shutil.copytree(source, target, dirs_exist_ok=True) - else: - shutil.copy2(source, target) - - _REQUIREMENTS = ( PROJECT_ROOT / "requirements" / "requirements.galaxy.yml", PROJECT_ROOT / "requirements" / "requirements.git.yml", @@ -133,7 +94,7 @@ class TestAgainstPyYAML(unittest.TestCase): tmp = TemporaryDirectory() self.addCleanup(tmp.cleanup) slice_root = Path(tmp.name) - _materialise_image_slice(slice_root) + image_slice.materialise(slice_root, frozenset({"base"})) requirements = slice_root / "requirements" / "requirements.galaxy.yml" self.assertTrue( requirements.is_file(), diff --git a/tests/utils/image_slice.py b/tests/utils/image_slice.py new file mode 100644 index 0000000000..26a07b96e1 --- /dev/null +++ b/tests/utils/image_slice.py @@ -0,0 +1,59 @@ +from __future__ import annotations + +import re +import shutil +from typing import TYPE_CHECKING + +from utils import PROJECT_ROOT +from utils.cache.files import read_text + +if TYPE_CHECKING: + from pathlib import Path + +DOCKERFILE = PROJECT_ROOT / "Dockerfile" + +_STAGE = re.compile(r"^FROM\s+\S+\s+AS\s+(?P\S+)$", re.IGNORECASE) +_COPY = re.compile(r"^COPY\s+(?P\S+)\s+\$\{INFINITO_SRC_DIR\}/(?P\S+)$") + + +def _instructions() -> list[tuple[str, str]]: + stage = "" + found: list[tuple[str, str]] = [] + pending = "" + for raw in read_text(str(DOCKERFILE)).splitlines(): + line = raw.strip() + if not pending and (not line or line.startswith("#")): + continue + pending = f"{pending} {line}" if pending else line + if pending.endswith("\\"): + pending = pending[:-1].rstrip() + continue + start = _STAGE.match(pending) + if start: + stage = start.group("name") + else: + found.append((stage, pending)) + pending = "" + return found + + +def stage_runs(stage: str) -> list[str]: + return [ + text + for name, text in _instructions() + if name == stage and text.startswith("RUN ") + ] + + +def materialise(destination: Path, stages: frozenset[str]) -> None: + for stage, text in _instructions(): + match = _COPY.match(text) + if stage not in stages or not match: + continue + source = PROJECT_ROOT / match.group("source") + target = destination / match.group("target") + target.parent.mkdir(parents=True, exist_ok=True) + if source.is_dir(): + shutil.copytree(source, target, dirs_exist_ok=True) + else: + shutil.copy2(source, target) diff --git a/utils/env/handlers/__init__.py b/utils/env/handlers/__init__.py index df51dd1dbf..befbc04ff9 100644 --- a/utils/env/handlers/__init__.py +++ b/utils/env/handlers/__init__.py @@ -26,6 +26,7 @@ from .infinito import ( image_repository, inventory, is_wsl2, + lint_runner, outer_network_mtu, parent_image, pull_policy, @@ -116,6 +117,7 @@ ORDERED_HANDLERS = [ gha_passthrough, pull_policy, build, + lint_runner, docker_embedded_dns, docker_volume, github_repository_owner, diff --git a/utils/env/handlers/infinito/lint_runner.py b/utils/env/handlers/infinito/lint_runner.py new file mode 100644 index 0000000000..6e56eda00f --- /dev/null +++ b/utils/env/handlers/infinito/lint_runner.py @@ -0,0 +1,14 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from utils.env.builder import BuildContext, EnvBuilder + +KEY = "INFINITO_LINT_RUNNER" + + +def apply(eb: EnvBuilder, ctx: BuildContext) -> None: + if not (ctx.on_gha or ctx.on_act): + return + eb.setdefault(KEY, "host", comment=ctx.static_comments.get(KEY, "")) diff --git a/utils/install/lint/README.md b/utils/install/lint/README.md index cfa99d6011..ddaade5726 100644 --- a/utils/install/lint/README.md +++ b/utils/install/lint/README.md @@ -60,3 +60,7 @@ def ensure() -> None: The `all` mode honors a per-interpreter stamp at `build/install-lint-.stamp` (the suffix is the first 8 chars of `sha256(sys.executable)`, so host and container track independently even though `build/` is bind-mounted). Stamp dependencies are [lint.sh](../../../scripts/install/lint.sh) and [pyproject.toml](../../../pyproject.toml). Group-targeted invocations always run and never touch the stamp. + +With `INFINITO_LINT_RUNNER=docker` the `lint-docker` stage of the root [Dockerfile](../../../Dockerfile) runs every `all` group except `javascript` and `playwright`, which install into the bind-mounted tree, so a fresh container finds the toolchain in the image and the `all` run only checks it. +The stage runs the `full` stage's system package step before those groups, so they resolve packages in the order a runtime install does. +[test_main.py](../../../tests/unit/python/utils/install/lint/test_main.py) keeps that group list, that step and the files the stage copies in step with this package.