diff --git a/.github/workflows/README.md b/.github/workflows/README.md index 2525d5bdaf..bce489ac67 100644 --- a/.github/workflows/README.md +++ b/.github/workflows/README.md @@ -167,13 +167,19 @@ own stack, `+tor` on a variant that pins `services.tor.enabled` false, `+multi` on a role with `reachability.single_mode: true`, or any axis that fights the run's own `mode`, `network`, `distros`, `filesystem` or `architectures` input, or `:arm64` on a role whose `meta/services.yml` declares -`architectures: [amd64]`. +`architectures: [amd64]`, or `%centos:arm64` on a row installing a package whose +`meta/packages.yml` centos entry declares `architectures: [amd64]`. Such a +package entry narrows only its own distro and architecture pair: an unpinned +row that draws it moves to another architecture of the same distro, so the +role keeps every other pair. That is also what a retrigger replays: `--failed` reads the glyphs off the failed job's title and writes them back as a token, so the row comes back in the mode, network mode, distribution and architecture it died on rather than on whatever the rotation would pick next. The architecture is replayed because it is the -machine the job ran on, not a preference it could fall back from. The +machine the job ran on, not a preference it could fall back from, unless a +package entry no longer publishes that pair: the replay then keeps the distro, +drops the architecture and warns. The filesystem is deliberately left out. A title states the kind the matrix *assigned*, which a deploy is allowed to fall back from, so pinning it would both misstate what the job ran on and turn the kind into a diff --git a/cli/administration/deploy/ci/selections.py b/cli/administration/deploy/ci/selections.py index d7c43a83c5..783cd6fbe7 100644 --- a/cli/administration/deploy/ci/selections.py +++ b/cli/administration/deploy/ci/selections.py @@ -28,10 +28,14 @@ stopped, instead of aggregating to role ids and guessing the rest. from __future__ import annotations +import sys from typing import TYPE_CHECKING -from utils.github.variant import axes, selection +from cli.meta.ci import matrix +from utils.cache import PROJECT_ROOT +from utils.github.variant import axes, pools, selection from utils.github.variant.vpn import VPN_DEPLOY_MODES +from utils.packages.registry import published_architectures if TYPE_CHECKING: from collections.abc import Iterable, Mapping @@ -73,15 +77,18 @@ def failed_selections(jobs: list[dict], *, strict: bool = False) -> list[str]: if state == "success" or (strict and state != "failure"): continue label = axes.parse_label(str(job.get("name", ""))) + variants = tuple(int(part) for part in label.variant.split(",") if part) tokens.add( selection.describe( selection.Pin( app, - tuple(int(part) for part in label.variant.split(",") if part), + variants, label.mode, label.network, label.distro or None, - architecture=label.architecture or None, + architecture=_replayable_architecture( + app, variants, label.distro, label.architecture + ), vpn=label.vpn if label.mode in VPN_DEPLOY_MODES else None, ) ) @@ -89,6 +96,51 @@ def failed_selections(jobs: list[dict], *, strict: bool = False) -> list[str]: return sorted(tokens) +def _replayable_architecture( + app: str, variants: tuple[int, ...], distro: str, architecture: str +) -> str | None: + """The architecture pin a replay may carry. + + A job the matrix planned before a package narrowed its pair would come + back as a token the pin check refuses, and one refused token aborts the + whole dispatch. The architecture is dropped instead, with a warning, and + the rotation picks one the row's packages are published for. + + Args: + app: role id of the failed job. + variants: the variant shards its title names. + distro: the distro its title names, ``""`` when none. + architecture: the architecture its title names, ``""`` when none. + """ + if not architecture or not distro: + return architecture or None + if not any( + architecture not in narrowed.get(distro, pools.ARCHITECTURES) + for narrowed in published_architectures(PROJECT_ROOT).values() + ): + return architecture + rounds = matrix.deployed_rounds(app) + services = tuple( + dict.fromkeys( + role + for index in variants or (0,) + if index < len(rounds) + for role in rounds[index] + ) + ) + if (distro, architecture) in axes.row_pairs( + app, (distro,), pools.ARCHITECTURES, services + ): + return architecture + print( + f"warning: {app}: replaying the failed {distro}:{architecture} job " + f"without its :{architecture} pin; a package the row installs is not " + f"published for that pair (meta/packages.yml architectures)", + file=sys.stderr, + ) + return None + + def collapse_to_roles(tokens: Iterable[str]) -> list[str]: """The same selections with every axis dropped, one entry per role. diff --git a/cli/meta/ci/validate.py b/cli/meta/ci/validate.py index 1bdbb60715..1c4a8ba51a 100644 --- a/cli/meta/ci/validate.py +++ b/cli/meta/ci/validate.py @@ -149,6 +149,9 @@ def problems( continue deployed = matrix.with_deployed_services(discovered[(pin.app, variant)]) try: + row_architectures = axes.row_architectures( + pin.app, architectures, deployed["services"] + ) axes.check_pins( pin.app, "" if variant is None else str(variant), @@ -164,8 +167,9 @@ def problems( vpn_mode=vpn_mode, distros=distros, filesystems=filesystems, - architectures=axes.row_architectures( - pin.app, architectures, deployed["services"] + architectures=row_architectures, + pairs=axes.row_pairs( + pin.app, distros, row_architectures, deployed["services"] ), ) except SystemExit as refusal: diff --git a/docs/architecture/decisions/0002-ci-architecture-axis.md b/docs/architecture/decisions/0002-ci-architecture-axis.md index 2ab4c8dba9..50a90c2381 100644 --- a/docs/architecture/decisions/0002-ci-architecture-axis.md +++ b/docs/architecture/decisions/0002-ci-architecture-axis.md @@ -61,6 +61,13 @@ machine, not just a value the job applies to itself. role the deploy planner brings up for that variant, because the deploy pulls those in too; an empty intersection aborts the matrix. +- **A package may narrow one distro and architecture pair.** A distro entry in + `meta/packages.yml` may declare `architectures` when its source publishes + nothing elsewhere, such as a Flathub app shipped for x86_64 only. The row + keeps both architectures; a draw of the unpublished pair moves to another + architecture of the same distro, a pin naming it aborts the matrix, and + `package_install` refuses it by name on a host before any module runs. + - **CI images are built natively per architecture and published as one tag per distro.** Each architecture builds on its own runner, and [push.sh](../../../scripts/image/push.sh) pushes the result by digest only, so diff --git a/meta/packages.yml b/meta/packages.yml index 8f265adfe8..6a4d8b89d9 100644 --- a/meta/packages.yml +++ b/meta/packages.yml @@ -37,6 +37,9 @@ blender: - org.blender.Blender flatpak: command: blender + # Flathub publishes org.blender.Blender for x86_64 only, and EL 10 has no other source + architectures: + - amd64 fedora: - blender diff --git a/plugins/action/package_install.py b/plugins/action/package_install.py index 7d8c410076..a1ffbfbe1f 100755 --- a/plugins/action/package_install.py +++ b/plugins/action/package_install.py @@ -56,7 +56,12 @@ from utils.packages.installed import ( state_holds, ) from utils.packages.outcome import aggregate -from utils.packages.plan import build_plan, merge_plans +from utils.packages.plan import ( + HOST_ARCHITECTURE_VAR, + build_plan, + ensure_published, + merge_plans, +) from utils.packages.registry import build_registry, project_root_from_env, resolve from utils.packages.schema import ROLE_FILE_META_PACKAGES, PackagesShapeError @@ -80,12 +85,19 @@ class ActionModule(ActionBase): package_ids = self._package_ids() registry = self._registry() role = self._role() + kernel = read_fact(facts, "architecture") + by_kernel = dict(task_vars.get(HOST_ARCHITECTURE_VAR) or {}) plans: list[list[ModuleCall]] = [] skipped: list[str] = [] for package_id in package_ids: spec = self._spec_for(registry, package_id, distribution, os_family, role) + if state == STATE_PRESENT: + try: + ensure_published(package_id, distribution, kernel, by_kernel, spec) + except ValueError as exc: + raise AnsibleActionFail(str(exc)) from exc plan = self._plan_for(spec, state) if not plan: skipped.append(package_id) @@ -242,7 +254,9 @@ class ActionModule(ActionBase): result = self._execute_module( module_name="ansible.builtin.setup", - module_args={"gather_subset": ["!all", "!min", "distribution", "pkg_mgr"]}, + module_args={ + "gather_subset": ["!all", "!min", "distribution", "pkg_mgr", "platform"] + }, task_vars=task_vars, ) if result.get("failed"): diff --git a/tests/unit/python/cli/administration/deploy/ci/test_selections.py b/tests/unit/python/cli/administration/deploy/ci/test_selections.py index ac76959125..2e6848eaa5 100644 --- a/tests/unit/python/cli/administration/deploy/ci/test_selections.py +++ b/tests/unit/python/cli/administration/deploy/ci/test_selections.py @@ -1,5 +1,7 @@ from __future__ import annotations +import contextlib +import io import unittest from typing import ClassVar @@ -303,3 +305,25 @@ class TestCollapseFailures(unittest.TestCase): selections.collapse_failures(hard, hard), selections.collapse_to_roles(hard), ) + + +class TestFailedSelectionsOnUnpublishedPairs(unittest.TestCase): + """A replayed pin the check refuses would abort the whole dispatch.""" + + def _replay(self, distro: str, architecture: str) -> tuple[selection.Pin, str]: + name = deploy_job_name( + "host", "dsk-blender", "0", distro=distro, architecture=architecture + ) + with contextlib.redirect_stderr(io.StringIO()) as stderr: + (token,) = selections.failed_selections([_job(name, "failure")]) + return selection.parse(token), stderr.getvalue() + + def test_an_unpublished_pair_drops_only_its_architecture_and_warns(self) -> None: + pin, warned = self._replay("centos", "arm64") + self.assertEqual((pin.distro, pin.architecture), ("centos", None)) + self.assertIn("centos:arm64", warned) + + def test_a_published_pair_is_replayed_as_it_ran(self) -> None: + pin, warned = self._replay("debian", "arm64") + self.assertEqual((pin.distro, pin.architecture), ("debian", "arm64")) + self.assertEqual(warned, "") diff --git a/tests/unit/python/plugins/action/test_package_install.py b/tests/unit/python/plugins/action/test_package_install.py index 373dab2db6..5766c71ed4 100644 --- a/tests/unit/python/plugins/action/test_package_install.py +++ b/tests/unit/python/plugins/action/test_package_install.py @@ -7,6 +7,8 @@ from ansible.plugins.action import ActionBase from ansible.plugins.loader import become_loader, shell_loader from plugins.action.package_install import ActionModule +from utils.cache.files import PROJECT_ROOT +from utils.cache.yaml import load_yaml_any from utils.packages.calls import ( GENERIC_PACKAGE, STATE_ABSENT, @@ -16,9 +18,13 @@ from utils.packages.calls import ( package_call, ) from utils.packages.outcome import aggregate +from utils.packages.plan import HOST_ARCHITECTURE_VAR from utils.packages.schema import PackageSpec QUERY = "ansible.builtin.command" +_BY_KERNEL = load_yaml_any(str(PROJECT_ROOT / "group_vars" / "all" / "00_general.yml"))[ + HOST_ARCHITECTURE_VAR +] def _modules(execute) -> list[str]: @@ -262,8 +268,9 @@ class TestRunMergesPlainPlans(unittest.TestCase): "pkg_mgr": "apt", } - def _run(self, package_ids, specs, query=None): + def _run(self, package_ids, specs, query=None, facts=None, by_kernel=None): action = _action({"id": package_ids}) + self.action = action action._task._role = None action._task.delegate_to = None action._connection = mock.Mock(become=None, transport="local") @@ -286,9 +293,47 @@ class TestRunMergesPlainPlans(unittest.TestCase): side_effect=lambda declaration, *_: specs[declaration.package_id], ), ): - result = action.run(task_vars={"ansible_facts": self.FACTS}) + result = action.run( + task_vars={ + "ansible_facts": facts or self.FACTS, + HOST_ARCHITECTURE_VAR: _BY_KERNEL + if by_kernel is None + else by_kernel, + } + ) return action._execute_module, result + def _centos(self, kernel, by_kernel=None): + flathub_only = PackageSpec( + ("org.blender.Blender",), source="flatpak", architectures=("amd64",) + ) + facts = { + "distribution": "CentOS", + "os_family": "RedHat", + "pkg_mgr": "dnf", + "architecture": kernel, + } + with self.assertRaises(AnsibleActionFail) as caught: + self._run( + ["git", "blender"], + {"git": PackageSpec(("git",)), "blender": flathub_only}, + facts=facts, + by_kernel=by_kernel, + ) + self.assertEqual(self.action._execute_module.call_args_list, []) + return str(caught.exception) + + def test_an_unpublished_architecture_fails_before_any_module_runs(self): + self.assertIn( + "'blender' cannot be installed on centos arm64", self._centos("aarch64") + ) + + def test_an_unmapped_kernel_architecture_fails_loud(self): + self.assertIn(HOST_ARCHITECTURE_VAR, self._centos("riscv64")) + + def test_the_kernel_map_comes_from_the_inventory(self): + self.assertIn(HOST_ARCHITECTURE_VAR, self._centos("x86_64", by_kernel={})) + def test_two_repository_ids_cost_one_package_manager_call(self): execute, _result = self._run( ["git", "curl"], diff --git a/tests/unit/python/roles/dsk-blender/__init__.py b/tests/unit/python/roles/dsk-blender/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/roles/dsk-blender/test_architectures.py b/tests/unit/python/roles/dsk-blender/test_architectures.py new file mode 100644 index 0000000000..eddbc7f4ff --- /dev/null +++ b/tests/unit/python/roles/dsk-blender/test_architectures.py @@ -0,0 +1,52 @@ +from __future__ import annotations + +import unittest + +from utils.github.variant.pins import draw_pair, row_architectures, row_pairs +from utils.github.variant.pools import ARCHITECTURES, DISTROS + +ROLE = "dsk-blender" +UNPUBLISHED = ("centos", "arm64") + + +def _drawn() -> set[tuple[str, str]]: + architectures = row_architectures(ROLE, ARCHITECTURES) + pairs = row_pairs(ROLE, DISTROS, architectures) + return { + draw_pair( + pairs, + DISTROS, + architectures, + pin_distro=None, + pin_architecture=None, + index=index, + sweep=sweep, + ) + for index in range(len(DISTROS) * len(ARCHITECTURES)) + for sweep in range(len(ARCHITECTURES)) + } + + +class TestBlenderArchitectures(unittest.TestCase): + def test_the_role_keeps_every_architecture(self) -> None: + self.assertEqual(row_architectures(ROLE, ARCHITECTURES), ARCHITECTURES) + + def test_the_matrix_never_plans_centos_on_arm64(self) -> None: + self.assertNotIn( + UNPUBLISHED, + _drawn(), + "centos installs org.blender.Blender from Flathub, which publishes " + "it for x86_64 only (https://flathub.org/api/v2/summary/" + "org.blender.Blender), so the flatpak task aborts there with " + "'Nothing matches org.blender.Blender in remote flathub'", + ) + + def test_every_other_distro_still_runs_on_arm64(self) -> None: + self.assertEqual( + {distro for distro, architecture in _drawn() if architecture == "arm64"}, + set(DISTROS) - {"centos"}, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/utils/github/variant/test_axes.py b/tests/unit/python/utils/github/variant/test_axes.py index eaf5dbc0db..34b21306ae 100644 --- a/tests/unit/python/utils/github/variant/test_axes.py +++ b/tests/unit/python/utils/github/variant/test_axes.py @@ -2,8 +2,10 @@ from __future__ import annotations import unittest import unittest.mock as mock +from typing import ClassVar from utils.github.variant import axes, network, pins, pools +from utils.packages.schema import PackagesShapeError from utils.roles.display import display_names from utils.roles.mapping import ( ROLE_FILE_META_DOMAINS, @@ -1022,6 +1024,98 @@ class TestArchitectureAxis(unittest.TestCase): ): _assign(rows, sweep=0, network_input="auto", variants_per_app=_VARIANTS) + _CENTOS_AMD64_ONLY: ClassVar[dict] = {"web-app-b": {"centos": frozenset({"amd64"})}} + + def _pairs(self, rows, published, sweeps=range(1)) -> set[tuple[str, str]]: + with mock.patch.object(pins, "published_architectures", return_value=published): + return { + (entry["distro"], entry["architecture"]) + for sweep in sweeps + for entry in _assign( + rows, + sweep=sweep, + network_input="clearnet", + variants_per_app=_VARIANTS, + ) + } + + def test_an_unpublished_pair_is_never_planned_and_every_other_is(self) -> None: + rows = [_row("web-app-b", index, ("compose",)) for index in range(10)] + drawn = self._pairs(rows, self._CENTOS_AMD64_ONLY, sweeps=range(4)) + self.assertNotIn(("centos", "arm64"), drawn) + self.assertEqual( + drawn, + { + (distro, architecture) + for distro in pools.DISTROS + for architecture in pools.ARCHITECTURES + } + - {("centos", "arm64")}, + ) + + def test_a_service_package_narrows_the_row_like_its_own(self) -> None: + rows = [ + {**_row("web-app-c", index, ("compose",)), "services": ["web-app-b"]} + for index in range(10) + ] + self.assertNotIn( + ("centos", "arm64"), + self._pairs(rows, self._CENTOS_AMD64_ONLY, sweeps=range(4)), + ) + + def test_a_published_everywhere_row_draws_what_it_drew_before(self) -> None: + rows = [_row("web-app-b", index, ("compose",)) for index in range(10)] + entries = _assign( + rows, sweep=3, network_input="clearnet", variants_per_app=_VARIANTS + ) + self.assertEqual( + [(entry["distro"], entry["architecture"]) for entry in entries], + [ + ( + pools.rotate(pools.DISTROS, index, 3), + pools.rotate(pools.ARCHITECTURES, index, 3), + ) + for index in range(10) + ], + ) + + def test_a_pinned_distro_keeps_the_architecture_it_is_published_for(self) -> None: + rows = [ + _row("web-app-b", index, ("compose",), pin_distro="centos") + for index in range(4) + ] + self.assertEqual( + self._pairs(rows, self._CENTOS_AMD64_ONLY), {("centos", "amd64")} + ) + + def test_a_pinned_unpublished_pair_aborts_the_matrix(self) -> None: + rows = [ + _row( + "web-app-b", + 0, + ("compose",), + pin_distro="centos", + pin_architecture="arm64", + ) + ] + with self.assertRaises(SystemExit) as caught: + self._pairs(rows, self._CENTOS_AMD64_ONLY) + self.assertIn("not published", str(caught.exception)) + + def test_an_unparsable_registry_refuses_in_one_line(self) -> None: + with ( + mock.patch.object( + pins, + "published_architectures", + side_effect=PackagesShapeError("meta/packages.yml: app.centos bad"), + ), + self.assertRaises(SystemExit) as caught, + ): + pins.row_pairs("web-app-b", pools.DISTROS, pools.ARCHITECTURES) + self.assertEqual( + str(caught.exception), "web-app-b: meta/packages.yml: app.centos bad" + ) + def test_the_architecture_survives_the_label_round_trip(self) -> None: entry = _assign( [_row("web-app-a", 0, ("swarm",))], diff --git a/tests/unit/python/utils/packages/test_plan.py b/tests/unit/python/utils/packages/test_plan.py index b3752bfb3d..2b5ecd01be 100644 --- a/tests/unit/python/utils/packages/test_plan.py +++ b/tests/unit/python/utils/packages/test_plan.py @@ -1,9 +1,15 @@ import re import unittest +from typing import ClassVar from utils.packages.calls import STATE_ABSENT, STATE_PRESENT from utils.packages.installed import deb_pin_argv -from utils.packages.plan import build_plan, merge_plans +from utils.packages.plan import ( + HOST_ARCHITECTURE_VAR, + build_plan, + ensure_published, + merge_plans, +) from utils.packages.schema import ( SOURCE_AUR, SOURCE_BUILD, @@ -385,6 +391,43 @@ class TestFlatpakSource(unittest.TestCase): ) +class TestEnsurePublished(unittest.TestCase): + """A host the source publishes nothing for is refused by name, before the + remote answers with an anonymous ``Nothing matches``.""" + + SPEC = PackageSpec( + ("org.blender.Blender",), source=SOURCE_FLATPAK, architectures=("amd64",) + ) + BY_KERNEL: ClassVar[dict[str, str]] = {"x86_64": "amd64", "aarch64": "arm64"} + + def _ensure(self, kernel, spec=SPEC, distribution="centos"): + ensure_published("blender", distribution, kernel, self.BY_KERNEL, spec) + + def test_an_unpublished_architecture_names_package_distro_and_arch(self): + with self.assertRaises(ValueError) as caught: + self._ensure("aarch64") + for word in ("blender", "centos", "arm64", "org.blender.Blender", "amd64"): + with self.subTest(word=word): + self.assertIn(word, str(caught.exception)) + + def test_a_published_architecture_passes(self): + self._ensure("x86_64") + + def test_an_unmapped_kernel_architecture_fails_loud(self): + for kernel in ("riscv64", ""): + with ( + self.subTest(kernel=kernel), + self.assertRaises(ValueError) as caught, + ): + self._ensure(kernel) + self.assertIn(HOST_ARCHITECTURE_VAR, str(caught.exception)) + + def test_an_entry_without_architectures_passes_everywhere(self): + for kernel in ("aarch64", "riscv64"): + with self.subTest(kernel=kernel): + self._ensure(kernel, PackageSpec(("blender",)), "fedora") + + def _plan(*names, **spec): return build_plan(PackageSpec(tuple(names), **spec), STATE_PRESENT) diff --git a/tests/unit/python/utils/packages/test_registry.py b/tests/unit/python/utils/packages/test_registry.py index f649296aa7..7ecb27b51d 100644 --- a/tests/unit/python/utils/packages/test_registry.py +++ b/tests/unit/python/utils/packages/test_registry.py @@ -3,11 +3,13 @@ import unittest from pathlib import Path from utils.cache.yaml import dump_yaml +from utils.github.variant.pools import ARCHITECTURES from utils.packages.registry import ( build_registry, iter_inventory_package_lists, load_declarations, load_references, + published_architectures, resolve, ) from utils.packages.schema import ( @@ -255,6 +257,72 @@ class TestRegistry(unittest.TestCase): self.assertEqual(spec.source, "download") self.assertEqual(spec.download["url"], "https://vendor.example/editor.deb") + def _architectures(self, value): + entry = {"names": ["org.example.App"], "source": "flatpak"} + if value is not None: + entry["architectures"] = value + _write_role(self.root, "role-a", {"app": {"centos": entry}}) + return resolve(self._declaration("app"), "centos").architectures + + def test_an_entry_without_architectures_takes_every_one(self): + self.assertEqual(self._architectures(None), ARCHITECTURES) + + def test_an_entry_narrows_to_its_declared_architectures(self): + self.assertEqual(self._architectures(["amd64"]), ("amd64",)) + + def test_an_unknown_entry_key_is_refused(self): + _write_role( + self.root, + "role-a", + {"app": {"centos": {"names": ["app"], "architecture": ["amd64"]}}}, + ) + with self.assertRaises(PackagesShapeError) as ctx: + resolve(self._declaration("app"), "centos") + self.assertIn("architecture", str(ctx.exception)) + + def test_an_entry_key_beside_the_distro_keys_is_refused(self): + _write_role( + self.root, + "role-a", + {"app": {"centos": ["app"], "architectures": ["amd64"]}}, + ) + with self.assertRaises(PackagesShapeError) as ctx: + build_registry(self.root) + self.assertIn("architectures", str(ctx.exception)) + + def test_architectures_reject_what_no_host_can_match(self): + for value in ("amd64", [], ["x86_64"]): + with ( + self.subTest(value=value), + self.assertRaises(PackagesShapeError) as ctx, + ): + self._architectures(value) + self.assertIn("architectures", str(ctx.exception)) + + def test_published_architectures_lists_only_the_narrowed_pairs(self): + _write_shared( + self.root, + { + "app": { + "Debian": ["app"], + "Archlinux": ["app"], + "RedHat": ["app"], + "centos": { + "names": ["org.example.App"], + "source": "flatpak", + "architectures": ["amd64"], + }, + }, + "lib": {"Debian": ["lib"], "Archlinux": ["lib"], "RedHat": ["lib"]}, + }, + ) + _write_role(self.root, "role-a", {"app": {"shared": True}}) + _write_role(self.root, "role-b", {"lib": {"shared": True}}) + self.assertEqual( + published_architectures(self.root), + {"role-a": {"centos": frozenset({"amd64"})}}, + ) + def test_unknown_distro_raises_without_family(self): _write_role(self.root, "role-a", {"git": {"Debian": ["git"]}}) with self.assertRaises(PackagesShapeError): diff --git a/utils/github/variant/axes.py b/utils/github/variant/axes.py index 65b0eef251..ca8b905490 100644 --- a/utils/github/variant/axes.py +++ b/utils/github/variant/axes.py @@ -67,7 +67,13 @@ from utils.github.variant.network import ( row_pulls_tor, row_states, ) -from utils.github.variant.pins import check_pins, priority_picks, row_architectures +from utils.github.variant.pins import ( + check_pins, + draw_pair, + priority_picks, + row_architectures, + row_pairs, +) from utils.github.variant.pools import ( ARCHITECTURES, DISTROS, @@ -99,6 +105,7 @@ __all__ = [ "priority_picks", "resolve_sweep", "row_architectures", + "row_pairs", "sort_key", ] @@ -225,6 +232,7 @@ def assign( offered_architectures = row_architectures( app, architectures, row.get("services", ()) ) + pairs = row_pairs(app, distros, offered_architectures, row.get("services", ())) check_pins( app, variant_csv, @@ -241,6 +249,7 @@ def assign( distros=distros, filesystems=filesystems, architectures=offered_architectures, + pairs=pairs, ) if priority: picked = priority_picks( @@ -284,13 +293,18 @@ def assign( ] label = codec.encode(app, variant_csv) for step, (mode, state, meshed) in enumerate(picked): - distro = pin_distro or rotate(distros, position + step, sweep) + distro, architecture = draw_pair( + pairs, + distros, + offered_architectures, + pin_distro=pin_distro, + pin_architecture=pin_architecture, + index=position + step, + sweep=sweep, + ) filesystem = pin_filesystem or rotate( filesystems, (position + step) // len(distros), sweep ) - architecture = pin_architecture or rotate( - offered_architectures, position + step, sweep - ) glyphs = ( to_emoji(mode) + (to_emoji(state) if mode in NETWORK_DEPLOY_MODES else LOCAL_GLYPH) diff --git a/utils/github/variant/pins.py b/utils/github/variant/pins.py index 45a6e69db0..8554efad68 100644 --- a/utils/github/variant/pins.py +++ b/utils/github/variant/pins.py @@ -9,16 +9,25 @@ from __future__ import annotations from typing import TYPE_CHECKING +from utils.cache import PROJECT_ROOT from utils.github.variant.network import combinations, network_states -from utils.github.variant.pools import ARCHITECTURES +from utils.github.variant.pools import ARCHITECTURES, rotate from utils.github.variant.vpn import VPN_DEPLOY_MODES, pinned_vpn_states +from utils.packages.registry import published_architectures +from utils.packages.schema import PackagesShapeError from utils.roles.display import VARIANT_SEPARATOR from utils.roles.meta_lookup import get_role_architectures if TYPE_CHECKING: from collections.abc import Sequence -__all__ = ["check_pins", "priority_picks", "row_architectures"] +__all__ = [ + "check_pins", + "draw_pair", + "priority_picks", + "row_architectures", + "row_pairs", +] def _reject(app: str, variant: str, reason: str) -> None: @@ -50,6 +59,7 @@ def check_pins( distros: Sequence[str], filesystems: Sequence[str], architectures: Sequence[str] = ARCHITECTURES, + pairs: Sequence[tuple[str, str]] | None = None, ) -> None: """Prove the row can take what the selection token pinned on it. @@ -57,7 +67,8 @@ def check_pins( network modes by its ``--network`` input, the mesh states by its ``--vpn`` input and the two pools by ``--distros`` and ``--filesystem``, so this catches a pin that fights the role, the variant, or the run's own axes with - one check each. + one check each. ``pairs`` (:func:`row_pairs`) adds the distro and + architecture combinations the row's packages are published for. """ if pin_mode is not None and pin_mode not in offered: _reject( @@ -78,6 +89,15 @@ def check_pins( f"pinned {axis} {value!r} is outside this run's {axis} pool " f"({', '.join(pool) or 'empty'})", ) + if pairs is not None and not _pinned_pairs(pairs, pin_distro, pin_architecture): + _reject( + app, + variant, + f"pinned {pin_distro or 'any distro'} on " + f"{pin_architecture or 'any architecture'} is impossible here: a " + f"package the row installs is not published there " + f"(meta/packages.yml architectures)", + ) modes = (pin_mode,) if pin_mode else offered if pin_network is not None and not any( pin_network in network_states(mode, states=states, network_input=network_input) @@ -172,3 +192,103 @@ def row_architectures( f"pool or the declarations." ) return allowed + + +def _pinned_pairs( + pairs: Sequence[tuple[str, str]], + pin_distro: str | None, + pin_architecture: str | None, +) -> list[tuple[str, str]]: + return [ + (distro, architecture) + for distro, architecture in pairs + if pin_distro in (None, distro) and pin_architecture in (None, architecture) + ] + + +def row_pairs( + app: str, + distros: Sequence[str], + architectures: Sequence[str], + services: Sequence[str] = (), +) -> tuple[tuple[str, str], ...]: + """The distro and architecture pairs one row may deploy on this run. + + Args: + app: role id, read for the packages its ``meta/packages.yml`` installs. + distros: the run's distro pool. + architectures: what :func:`row_architectures` left the row. + services: the roles the row's variant deploys, whose packages the + deploy installs too. + + Raises: + SystemExit: no pair is left, which dropping the row instead would + report as a green run for a role that never deployed; or the + registry does not parse, which planning must refuse in one line + rather than a traceback. + """ + try: + published = published_architectures(PROJECT_ROOT) + except PackagesShapeError as exc: + raise SystemExit(f"{app}: {exc}") from exc + pairs = tuple( + (distro, architecture) + for distro in distros + for architecture in architectures + if all( + architecture in published.get(role, {}).get(distro, ARCHITECTURES) + for role in (app, *services) + ) + ) + if not pairs: + raise SystemExit( + f"{app}: meta/packages.yml publishes no package of the row for any " + f"of {', '.join(distros) or 'no distro'} on " + f"{', '.join(architectures) or 'no architecture'}. Widen the run's " + f"distro or architecture pool." + ) + return pairs + + +def draw_pair( + pairs: Sequence[tuple[str, str]], + distros: Sequence[str], + architectures: Sequence[str], + *, + pin_distro: str | None, + pin_architecture: str | None, + index: int, + sweep: int, +) -> tuple[str, str]: + """The distro and architecture one deploy of a row takes. + + Both rotate independently. Only an unpublished draw moves: first to + another architecture of the same distro, so the distro walk keeps its + coprime coverage, then to another distro of the same architecture when + the architecture is pinned. + + Args: + pairs: :func:`row_pairs` of the row, already proven by + :func:`check_pins` to hold a pair the pins allow. + distros: the run's distro pool, in rotation order. + architectures: the row's architectures, in rotation order. + pin_distro: the token's pinned distro, ``None`` for any. + pin_architecture: the token's pinned architecture, ``None`` for any. + index: the deploy's rotation index. + sweep: the sweep number. + """ + allowed = _pinned_pairs(pairs, pin_distro, pin_architecture) + distro = pin_distro or rotate(distros, index, sweep) + architecture = pin_architecture or rotate(architectures, index, sweep) + if (distro, architecture) in allowed: + return distro, architecture + same_distro = [pair for pair in allowed if pair[0] == distro] + same_architecture = [pair for pair in allowed if pair[1] == architecture] + for candidates in ( + [] if pin_architecture else same_distro, + [] if pin_distro else same_architecture, + allowed, + ): + if candidates: + return candidates[(index + sweep) % len(candidates)] + raise AssertionError("check_pins proved a pair the pins allow") diff --git a/utils/packages/plan.py b/utils/packages/plan.py index bc397ca129..711c03007b 100644 --- a/utils/packages/plan.py +++ b/utils/packages/plan.py @@ -10,7 +10,9 @@ plugin only executes what it is handed. from __future__ import annotations from dataclasses import replace +from typing import TYPE_CHECKING +from utils.github.variant.pools import ARCHITECTURES from utils.packages.calls import ( GENERIC_PACKAGE, STATE_ABSENT, @@ -35,6 +37,54 @@ from utils.packages.sources import ( repository_calls, ) +if TYPE_CHECKING: + from collections.abc import Mapping + +HOST_ARCHITECTURE_VAR = "HOST_ARCHITECTURE_BY_KERNEL" +"""The group_vars map from kernel machine names to architecture tokens.""" + + +def ensure_published( + package_id: str, + distribution: str, + kernel: str, + by_kernel: Mapping[str, str], + spec: PackageSpec, +) -> None: + """Refuse a package whose source publishes nothing for the host. + + Args: + package_id: the logical id, named in the refusal. + distribution: the host's distribution, named in the refusal. + kernel: the host's ``ansible_facts.architecture``, ``""`` when absent. + by_kernel: :data:`HOST_ARCHITECTURE_VAR`, read from the inventory. + spec: the entry resolved for that distribution. + + Raises: + ValueError: the entry narrows its architectures and the host's is + either not among them or cannot be mapped to judge it. + """ + if set(ARCHITECTURES) <= set(spec.architectures): + return + architecture = by_kernel.get(kernel) + if architecture is None: + raise ValueError( + f"Package '{package_id}' is published for " + f"{', '.join(spec.architectures)} only on {distribution}, and " + f"{HOST_ARCHITECTURE_VAR} ({dict(by_kernel)}) maps no architecture " + f"for this host's kernel architecture {kernel or '(fact missing)'!r}." + ) + if architecture in spec.architectures: + return + raise ValueError( + f"Package '{package_id}' cannot be installed on {distribution} " + f"{architecture}: its {spec.source} source " + f"({', '.join(spec.names)}) is published for " + f"{', '.join(spec.architectures)} only. Deploy it on " + f"{' or '.join(spec.architectures)}, or on a distribution whose " + f"entry ships it for {architecture}." + ) + def build_plan(spec: PackageSpec, state: str) -> list[ModuleCall]: """Return the ordered module calls that bring ``spec`` into ``state``.""" diff --git a/utils/packages/registry.py b/utils/packages/registry.py index 10098914fd..78cf0ccdf6 100644 --- a/utils/packages/registry.py +++ b/utils/packages/registry.py @@ -14,6 +14,7 @@ for a target distribution. The declaration shape itself lives in from __future__ import annotations +import functools import os from dataclasses import dataclass, field from pathlib import Path @@ -24,9 +25,11 @@ if TYPE_CHECKING: from utils.cache import PROJECT_ROOT from utils.cache.yaml import load_yaml_any +from utils.github.variant.pools import ARCHITECTURES from utils.packages.schema import ( BATCH_KEY, DISTRO_FAMILY, + ENTRY_KEYS, INVENTORY_PACKAGES_VAR, ROLE_FILE_META_PACKAGES, SHARED_REFERENCE, @@ -116,6 +119,13 @@ def load_declarations(project_root: Path) -> list[Declaration]: raise PackagesShapeError( f"{path}: {package_id}.{BATCH_KEY} must be a boolean when set." ) + misplaced = sorted(mapping.keys() & ENTRY_KEYS) + if misplaced: + raise PackagesShapeError( + f"{path}: {package_id} carries {misplaced} beside its distro " + f"keys, where no distro resolves them; move them into the " + f"distro entry they belong to." + ) declarations.append(Declaration(package_id, role, path, mapping)) return declarations @@ -202,6 +212,39 @@ def build_registry(project_root: Path) -> dict[str, Declaration]: return registry +@functools.cache +def published_architectures(project_root: Path) -> dict[str, dict[str, frozenset[str]]]: + """Per role, per default distro, the architectures every package the role + declares or references is published for. + + Args: + project_root: repository root holding the package registry. + + Returns: + only the narrowed pairs; a role or distro that is absent takes every + architecture. + """ + registry = build_registry(project_root) + installs: dict[str, set[str]] = {} + for package_id, declaration in registry.items(): + if declaration.role is not None: + installs.setdefault(declaration.role, set()).add(package_id) + for role, package_ids in load_references(project_root).items(): + installs.setdefault(role, set()).update(package_ids & registry.keys()) + narrowed: dict[str, dict[str, frozenset[str]]] = {} + for role, package_ids in installs.items(): + for package_id in sorted(package_ids): + for distro in DISTRO_FAMILY: + spec = resolve(registry[package_id], distro) + if spec is None or not set(ARCHITECTURES) - set(spec.architectures): + continue + per_distro = narrowed.setdefault(role, {}) + per_distro[distro] = per_distro.get( + distro, frozenset(ARCHITECTURES) + ) & frozenset(spec.architectures) + return narrowed + + def project_root_from_env() -> Path: """Repository root, overridable for tests via ``INFINITO_PROJECT_ROOT``.""" key = "INFINITO_PROJECT_ROOT" # nocheck: test-only override, never set by a deploy diff --git a/utils/packages/schema.py b/utils/packages/schema.py index 31c921f3b1..c1ef7a673e 100644 --- a/utils/packages/schema.py +++ b/utils/packages/schema.py @@ -48,6 +48,20 @@ pulls them from a Flatpak remote:: named after the application id, not after the binary inside it, so without this key a role calling ``blender`` finds nothing on PATH. +``architectures`` narrows one distro entry to the CPU architectures its +source publishes, drawn from +:data:`utils.github.variant.pools.ARCHITECTURES`; absent means every one:: + + blender: + centos: + source: flatpak + names: [org.blender.Blender] + architectures: [amd64] + +The deploy matrix keeps a role installing it off that distro and +architecture pair, and ``package_install`` refuses it there before any +module runs. + ``source: download`` fetches one vendor artefact and installs it locally, for a vendor that publishes a ``.deb`` or ``.rpm`` but runs no repository:: @@ -99,6 +113,7 @@ from dataclasses import dataclass from typing import TYPE_CHECKING, Any from utils.distros import distro_family +from utils.github.variant.pools import ARCHITECTURES if TYPE_CHECKING: from pathlib import Path @@ -155,6 +170,22 @@ REPO_KEYS: frozenset[str] = frozenset( """A repository definition must declare at least one of these; the rest (``name``, ``description``, ``gpgkey``, ``gpgcheck``, ``state``) qualify it.""" +ENTRY_KEYS: frozenset[str] = frozenset( + { + "names", + "source", + "repo", + "virtual", + "build", + "download", + "flatpak", + "architectures", + } +) +"""Every key a distro entry may carry. Anything else is refused rather than +ignored: a misspelt ``architecture`` would otherwise drop the narrowing and +install where the source publishes nothing.""" + DISTRO_FAMILY: dict[str, str] = distro_family() """The default distro matrix mapped onto the ``os_family`` ansible reports for it, read from the ``meta/distros.yml`` SPOT. Coverage is required for @@ -176,6 +207,23 @@ class PackageSpec: build: dict[str, Any] | None = None flatpak: dict[str, Any] | None = None download: dict[str, Any] | None = None + architectures: tuple[str, ...] = ARCHITECTURES + + +def _validate_architectures( + package_id: str, key: str, architectures: Any, path: Path +) -> None: + if ( + not isinstance(architectures, list) + or not architectures + or any(value not in ARCHITECTURES for value in architectures) + ): + raise PackagesShapeError( + f"{path}: {package_id}.{key}.architectures must be a non-empty " + f"list drawn from {ARCHITECTURES}, got {architectures!r}. An " + f"unknown token would match no host and refuse the package " + f"everywhere." + ) def _validate_repo(package_id: str, key: str, repo: Any, path: Path) -> None: @@ -270,6 +318,12 @@ def normalize_entry(package_id: str, key: str, value: Any, path: Path) -> Packag f"{path}: {package_id}.{key} must be a list of names or a mapping, " f"got {type(value).__name__}." ) + unknown = sorted(set(value) - ENTRY_KEYS) + if unknown: + raise PackagesShapeError( + f"{path}: {package_id}.{key} has unknown key(s) {unknown}; an entry " + f"may carry {sorted(ENTRY_KEYS)}." + ) names = value.get("names") if not isinstance(names, list) or any(not isinstance(n, str) for n in names): @@ -302,6 +356,16 @@ def normalize_entry(package_id: str, key: str, value: Any, path: Path) -> Packag flatpak = value.get("flatpak") _validate_flatpak(package_id, key, source, flatpak, path) + architectures = value.get("architectures", list(ARCHITECTURES)) + _validate_architectures(package_id, key, architectures, path) + return PackageSpec( - tuple(names), str(source), repo, virtual, build, flatpak, download + tuple(names), + str(source), + repo, + virtual, + build, + flatpak, + download, + tuple(architectures), )