From 1ed3fd11dab1869c6bd6eea3ada6635e530002f2 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Wed, 4 Nov 2026 10:41:09 +0100 Subject: [PATCH] fix(provision): disable the services gated on a provider the row disables A tor-only CI row disables web-svc-coturn, which no onion can serve, but the disabler switched off only service entries keyed coturn. Nextcloud's talk entry is gated on 'web-svc-coturn' in group_names and variant 0 pins it true, so Talk stayed on without a TURN server and 01_fullstack.yml's assert stopped every Nextcloud#0 tor row. When disable resolves to a provider role P, every entry whose base enabled is exactly the presence test of P is written false as well, and the reconcile releases those entries once P is no longer disabled. Negated, compound and variable gates are left alone. Across all 755 planner row states this changes one value an app sees: talk on Nextcloud#0 tor rows. Co-Authored-By: Claude Opus 5.5 --- .../inventory/provision/services_disabler.py | 136 +++++++++++--- docs/contributing/environment/hardware.md | 2 +- .../test_disabled_provider_dependents.py | 141 +++++++++++++++ .../provision/test_services_disabler.py | 170 ++++++++++++++++++ 4 files changed, 424 insertions(+), 25 deletions(-) create mode 100644 tests/integration/infrastructure/services/test_disabled_provider_dependents.py diff --git a/cli/administration/inventory/provision/services_disabler.py b/cli/administration/inventory/provision/services_disabler.py index 5710a91c35..c478374b73 100644 --- a/cli/administration/inventory/provision/services_disabler.py +++ b/cli/administration/inventory/provision/services_disabler.py @@ -1,6 +1,7 @@ from __future__ import annotations import os +import re from typing import TYPE_CHECKING from ruamel.yaml.comments import CommentedMap @@ -21,6 +22,10 @@ if TYPE_CHECKING: DISABLED_SERVICES_RECORD = "_INFINITO_SERVICES_DISABLED" +_PRESENCE_TEST = re.compile( + r"""\{\{\s*(['"])(?P[\w.-]+)\1\s+in\s+group_names\s*\}\}""" +) + def _load_yaml_mapping_tolerant(path: Path) -> dict: """Read a YAML file as a mapping; non-mapping or unparseable content @@ -104,6 +109,66 @@ def _declared_toggles(app_id: str, svc_name: str, roles_dir: Path) -> list[str]: return [flag for flag in ("enabled", "shared") if flag in entry] +def _presence_tested_role(value: object) -> str | None: + if not isinstance(value, str): + return None + match = _PRESENCE_TEST.fullmatch(value.strip()) + return match.group("role") if match else None + + +def find_presence_dependents( + provider_roles: set[str], roles_dir: Path +) -> list[tuple[str, str, str]]: + """Service entries a role switches on only while a provider is deployed. + + Args: + provider_roles: application ids of the providers being disabled. + roles_dir: roles tree whose ``meta/services.yml`` files are read. + + Returns: + ``(app_id, service_key, provider)`` for every entry whose base + ``enabled`` is exactly ``'' in group_names``, in role and + file order. Negated and compound gates never match. + """ + dependents: list[tuple[str, str, str]] = [] + if not provider_roles or not roles_dir.exists(): + return dependents + for role_dir in sorted(roles_dir.iterdir()): + services = _load_yaml_mapping_tolerant(role_dir / ROLE_FILE_META_SERVICES) + for svc_name, entry in services.items(): + if not isinstance(entry, dict): + continue + provider = _presence_tested_role(entry.get("enabled")) + if provider in provider_roles: + dependents.append((role_dir.name, svc_name, provider)) + return dependents + + +def _disable_entry( + applications: CommentedMap, app_id: str, svc_name: str, flags: list[str] +) -> bool: + app_data = applications.get(app_id) + if not isinstance(app_data, CommentedMap): + app_data = CommentedMap() + applications[app_id] = app_data + + svc_map = app_data.get("services") + if not isinstance(svc_map, CommentedMap): + svc_map = CommentedMap() + app_data["services"] = svc_map + + if not flags: + return False + + svc = svc_map.get(svc_name) + if not isinstance(svc, CommentedMap): + svc = CommentedMap() + svc_map[svc_name] = svc + for flag in flags: + svc[flag] = False + return True + + def find_provider_roles(services: list[str], roles_dir: Path) -> dict[str, str]: """ Return mapping of service_name -> application_id for the provider role of each @@ -179,7 +244,10 @@ def apply_services_disabled( For every role under roles_dir whose meta/services.yml defines a service listed in `services`, set enabled: false and shared: false in host_vars_file under applications..services.. Missing application - or services blocks are created as needed. + or services blocks are created as needed. The same happens to every entry + whose base `enabled` is the presence test of a disabled provider role + (:func:`find_presence_dependents`), so a variant's literal pin cannot keep + it on once that provider leaves the inventory. Per the materialised path is ``applications..services.`` (no ``compose.services`` wrapper). @@ -210,26 +278,9 @@ def apply_services_disabled( changed = False for svc_name in services: for app_id in sorted(find_roles_with_service(svc_name, roles_dir)): - app_data = applications.get(app_id) - if not isinstance(app_data, CommentedMap): - app_data = CommentedMap() - applications[app_id] = app_data - - svc_map = app_data.get("services") - if not isinstance(svc_map, CommentedMap): - svc_map = CommentedMap() - app_data["services"] = svc_map - flags = _declared_toggles(app_id, svc_name, roles_dir) - if not flags: + if not _disable_entry(applications, app_id, svc_name, flags): continue - - svc = svc_map.get(svc_name) - if not isinstance(svc, CommentedMap): - svc = CommentedMap() - svc_map[svc_name] = svc - for flag in flags: - svc[flag] = False changed = True written = ", ".join(f"{flag}=false" for flag in flags) print(f"[INFO] disable: {app_id}.services.{svc_name} → {written}") @@ -255,12 +306,26 @@ def apply_services_disabled( f"[INFO] disable: {app_id}.services.{svc_name} (variant-baked) → {written}" ) + provider_map = find_provider_roles(services, roles_dir) + for app_id, svc_name, provider in find_presence_dependents( + set(provider_map.values()), roles_dir + ): + if svc_name in services: + continue + flags = _declared_toggles(app_id, svc_name, roles_dir) + if not _disable_entry(applications, app_id, svc_name, flags): + continue + changed = True + written = ", ".join(f"{flag}=false" for flag in flags) + print( + f"[INFO] disable: {app_id}.services.{svc_name} (gated on {provider}) → {written}" + ) + if changed: with host_vars_file.open("w", encoding="utf-8") as f: yaml_rt.dump(doc, f) if inventory_file is not None: - provider_map = find_provider_roles(services, roles_dir) if provider_map: print(f"[INFO] disable: provider roles found: {provider_map}") remove_roles_from_inventory(inventory_file, list(provider_map.values())) @@ -284,14 +349,34 @@ def apply_services_disabled_from_env( ) -def _revert_disabled_toggles(applications: CommentedMap, services: list[str]) -> None: +def _released_dependents( + stale: list[str], current: list[str], roles_dir: Path +) -> list[tuple[str, str]]: + released = set(find_provider_roles(stale, roles_dir).values()) - set( + find_provider_roles(current, roles_dir).values() + ) + return [ + (app_id, svc_name) + for app_id, svc_name, _provider in find_presence_dependents(released, roles_dir) + if svc_name not in current + ] + + +def _revert_disabled_toggles( + applications: CommentedMap, + services: list[str], + dependents: list[tuple[str, str]], +) -> None: + gated: dict[str, list[str]] = {} + for app_id, svc_name in dependents: + gated.setdefault(app_id, []).append(svc_name) for app_id, app_data in applications.items(): if not isinstance(app_data, CommentedMap): continue svc_map = app_data.get("services") if not isinstance(svc_map, CommentedMap): continue - for svc_name in services: + for svc_name in dict.fromkeys([*services, *gated.get(app_id, [])]): svc = svc_map.get(svc_name) if not isinstance(svc, CommentedMap): continue @@ -310,7 +395,8 @@ def _revert_disabled_toggles(applications: CommentedMap, services: list[str]) -> def reconcile_services_disabled_from_env(host_vars_file: Path, roles_dir: Path) -> None: """Drop the false toggles of every key the previous `disable` run recorded - and this run's `disable` no longer lists, then record this run's keys. + and this run's `disable` no longer lists, and of every entry gated on a + provider those keys no longer keep disabled, then record this run's keys. Runs before the variant bake, so a variant that wants a toggle off writes it again right after. @@ -333,7 +419,9 @@ def reconcile_services_disabled_from_env(host_vars_file: Path, roles_dir: Path) stale = [key for key in recorded if key not in current] applications = doc.get("applications") if stale and isinstance(applications, CommentedMap): - _revert_disabled_toggles(applications, stale) + _revert_disabled_toggles( + applications, stale, _released_dependents(stale, current, roles_dir) + ) if current: doc[DISABLED_SERVICES_RECORD] = current diff --git a/docs/contributing/environment/hardware.md b/docs/contributing/environment/hardware.md index 318ed941de..f4ac45b79d 100644 --- a/docs/contributing/environment/hardware.md +++ b/docs/contributing/environment/hardware.md @@ -43,7 +43,7 @@ You MAY pass `disable=` to `make compose-deploy` to disable services automa make compose-deploy mode=reinstall apps=web-app-discourse disable=matomo ``` -This sets `enabled: false` and `shared: false` for every listed service in the generated inventory. See [variables.md](variables.md) for details. +This sets `enabled: false` and `shared: false` for every listed service in the generated inventory, and for every service entry whose `enabled` is exactly `"{{ '' in group_names }}"` of a disabled provider role, even where a variant pins that entry on. Negated and compound gates stay untouched. See [variables.md](variables.md) for details. | Service | Optional | What it provides | Effect of disabling | Safe to disable when | |---|---|---|---|---| diff --git a/tests/integration/infrastructure/services/test_disabled_provider_dependents.py b/tests/integration/infrastructure/services/test_disabled_provider_dependents.py new file mode 100644 index 0000000000..f17ffc6d3b --- /dev/null +++ b/tests/integration/infrastructure/services/test_disabled_provider_dependents.py @@ -0,0 +1,141 @@ +"""Integration guard: a disabled provider takes the entries gated on its +presence along, even where a variant pins them on. + +``web-app-nextcloud#0`` pins ``services.talk.enabled: true``, while the role's +own gate is ``'web-svc-coturn' in group_names``. On a tor-only row the CI +planner disables ``web-svc-coturn``, which serves clearnet only. Talk then stayed +on without a TURN server, and the role's "Talk has the TURN server its calls +relay through" assert failed on every such row. + +The test builds that row's inventory the way the dev deploy does (planner +include, ``disable`` tokens, orphan prune, variant bake, provision disabler) and +renders the real applications payload against the row's groups: whenever the +spreed addon is on, the standalone TURN server it hands out must be on too. +""" + +from __future__ import annotations + +import contextlib +import io +import json +import os +import unittest +from pathlib import Path +from tempfile import TemporaryDirectory +from unittest.mock import patch + +from ansible.parsing.dataloader import DataLoader +from ansible.template import Templar + +from cli.administration.deploy.development.inventory import ( + _build_services_overrides_for_round, + _resolve_variant_payloads, + plan_dev_inventory_matrix, + prune_orphans_after_disable, +) +from cli.administration.inventory.provision.services_disabler import ( + apply_services_disabled_from_env, + find_provider_roles, + parse_services_disabled, + reconcile_services_disabled_from_env, +) +from utils.cache import _reset_cache_for_tests +from utils.cache.applications import get_merged_applications +from utils.cache.yaml import dump_yaml, load_yaml_any +from utils.github.variant.network import TOR, disabled_services + +from . import PROJECT_ROOT + +ROLES_DIR = PROJECT_ROOT / "roles" +APP = "web-app-nextcloud" +TURN_PROVIDER = "web-svc-coturn" +VARIANT = 0 + + +def _provision_tor_row(workdir: Path) -> tuple[list[str], dict]: + """Provision the tor-only row of ``APP#VARIANT``. + + Args: + workdir: directory the row's ``devices.yml`` and host_vars go to. + + Returns: + the row's inventory groups and its host_vars ``applications``. + """ + plan = plan_dev_inventory_matrix( + roles_dir=str(ROLES_DIR), primary_apps=[APP], base_inventory_dir="plan" + ) + round_index, _dir, round_variants, include, _purge = plan[VARIANT] + disable = disabled_services(TOR, include) + if TURN_PROVIDER not in disable.split(): + raise AssertionError( + f"the tor-only row of {APP}#{VARIANT} no longer disables {TURN_PROVIDER} " + f"(disable={disable!r}); this guard reproduces nothing" + ) + disabled = find_provider_roles(parse_services_disabled(disable), ROLES_DIR) + include, _pruned = prune_orphans_after_disable( + include=include, + primary_apps=[APP], + disabled_app_ids=set(disabled.values()), + services_overrides=_build_services_overrides_for_round( + roles_dir=str(ROLES_DIR), + round_index=round_index, + primary_app_variants={APP: round_variants[APP]}, + ), + ) + payloads = _resolve_variant_payloads( + roles_dir=str(ROLES_DIR), include=include, active_variants=round_variants + ) + host_vars = workdir / "localhost.yml" + devices = workdir / "devices.yml" + dump_yaml(host_vars, {"applications": json.loads(json.dumps(payloads))}) + dump_yaml( + devices, + {"all": {"children": {app: {"hosts": {"localhost": {}}} for app in include}}}, + ) + with ( + patch.dict(os.environ, {"disable": disable}), + contextlib.redirect_stdout(io.StringIO()), + ): + reconcile_services_disabled_from_env(host_vars, ROLES_DIR) + apply_services_disabled_from_env( + host_vars, roles_dir=ROLES_DIR, inventory_file=devices + ) + groups = sorted(load_yaml_any(devices)["all"]["children"]) + return groups, load_yaml_any(host_vars)["applications"] + + +class TestDisabledProviderDependents(unittest.TestCase): + def tearDown(self) -> None: + _reset_cache_for_tests() + + def test_talk_hands_out_a_turn_server_on_the_tor_row(self) -> None: + with TemporaryDirectory() as tmp: + groups, applications = _provision_tor_row(Path(tmp)) + _reset_cache_for_tests() + rendered = get_merged_applications( + variables={ + "ansible_facts": {"os_family": "Debian"}, + "ansible_connection": "local", + "inventory_hostname": "localhost", + "group_names": groups, + "applications": applications, + }, + roles_dir=str(ROLES_DIR), + templar=Templar(loader=DataLoader()), + )[APP] + + spreed = rendered["addons"]["spreed"]["enabled"] + turn = rendered["services"]["talk"]["turn_server"]["standalone_enabled"] + + self.assertIsInstance(spreed, bool) + self.assertIsInstance(turn, bool) + self.assertFalse( + spreed and not turn, + f"{APP}#{VARIANT} on a tor-only row runs Talk (spreed enabled) while " + f"{TURN_PROVIDER} is out of the inventory, so Talk hands out no TURN " + "server and the role's TURN assert fails", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/cli/administration/inventory/provision/test_services_disabler.py b/tests/unit/python/cli/administration/inventory/provision/test_services_disabler.py index d127a5e0bc..8835bfa57c 100644 --- a/tests/unit/python/cli/administration/inventory/provision/test_services_disabler.py +++ b/tests/unit/python/cli/administration/inventory/provision/test_services_disabler.py @@ -13,6 +13,7 @@ from cli.administration.inventory.provision.services_disabler import ( apply_services_disabled, apply_services_disabled_from_env, assert_services_disabled_inventory_consistency_from_env, + find_presence_dependents, find_provider_roles, find_services_disabled_conflicts, parse_services_disabled, @@ -412,6 +413,175 @@ class TestApplyServicesDisabled(unittest.TestCase): self.assertFalse(result["applications"]["app-b"]["services"]["ldap"]["enabled"]) +COTURN_GATE = "{{ 'web-svc-coturn' in group_names }}" + + +class TestPresenceDependents(unittest.TestCase): + def setUp(self): + self.tmp = TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + self.yaml_rt = YAML(typ="rt") + self.yaml_rt.preserve_quotes = True + self.host_vars = self.root / "host_vars.yml" + self.roles_dir = self.root / "roles" + self.roles_dir.mkdir() + self._make_role( + "web-svc-coturn", {"coturn": {"image": "coturn", "shared": True}} + ) + self._make_role( + "web-app-matomo", {"matomo": {"image": "matomo", "shared": True}} + ) + + def _make_role(self, role_name: str, services: dict) -> None: + role_dir = self.roles_dir / role_name + (role_dir / "meta").mkdir(parents=True) + (role_dir / "vars").mkdir(parents=True) + dump_yaml(role_dir / ROLE_FILE_META_SERVICES, services) + dump_yaml(role_dir / ROLE_FILE_VARS_MAIN, {"application_id": role_name}) + + def _consumer(self, key: str, enabled: str, *, shared: bool) -> None: + entry = {"enabled": enabled, **({"shared": enabled} if shared else {})} + self._make_role( + "web-app-nextcloud", {"coturn": {"enabled": COTURN_GATE}, key: entry} + ) + pinned = {"enabled": True, **({"shared": True} if shared else {})} + with self.host_vars.open("w") as f: + self.yaml_rt.dump( + {"applications": {"web-app-nextcloud": {"services": {key: pinned}}}}, f + ) + + def _disable(self, tokens: list[str]) -> dict: + apply_services_disabled(self.host_vars, tokens, roles_dir=self.roles_dir) + with self.host_vars.open("r") as f: + return dict( + self.yaml_rt.load(f)["applications"]["web-app-nextcloud"]["services"] + ) + + def test_an_entry_gated_on_the_disabled_provider_is_flipped(self): + self._consumer("talk", COTURN_GATE, shared=True) + + services = self._disable(["web-svc-coturn"]) + + self.assertEqual({"enabled": False, "shared": False}, dict(services["talk"])) + + def test_the_service_key_of_the_provider_flips_the_gated_entry_too(self): + self._consumer("talk", COTURN_GATE, shared=True) + + services = self._disable(["coturn"]) + + self.assertEqual({"enabled": False, "shared": False}, dict(services["talk"])) + + def test_double_quotes_and_tight_spacing_still_match(self): + self._consumer("talk", '{{"web-svc-coturn" in group_names}}', shared=True) + + services = self._disable(["web-svc-coturn"]) + + self.assertEqual({"enabled": False, "shared": False}, dict(services["talk"])) + + def test_a_negated_gate_is_left_alone(self): + self._consumer( + "fallback", "{{ 'web-svc-coturn' not in group_names }}", shared=True + ) + + services = self._disable(["web-svc-coturn"]) + + self.assertEqual({"enabled": True, "shared": True}, dict(services["fallback"])) + + def test_a_compound_gate_is_left_alone(self): + self._consumer( + "talk", + "{{ 'web-svc-coturn' in group_names and 'svc-net-tor' not in group_names }}", + shared=True, + ) + + services = self._disable(["web-svc-coturn"]) + + self.assertEqual({"enabled": True, "shared": True}, dict(services["talk"])) + + def test_a_gate_on_a_variable_is_left_alone(self): + self._consumer("talk", "{{ TURN_PROVIDER in group_names }}", shared=True) + + services = self._disable(["web-svc-coturn"]) + + self.assertEqual({"enabled": True, "shared": True}, dict(services["talk"])) + + def test_a_gate_on_another_provider_is_left_alone(self): + self._consumer("talk", "{{ 'web-app-matomo' in group_names }}", shared=True) + + services = self._disable(["web-svc-coturn"]) + + self.assertEqual({"enabled": True, "shared": True}, dict(services["talk"])) + + def test_a_gated_entry_without_shared_does_not_get_one(self): + self._consumer("talk", COTURN_GATE, shared=False) + + services = self._disable(["web-svc-coturn"]) + + self.assertEqual({"enabled": False}, dict(services["talk"])) + + def test_dependents_report_the_entry_and_its_provider(self): + self._consumer("talk", COTURN_GATE, shared=True) + + self.assertEqual( + [("web-app-nextcloud", "talk", "web-svc-coturn")], + [ + dependent + for dependent in find_presence_dependents( + {"web-svc-coturn"}, self.roles_dir + ) + if dependent[1] != "coturn" + ], + ) + + def _provision(self, disable: str) -> None: + with unittest.mock.patch.dict(os.environ, {"disable": disable}): + reconcile_services_disabled_from_env(self.host_vars, self.roles_dir) + apply_services_disabled_from_env(self.host_vars, roles_dir=self.roles_dir) + + def test_a_provider_dropped_from_disable_releases_its_gated_entry(self): + self._make_role( + "web-app-nextcloud", + {"coturn": {"enabled": COTURN_GATE}, "talk": {"enabled": COTURN_GATE}}, + ) + with self.host_vars.open("w") as f: + self.yaml_rt.dump({"applications": {}}, f) + + self._provision("web-svc-coturn,matomo") + self._provision("matomo") + + with self.host_vars.open("r") as f: + services = self.yaml_rt.load(f)["applications"]["web-app-nextcloud"][ + "services" + ] + self.assertNotIn("talk", services) + + def test_a_provider_another_listed_key_keeps_disabled_holds_its_gated_entry(self): + dump_yaml( + self.roles_dir / "web-svc-coturn" / ROLE_FILE_META_SERVICES, + { + "coturn": {"image": "coturn", "shared": True}, + "turn": {"enabled": True, "shared": True, "canonical": "coturn"}, + }, + ) + self._make_role( + "web-app-nextcloud", + {"coturn": {"enabled": COTURN_GATE}, "talk": {"enabled": COTURN_GATE}}, + ) + with self.host_vars.open("w") as f: + self.yaml_rt.dump({"applications": {}}, f) + self._provision("web-svc-coturn") + + with unittest.mock.patch.dict(os.environ, {"disable": "coturn"}): + reconcile_services_disabled_from_env(self.host_vars, self.roles_dir) + + with self.host_vars.open("r") as f: + services = self.yaml_rt.load(f)["applications"]["web-app-nextcloud"][ + "services" + ] + self.assertEqual({"enabled": False}, dict(services["talk"])) + + class TestApplyServicesDisabledFromEnv(unittest.TestCase): def setUp(self): self.tmp = TemporaryDirectory()