diff --git a/cli/meta/roles/applications/resolution/affected/__main__.py b/cli/meta/roles/applications/resolution/affected/__main__.py index 55feeac633..aef7de7134 100755 --- a/cli/meta/roles/applications/resolution/affected/__main__.py +++ b/cli/meta/roles/applications/resolution/affected/__main__.py @@ -2,27 +2,27 @@ """ Resolve the set of roles affected by a change to a given set of seed roles. -A role R is "affected" by seed S iff S appears in R's transitive prerequisite -closure (run_after + dependencies + services), as defined by -:class:`cli.meta.roles.applications.resolution.combined.resolver.CombinedResolver`. - Usage: python -m cli.meta.roles.applications.resolution.affected --changed-roles ROLE [ROLE ...] Output: Whitespace-separated, sorted list of selection tokens (single line), - including the seed roles themselves. A role whose variants do not all - reach a seed is narrowed to the ones that do (``role#0,2``, - :mod:`utils.github.variant.selection`): a variant that switches its - provider off does not inherit the seed's change, so deploying it verifies - nothing. The narrowing is transitive over the whole chain, because each - round's closure is walked on that round's variant-merged services maps. + including the seed roles themselves and every role that runs one of them + through an ungated ``include_role``/``import_role``, transitively, each + with all its variants. Every other role is kept only with + the variants whose round really deploys a seed (``role#0,2``, + :mod:`utils.github.variant.selection`), and dropped when none does: a + variant that switches its provider off, or reaches the seed only over a + ``run_after`` ordering hint, does not inherit the seed's change, so + deploying it verifies nothing. The narrowing is transitive over the whole + chain, because each round's closure is walked on that round's + variant-merged services maps. Exit codes: 0 Success. The closure was computed and printed. 1 Resolver error or unknown seed. 2 At least one seed role is non-modellable in the resolver - (no application_id and not referenced by any role's run_after). + (no application_id, so no round closure can contain it). Callers MUST treat this as "fall back to a full deploy" because the resolver cannot guarantee that downstream consumers are enumerated for that seed. @@ -32,23 +32,33 @@ from __future__ import annotations import argparse import sys +from collections.abc import Mapping from typing import TYPE_CHECKING from cli.meta.roles.applications.resolution.combined.errors import ( CombinedResolutionError, ) -from cli.meta.roles.applications.resolution.combined.repo_paths import roles_dir +from cli.meta.roles.applications.resolution.combined.repo_paths import ( + role_config_path, + roles_dir, +) from cli.meta.roles.applications.resolution.combined.resolver import CombinedResolver from cli.meta.roles.applications.resolution.combined.role_introspection import ( has_application_id, - load_run_after, ) +from cli.meta.roles.applications.resolution.combined.yaml_utils import load_yaml_file from utils.cache.applications import get_variants +from utils.roles.applications.services.registry import ( + build_service_registry_from_roles_dir, + is_explicit_truth, +) +from utils.roles.applications.topics import provider_of from utils.roles.applications.variants import resolve_round from utils.roles.display import VARIANT_SEPARATOR +from utils.roles.invocations import role_includes if TYPE_CHECKING: - from collections.abc import Iterable, Mapping + from collections.abc import Iterable from pathlib import Path EXIT_NON_MODELLABLE_SEED = 2 @@ -61,40 +71,130 @@ def _list_role_names() -> list[str]: return sorted(p.name for p in rdir.iterdir() if p.is_dir()) -def _non_modellable_seeds(seeds: set[str], all_roles: list[str]) -> list[str]: - """Return seeds that the resolver cannot reach as a downstream prereq. +def _non_modellable_seeds(seeds: set[str]) -> list[str]: + """ + Args: + seeds: the changed roles. - A seed is reachable iff at least one of: - * it has ``application_id`` (then app-deps and shared-service edges - from any consumer can include it), or - * some role lists it in its ``run_after`` (then a run_after edge - from that consumer includes it). + Returns: + Every seed without ``application_id``, sorted. A round pulls a role + in only over app-only ``dependencies`` and ``services`` edges, never + over ``run_after``, so the resolver cannot enumerate who deploys + such a seed and the caller MUST fall back to a full deploy. + """ + return sorted(role for role in seeds if not has_application_id(role)) - Any other seed (e.g. a non-app helper role only pulled in via - ``include_role`` from tasks) is invisible to the resolver. Returning - a partial closure for such a seed silently shrinks the deploy - matrix. Callers MUST fall back to a full deploy in that case. + +def _switched_on(blocks: list[Mapping]) -> dict[str, dict]: + """ + Args: + blocks: services maps of one role. + + Returns: + ``{key: enabled and shared}`` for each key some block marks + ``enabled`` and some block marks ``shared`` with an explicit truth, + which every deep merge of those blocks needs before it pulls the + key's provider in. """ - if not seeds: - return [] + def flagged(flag: str) -> set[str]: + return { + str(key) + for block in blocks + for key, entry in block.items() + if isinstance(entry, Mapping) and is_explicit_truth(entry.get(flag)) + } - run_after_index: set[str] = set() - for role in all_roles: - try: - for target in load_run_after(role): - run_after_index.add(target) - except CombinedResolutionError: - continue + return { + key: {"enabled": True, "shared": True} + for key in flagged("enabled") & flagged("shared") + } - out: list[str] = [] - for seed in sorted(seeds): - if has_application_id(seed): - continue - if seed in run_after_index: - continue - out.append(seed) - return out + +def _own_blocks(name: str, variants: Mapping[str, list]) -> list[Mapping]: + """ + Args: + name: a role. + variants: parsed variants per role. + + Returns: + The role's ``meta/services.yml`` and each of its variants' + ``services`` blocks, the mappings among them. + """ + path = role_config_path(name) + blocks = [ + load_yaml_file(path) if path.exists() else {}, + *( + payload.get("services") + for payload in variants.get(name) or () + if isinstance(payload, Mapping) + ), + ] + return [block for block in blocks if isinstance(block, Mapping)] + + +def _nested_demands( + sources: Mapping[str, list[Mapping]], registry: Mapping +) -> list[tuple[str, Mapping]]: + """ + Args: + sources: services blocks per role. + registry: the service registry of the roles tree. + + Returns: + ``(provider, demand)`` for every nested ``services`` map a block + places on one of its keys, with the provider of that key. + """ + return [ + (provider_of(str(key), registry), entry["services"]) + for blocks in sources.values() + for block in blocks + for key, entry in block.items() + if isinstance(entry, Mapping) and isinstance(entry.get("services"), Mapping) + ] + + +def _union_services( + names: list[str], variants: Mapping[str, list] +) -> dict[str, dict[str, dict]]: + """ + Args: + names: every role. + variants: parsed variants per role. + + Returns: + ``{role: services map}`` built by :func:`_switched_on` from the + role's ``meta/services.yml``, each variant's ``services`` block, and + every nested ``services`` demand another role's block makes of it, + the three sources a round deep-merges its map from. + """ + sources = {name: _own_blocks(name, variants) for name in names} + registry = build_service_registry_from_roles_dir(roles_dir()) + for provider, demand in _nested_demands(sources, registry): + if provider in sources: + sources[provider].append(demand) + return {name: _switched_on(blocks) for name, blocks in sources.items()} + + +def _with_includers(seeds: set[str], names: list[str]) -> set[str]: + """ + Args: + seeds: the changed roles. + names: every role. + + Returns: + *seeds* plus every role that includes one of them, transitively, per + :func:`utils.roles.invocations.role_includes`. + """ + path = str(roles_dir()) + found = set(seeds) + frontier = set(seeds) + while frontier: + frontier = { + name for name in names if frontier & role_includes(path, name) + } - found + found |= frontier + return found def affected_roles(changed: Iterable[str]) -> list[str]: @@ -109,7 +209,7 @@ def affected_roles(changed: Iterable[str]) -> list[str]: f"Unknown role(s) passed via --changed-roles: {sorted(unknown)}" ) - non_modellable = _non_modellable_seeds(seeds, all_roles) + non_modellable = _non_modellable_seeds(seeds) if non_modellable: print( "non-modellable seed(s) for resolver: " @@ -118,17 +218,22 @@ def affected_roles(changed: Iterable[str]) -> list[str]: ) raise SystemExit(EXIT_NON_MODELLABLE_SEED) - resolver = CombinedResolver() - affected: set[str] = set(seeds) - - for role in all_roles: - if role in affected: - continue - prereqs = resolver.resolve(role) - if any(p in seeds for p in prereqs): - affected.add(role) - - return sorted(affected) + resolver = CombinedResolver( + services_overrides=_union_services( + all_roles, get_variants(roles_dir=str(roles_dir()), readonly=True) + ), + follow_run_after=False, + ) + changed_roles = _with_includers(seeds, all_roles) + return sorted( + changed_roles + | { + role + for role in all_roles + if role not in changed_roles + and changed_roles.intersection(resolver.resolve(role)) + } + ) def _round_resolver( @@ -167,14 +272,19 @@ def _pinned( count: int, roles_path: Path, variants: Mapping[str, list], -) -> str: - """*role*, narrowed to the variants whose own closure reaches a seed. +) -> str | None: + """ + Args: + role: an affected role that is not a seed. + seeds: the changed roles. + count: the variants *role* runs in, at least one. + roles_path: the roles tree. + variants: parsed variants per role. - Returns the bare role id whenever the narrowing cannot be trusted: no - variant reaching a seed means the role is affected through an edge the - round closure does not model (a ``run_after`` hint, or a resolution the - variant merge refused), and verifying none of it is worse than verifying - all of it. + Returns: + ``None`` when no round deploys a seed; the bare role id when every + round does, or when a round's resolution fails, because the + narrowing cannot be trusted then; else the ``role#i,j`` token. """ try: hits = [ @@ -186,36 +296,50 @@ def _pinned( ] except CombinedResolutionError: return role - if not hits or len(hits) == count: + if not hits: + return None + if len(hits) == count: return role return role + VARIANT_SEPARATOR + ",".join(str(index) for index in hits) def affected_selection(changed: Iterable[str]) -> list[str]: - """:func:`affected_roles` as selection tokens, variant-narrowed. + """ + Args: + changed: the changed roles. - A seed role keeps every variant: its own files changed, so each of them - has to redeploy regardless of which providers it pulls. + Returns: + Every seed and every role that includes one, transitively, with all + its variants, and every other + affected role with only the variants whose round deploys one of + them; a role none of whose rounds does is left out. """ seeds: set[str] = {r.strip() for r in changed if r and r.strip()} affected = affected_roles(changed) + changed_roles = _with_includers(seeds, _list_role_names()) variants = get_variants(roles_dir=str(roles_dir()), readonly=True) - counts = {role: len(variants.get(role) or ()) for role in affected} - return [ + tokens = ( role - if role in seeds or counts[role] < 2 - else _pinned(role, seeds, counts[role], roles_dir(), variants) + if role in changed_roles + else _pinned( + role, + changed_roles, + max(1, len(variants.get(role) or ())), + roles_dir(), + variants, + ) for role in affected - ] + ) + return [token for token in tokens if token] def main() -> None: parser = argparse.ArgumentParser( description=( - "Print all roles whose transitive prerequisite closure " - "(run_after + dependencies + services) contains any of the " - "given seed roles, each narrowed to the variants that reach one. " - "Seed roles themselves are included, with every variant." + "Print every role with a variant whose round deploys one of the " + "given seed roles, or a role including one, over dependencies or " + "services, narrowed to those variants. Seed roles and the roles " + "including them are printed with every variant." ) ) parser.add_argument( diff --git a/docs/contributing/artefact/git/pipeline.md b/docs/contributing/artefact/git/pipeline.md index b1f7633b57..1a308c245a 100644 --- a/docs/contributing/artefact/git/pipeline.md +++ b/docs/contributing/artefact/git/pipeline.md @@ -79,11 +79,12 @@ The two deploy-test workflows listed in the `Infrastructure tests` table of [wor 3. **Diff vs `origin/main`**, applied only when the `whitelist` input is empty: - **Skipped paths:** `.md` and `.rst` files and everything under `tests/` outside `roles//...` neither seed a role nor widen the deploy. - **No diff at all**, OR **any other changed path outside `roles//...`**, OR **only skipped paths**: no whitelist is set, so the full deploy across the workflow's scope runs. - - **All remaining changed paths under `roles//...`**: the changed roles become the seed set, and the whitelist is the transitive closure of those seeds expanded upwards over `run_after`, `dependencies`, and shared services. In other words, every role whose prerequisite set as defined by [combined resolver](../../../../cli/meta/roles/applications/resolution/combined/resolver.py) contains one of the seeds is included, together with the seeds themselves. + - **All remaining changed paths under `roles//...`**: the changed roles become the seed set, and the candidates are the transitive closure of those seeds expanded upwards over `dependencies` and shared services. In other words, every role whose prerequisite set as defined by [combined resolver](../../../../cli/meta/roles/applications/resolution/combined/resolver.py) contains one of the seeds is a candidate, together with the seeds themselves. The closure reads each role's services as the union of `meta/services.yml`, every `meta/variants.yml` entry, and every nested `services` demand another role makes of it, so it contains every round's closure. + - **Includers**: a role whose task or handler files run a seed through `include_role`/`import_role` ([`role_includes`](../../../../utils/roles/invocations.py)), transitively, counts as a seed itself, because each of its rounds runs the seed's tasks. An include whose task or enclosing block requires the included role in `group_names` is skipped: it only runs where the round deploys that role anyway. Each role in that closure is then narrowed to the variants that actually reach a seed: variant `i` of a role is kept only when round `i`'s closure — walked on the same variant-merged services maps [the matrix planner](../../../../cli/administration/deploy/development/inventory/planner.py) builds its rounds from, and therefore variant-aware at every generation of the chain — contains one of the seeds. A role whose variants do not all qualify enters the whitelist as a `role#0,2` selection token, so an image bump in a provider no longer redeploys the variants that switch that provider off. This applies to every auto-derived whitelist — the weekly update PRs, Dependabot, and any other diff-driven run — because they all resolve through this one path. -The reverse closure is fail-safe: any seed that is not modellable in the resolver (no `application_id` and not referenced by any role's `run_after`) MUST trigger a fall-back to a full deploy, as MUST any resolver runtime error. The closure MUST NOT silently shrink the deploy matrix on partial information. The variant narrowing follows the same rule: a role reached only through a `run_after` edge (which the round closure does not follow) keeps every variant, and so does a seed role itself, whose own files changed. +The reverse closure is fail-safe: any seed that is not modellable in the resolver (no `application_id`, so no round closure can contain it) MUST trigger a fall-back to a full deploy, as MUST any resolver runtime error. The closure MUST NOT silently shrink the deploy matrix on partial information. A seed role and every includer keep every variant, because the code they run changed. Every other role none of whose rounds contains a seed is left out of the whitelist, including one reached only through a `run_after` edge: `run_after` is an ordering hint the planner never follows, so no round of that role deploys the seed's change. The PR-scope short-circuits in [scope.sh](../../../../scripts/meta/resolve/pr/scope.sh) (documentation-only, agent-only) still apply at the entry layer. They skip the orchestrator entirely and are independent of the diff-driven whitelist resolution above. diff --git a/scripts/meta/resolve/diff/affected_roles.sh b/scripts/meta/resolve/diff/affected_roles.sh index 273869c759..356c1969c8 100755 --- a/scripts/meta/resolve/diff/affected_roles.sh +++ b/scripts/meta/resolve/diff/affected_roles.sh @@ -1,9 +1,5 @@ #!/usr/bin/env bash # -# Compute which roles are affected by the current branch's diff against -# `origin/main`, expanded transitively over run_after + dependencies + -# services edges via cli.meta.roles.applications.resolution.affected. -# # Output (single line on stdout): # __ALL__ full deploy needed. Emitted when: # * the diff is empty, OR diff --git a/tests/unit/python/cli/meta/roles/applications/resolution/affected/test_main.py b/tests/unit/python/cli/meta/roles/applications/resolution/affected/test_main.py index 0b8acce987..d015e3577e 100644 --- a/tests/unit/python/cli/meta/roles/applications/resolution/affected/test_main.py +++ b/tests/unit/python/cli/meta/roles/applications/resolution/affected/test_main.py @@ -14,6 +14,7 @@ from utils.roles.mapping import ( ROLE_FILE_META_MAIN, ROLE_FILE_META_SERVICES, ROLE_FILE_META_VARIANTS, + ROLE_FILE_TASKS_MAIN, ROLE_FILE_VARS_MAIN, ) @@ -62,6 +63,12 @@ def _write_dependencies(root: Path, role: str, deps: list[str]) -> None: ) +def _write_tasks(root: Path, role: str, tasks: list[dict]) -> None: + path = root / "roles" / role / ROLE_FILE_TASKS_MAIN + path.parent.mkdir(parents=True, exist_ok=True) + dump_yaml(path, tasks) + + class TestAffected(unittest.TestCase): def test_seed_only_when_no_consumers(self) -> None: with tempfile.TemporaryDirectory() as td: @@ -75,7 +82,7 @@ class TestAffected(unittest.TestCase): ["leaf"], ) - def test_run_after_consumer_is_included(self) -> None: + def test_a_run_after_consumer_is_not_affected(self) -> None: with tempfile.TemporaryDirectory() as td: root = Path(td) _mk_app_role(root, "leaf", "leaf") @@ -83,10 +90,8 @@ class TestAffected(unittest.TestCase): _write_run_after(root, "consumer", ["leaf"]) with patch.object(repo_paths, "PROJECT_ROOT", root): - self.assertEqual( - affected_main.affected_roles(["leaf"]), - ["consumer", "leaf"], - ) + self.assertEqual(affected_main.affected_roles(["leaf"]), ["leaf"]) + self.assertEqual(affected_main.affected_selection(["leaf"]), ["leaf"]) def test_dependencies_consumer_is_included_transitively(self) -> None: with tempfile.TemporaryDirectory() as td: @@ -218,6 +223,157 @@ class TestAffected(unittest.TestCase): got = affected_main.affected_selection(["web-app-keycloak"]) self.assertIn("web-app-consumer#0,1", got) + def test_a_role_no_round_of_which_deploys_the_seed_is_left_out(self) -> None: + with tempfile.TemporaryDirectory() as td: + root = Path(td) + for role in ("web-app-n8n", "web-app-matrix", "web-app-discourse"): + _mk_app_role(root, role, role) + off = {"enabled": False, "shared": False} + on = {"enabled": True, "shared": True} + dynamic = "{{ 'web-app-n8n' in group_names }}" + dump_yaml( + root / "roles" / "web-app-matrix" / ROLE_FILE_META_SERVICES, + {"matrix": {}, "n8n": {"enabled": dynamic, "shared": dynamic}}, + ) + dump_yaml( + root / "roles" / "web-app-matrix" / ROLE_FILE_META_VARIANTS, + [{"services": {"n8n": off}}, {"services": {"n8n": on}}], + ) + dump_yaml( + root / "roles" / "web-app-discourse" / ROLE_FILE_META_SERVICES, + {"discourse": {}, "matrix": on}, + ) + dump_yaml( + root / "roles" / "web-app-discourse" / ROLE_FILE_META_VARIANTS, + [{}, {"services": {"matrix": off}}], + ) + + with patch.object(repo_paths, "PROJECT_ROOT", root): + self.assertIn( + "web-app-discourse", affected_main.affected_roles(["web-app-n8n"]) + ) + got = affected_main.affected_selection(["web-app-n8n"]) + self.assertEqual(got, ["web-app-matrix#1", "web-app-n8n"]) + + def test_a_service_key_a_variant_switches_on_reaches_the_seed(self) -> None: + shapes = { + "only the variant declares it": ( + {"moodle": {}}, + {"enabled": True, "shared": True}, + ), + "disk shares it, the variant enables it": ( + {"moodle": {}, "lam": {"shared": True}}, + {"enabled": True}, + ), + } + for label, (disk, variant) in shapes.items(): + with self.subTest(label), tempfile.TemporaryDirectory() as td: + root = Path(td) + _mk_app_role(root, "web-app-lam", "web-app-lam") + _mk_app_role(root, "web-app-moodle", "web-app-moodle") + dump_yaml( + root / "roles" / "web-app-moodle" / ROLE_FILE_META_SERVICES, disk + ) + dump_yaml( + root / "roles" / "web-app-moodle" / ROLE_FILE_META_VARIANTS, + [{"services": {"lam": variant}}, {}], + ) + + with patch.object(repo_paths, "PROJECT_ROOT", root): + got = affected_main.affected_selection(["web-app-lam"]) + self.assertEqual(got, ["web-app-lam", "web-app-moodle#0"]) + + def test_a_nested_services_demand_on_a_provider_reaches_the_seed(self) -> None: + with tempfile.TemporaryDirectory() as td: + root = Path(td) + for role in ("web-app-keycloak", "web-app-matomo", "web-app-consumer"): + _mk_app_role(root, role, role) + off = {"enabled": False, "shared": False} + on = {"enabled": True, "shared": True} + dump_yaml( + root / "roles" / "web-app-matomo" / ROLE_FILE_META_SERVICES, + {"matomo": {"shared": True}, "sso": off}, + ) + dump_yaml( + root / "roles" / "web-app-consumer" / ROLE_FILE_META_SERVICES, + {"consumer": {}, "matomo": on}, + ) + dump_yaml( + root / "roles" / "web-app-consumer" / ROLE_FILE_META_VARIANTS, + [{"services": {"matomo": {**on, "services": {"sso": on}}}}, {}], + ) + + with patch.object(repo_paths, "PROJECT_ROOT", root): + got = affected_main.affected_selection(["web-app-keycloak"]) + self.assertIn("web-app-consumer#0", got) + + def test_an_include_selects_the_includer_and_the_rounds_deploying_it( + self, + ) -> None: + with tempfile.TemporaryDirectory() as td: + root = Path(td) + for role in ("svc-net-firewall", "svc-net-tor", "web-app-consumer"): + _mk_app_role(root, role, role) + off = {"enabled": False, "shared": False} + on = {"enabled": True, "shared": True} + _write_tasks( + root, + "svc-net-tor", + [{"ansible.builtin.include_role": {"name": "svc-net-firewall"}}], + ) + dump_yaml( + root / "roles" / "svc-net-tor" / ROLE_FILE_META_VARIANTS, [{}, {}] + ) + dump_yaml( + root / "roles" / "web-app-consumer" / ROLE_FILE_META_SERVICES, + {"consumer": {}, "tor": on}, + ) + dump_yaml( + root / "roles" / "web-app-consumer" / ROLE_FILE_META_VARIANTS, + [{"services": {"tor": on}}, {"services": {"tor": off}}], + ) + + with patch.object(repo_paths, "PROJECT_ROOT", root): + got = affected_main.affected_selection(["svc-net-firewall"]) + self.assertEqual( + got, ["svc-net-firewall", "svc-net-tor", "web-app-consumer#0"] + ) + + def test_an_include_gated_on_the_included_roles_group_adds_nothing(self) -> None: + gate = "'web-app-openwebui' in group_names" + include = { + "ansible.builtin.include_role": { + "name": "web-app-openwebui", + "tasks_from": "utils/refresh_model_grants.yml", + } + } + shapes = { + "own when": [{**include, "when": [gate, "flag | bool"]}], + "enclosing block": [{"block": [include], "when": gate}], + } + for label, tasks in shapes.items(): + with self.subTest(label), tempfile.TemporaryDirectory() as td: + root = Path(td) + for role in ("web-app-openwebui", "svc-ai-litellm"): + _mk_app_role(root, role, role) + _write_tasks(root, "svc-ai-litellm", tasks) + + with patch.object(repo_paths, "PROJECT_ROOT", root): + got = affected_main.affected_selection(["web-app-openwebui"]) + self.assertEqual(got, ["web-app-openwebui"]) + + def test_includes_chain_transitively(self) -> None: + with tempfile.TemporaryDirectory() as td: + root = Path(td) + for role in ("dsk-a", "dsk-b", "dsk-c", "dsk-d"): + _mk_app_role(root, role, role) + _write_tasks(root, "dsk-b", [{"include_role": {"name": "dsk-a"}}]) + _write_tasks(root, "dsk-c", [{"block": [{"import_role": "dsk-b"}]}]) + + with patch.object(repo_paths, "PROJECT_ROOT", root): + got = affected_main.affected_selection(["dsk-a"]) + self.assertEqual(got, ["dsk-a", "dsk-b", "dsk-c"]) + def test_a_seed_keeps_every_variant_of_its_own_role(self) -> None: with tempfile.TemporaryDirectory() as td: root = Path(td) @@ -253,7 +409,7 @@ class TestAffected(unittest.TestCase): affected_main.EXIT_NON_MODELLABLE_SEED, ) - def test_non_app_seed_reachable_via_run_after_is_modellable(self) -> None: + def test_a_non_app_seed_behind_run_after_is_still_non_modellable(self) -> None: with tempfile.TemporaryDirectory() as td: root = Path(td) _mk_non_app_role(root, "sys-helper") @@ -261,16 +417,19 @@ class TestAffected(unittest.TestCase): _write_run_after(root, "consumer", ["sys-helper"]) with patch.object(repo_paths, "PROJECT_ROOT", root): - got = affected_main.affected_roles(["sys-helper"]) - self.assertIn("sys-helper", got) - self.assertIn("consumer", got) + with self.assertRaises(SystemExit) as ctx: + affected_main.affected_roles(["sys-helper"]) + self.assertEqual( + ctx.exception.code, + affected_main.EXIT_NON_MODELLABLE_SEED, + ) def test_main_prints_space_separated_sorted(self) -> None: with tempfile.TemporaryDirectory() as td: root = Path(td) _mk_app_role(root, "leaf", "leaf") _mk_app_role(root, "consumer", "consumer") - _write_run_after(root, "consumer", ["leaf"]) + _write_dependencies(root, "consumer", ["leaf"]) with patch.object(repo_paths, "PROJECT_ROOT", root): buf = io.StringIO() diff --git a/tests/unit/python/utils/roles/test_invocations.py b/tests/unit/python/utils/roles/test_invocations.py index bc733816c5..09524381de 100644 --- a/tests/unit/python/utils/roles/test_invocations.py +++ b/tests/unit/python/utils/roles/test_invocations.py @@ -6,6 +6,7 @@ from utils.cache.yaml import dump_yaml from utils.roles.invocations import ( deploy_closure, expand_roles, + role_includes, role_invocations, stage_files, stage_invocations, @@ -18,6 +19,9 @@ from utils.roles.mapping import ( ) ROLES = ("role-a", "role-b", "role-c", "sys-ctl-hlth-x", "sys-ctl-hlth-y") +NESTED_CALL_GATE = ( + "'role-b' | application_allowed(group_names, lookup('deployment').whitelist)" +) def _role_file(role: str, role_file: str) -> str: @@ -141,6 +145,46 @@ class TestRoleInvocations(_TreeMixin, unittest.TestCase): ) +class TestRoleIncludes(_TreeMixin, unittest.TestCase): + def _includes(self, tasks) -> frozenset[str]: + self._write(_role_file("role-a", ROLE_FILE_TASKS_MAIN), tasks) + return role_includes(str(self.root / "roles"), "role-a") + + def test_a_template_with_a_literal_part_names_no_role(self): + tasks = [{"include_role": {"name": "sys-ctl-hlth-{{ kind }}"}}] + self.assertEqual(self._includes(tasks), frozenset()) + + def test_literal_names_and_literal_loop_items_are_included(self): + tasks = [ + {"include_role": {"name": "role-b"}}, + { + "include_role": {"name": "{{ dep }}"}, + "loop": ["role-c"], + "loop_control": {"loop_var": "dep"}, + }, + ] + self.assertEqual(self._includes(tasks), {"role-b", "role-c"}) + + def test_a_gate_holds_the_include_in_either_quote_style(self): + roles = str(self.root / "roles") + for role, quote in (("role-a", "'"), ("role-c", '"')): + self._write( + _role_file(role, ROLE_FILE_TASKS_MAIN), + [ + { + "include_role": {"name": "role-b"}, + "when": f"{quote}role-b{quote} in group_names", + } + ], + ) + self.assertEqual(role_includes(roles, "role-a"), frozenset()) + self.assertEqual(role_includes(roles, "role-c"), role_includes(roles, "role-a")) + + def test_a_gate_with_a_nested_call_argument_holds_the_include(self): + tasks = [{"include_role": {"name": "role-b"}, "when": NESTED_CALL_GATE}] + self.assertEqual(self._includes(tasks), frozenset()) + + class TestStageInvocations(_TreeMixin, unittest.TestCase): def _stage(self, tasks): return self._write("tasks/stages/01_constructor.yml", tasks) @@ -180,6 +224,45 @@ class TestStageInvocations(_TreeMixin, unittest.TestCase): {"role-b"}, ) + def test_a_double_quoted_membership_gate_closes_for_a_non_member(self): + path = self._stage( + [{"include_role": {"name": "role-b"}, "when": '"role-b" in group_names'}] + ) + self.assertEqual( + stage_invocations(path, frozenset(ROLES), seeds=[], group_names=[]), set() + ) + + def test_a_membership_test_inside_a_compound_condition_keeps_the_include(self): + path = self._stage( + [ + { + "include_role": {"name": "role-b"}, + "when": '"role-b" in group_names or true', + }, + { + "include_role": {"name": "role-c"}, + "when": "'role-c' in group_names or true", + }, + ] + ) + self.assertEqual( + stage_invocations(path, frozenset(ROLES), seeds=[], group_names=[]), + {"role-b", "role-c"}, + ) + + def test_an_application_allowed_gate_with_a_nested_call_decides_on_the_seeds(self): + path = self._stage( + [{"include_role": {"name": "role-b"}, "when": NESTED_CALL_GATE}] + ) + self.assertEqual( + stage_invocations(path, frozenset(ROLES), seeds=[], group_names=["role-b"]), + set(), + ) + self.assertEqual( + stage_invocations(path, frozenset(ROLES), seeds=["role-b"], group_names=[]), + {"role-b"}, + ) + def test_any_other_condition_keeps_the_include(self): path = self._stage( [{"include_role": {"name": "role-c"}, "when": ["MODE_CLEANUP | bool"]}] diff --git a/utils/roles/invocations.py b/utils/roles/invocations.py index ad52eb1674..fbafdb3384 100644 --- a/utils/roles/invocations.py +++ b/utils/roles/invocations.py @@ -50,7 +50,9 @@ _ROLE_FILE_REF_RE = re.compile(r"roles/(?P[a-z0-9-]+)/(?:tasks|handlers)/" _QUOTED_NAME_RE = re.compile(r"['\"](?P[a-z0-9][a-z0-9-]*)['\"]") _TEMPLATE_RE = re.compile(r"\{\{.*?\}\}") _MEMBERSHIP_GATE_RE = re.compile( - r"^'(?P[a-z0-9-]+)'\s*(?Pin\s+group_names|\|\s*application_allowed\b)" + r"(?P['\"])(?P[a-z0-9-]+)(?P=quote)\s*" + r"(?Pin\s+group_names" + r"|\|\s*application_allowed\s*\((?:[^()]|\([^()]*\))*\))" ) @@ -86,12 +88,12 @@ def _strings(value: Any) -> Iterator[str]: yield from _strings(item) -def _named(name: str, known: frozenset[str]) -> set[str] | None: +def _named(name: str, known: frozenset[str], *, globs: bool) -> set[str] | None: name = name.strip() if "{{" not in name: return {name} pattern = _TEMPLATE_RE.sub("*", name) - if not pattern.strip("*"): + if not globs or not pattern.strip("*"): return None return set(fnmatch.filter(known, pattern)) @@ -117,6 +119,35 @@ def _looped(task: dict[str, Any]) -> set[str] | None: return None +def included_roles( + task: dict[str, Any], known: frozenset[str], *, globs: bool +) -> tuple[set[str], bool]: + """ + Args: + task: one task mapping without the tasks nested in its blocks. + known: every existing role name. + globs: whether a template with a literal part names every role its + glob matches; else it names a role only through a literal loop. + + Returns: + The roles the task's ``include_role``/``import_role`` names, and + whether a name stayed unresolved. + """ + included: set[str] = set() + unresolved = False + for key in INCLUDE_ROLE_KEYS & task.keys(): + spec = task[key] + name = spec.get("name") if isinstance(spec, dict) else spec + named = _named(name, known, globs=globs) if isinstance(name, str) else None + if named is None: + named = _looped(task) + if named is None: + unresolved = True + continue + included |= named + return included & known, unresolved + + def task_invocations( task: dict[str, Any], known: frozenset[str] ) -> tuple[set[str], bool]: @@ -132,19 +163,8 @@ def task_invocations( invoked.update( match.group("role") for match in _ROLE_FILE_REF_RE.finditer(value) ) - - unresolved = False - for key in INCLUDE_ROLE_KEYS & own.keys(): - spec = own[key] - name = spec.get("name") if isinstance(spec, dict) else spec - named = _named(name, known) if isinstance(name, str) else None - if named is None: - named = _looped(own) - if named is None: - unresolved = True - continue - invoked |= named - return invoked & known, unresolved + included, unresolved = included_roles(own, known, globs=True) + return (invoked | included) & known, unresolved def file_invocations(path: Path, known: frozenset[str]) -> tuple[set[str], bool]: @@ -198,6 +218,65 @@ def role_invocations(roles_dir: str, role: str) -> frozenset[str]: return frozenset(invoked & known) +def _own_gates(when: Any) -> set[str]: + """ + Args: + when: a task's ``when``. + + Returns: + Every role one whole condition of *when* requires in the host's + groups (``'' in group_names``, ``'' | application_allowed(...)``). + """ + conditions = when if isinstance(when, list) else [when] + return { + match.group("role") + for condition in conditions + if isinstance(condition, str) + and (match := _MEMBERSHIP_GATE_RE.fullmatch(condition.strip())) + } + + +def _ungated_includes( + node: Any, gates: frozenset[str], known: frozenset[str] +) -> Iterator[str]: + if not isinstance(node, list): + return + for task in node: + if not isinstance(task, dict): + continue + held = gates | _own_gates(task.get("when")) + own = {key: value for key, value in task.items() if key not in NESTED_KEYS} + yield from included_roles(own, known, globs=False)[0] - held + for key in NESTED_KEYS: + yield from _ungated_includes(task.get(key), held, known) + + +@cache +def role_includes(roles_dir: str, role: str) -> frozenset[str]: + """ + Args: + roles_dir: directory holding the role folders. + role: role name. + + Returns: + Every other role an ``include_role``/``import_role`` in *role*'s task + and handler files names literally or through a literal loop, except + where that task or an enclosing block requires the included role in + the host's groups. + """ + known = role_names(roles_dir) + included = { + name + for path in _files(Path(roles_dir) / role, TASK_FILE_DIRS) + if any(key in read_text(str(path)) for key in ("include_role", "import_role")) + for name in _ungated_includes( + load_yaml_any(str(path), default_if_missing=None), frozenset(), known + ) + } + included.discard(role) + return frozenset(included) + + def stage_files(project_root: Path, host_types: Iterable[str]) -> list[Path]: """Return the play's stage files a host with *host_types* runs, in order. @@ -221,7 +300,7 @@ def _gate_closed( for condition in when if isinstance(when, list) else [when]: if not isinstance(condition, str): continue - match = _MEMBERSHIP_GATE_RE.match(condition.strip()) + match = _MEMBERSHIP_GATE_RE.fullmatch(condition.strip()) if match is None: continue members = group_names if match.group("test").startswith("in") else seeds @@ -283,7 +362,7 @@ def deploy_closure( group_names: the host's inventory groups. """ known = role_names(str(Path(project_root) / "roles")) - seed_set = {str(seed) for seed in seeds} + seed_set = {str(name) for name in seeds} roots = set(seed_set) for path in stage_files(project_root, host_types): roots |= stage_invocations(path, known, seeds=seed_set, group_names=group_names)