diff --git a/cli/administration/deploy/swarm/matrix.py b/cli/administration/deploy/swarm/matrix.py index e72c9dab8d..664df8d59e 100644 --- a/cli/administration/deploy/swarm/matrix.py +++ b/cli/administration/deploy/swarm/matrix.py @@ -52,10 +52,13 @@ def _provision( ) -def _extend_inventory(*, app_id: str, inv_dir: str) -> int: +def _extend_inventory( + *, app_id: str, inv_dir: str, round_variants: dict[str, int] +) -> int: env = os.environ.copy() env["APP_ID"] = app_id env["INV_PATH"] = f"{inv_dir}/devices.yml" + env["INFINITO_APP_VARIANTS"] = json.dumps(round_variants, sort_keys=True) return _run( ["python3", "-m", "utils.tests.swarm.extend_inventory"], env=env, @@ -228,7 +231,9 @@ def main(argv: list[str] | None = None) -> int: if rc == 0: rc = _force_shared_db(inv_dir=inv_root) if rc == 0: - rc = _extend_inventory(app_id=app_id, inv_dir=inv_root) + rc = _extend_inventory( + app_id=app_id, inv_dir=inv_root, round_variants=round_variants + ) if rc == 0: rc = _write_extras(extras_path=extras_path) if rc == 0: diff --git a/tests/unit/utils/tests/swarm/test_derive_includes.py b/tests/unit/utils/tests/swarm/test_derive_includes.py index 78233c2d19..de4bce4978 100644 --- a/tests/unit/utils/tests/swarm/test_derive_includes.py +++ b/tests/unit/utils/tests/swarm/test_derive_includes.py @@ -35,6 +35,44 @@ class TestActiveVariantMap(unittest.TestCase): self.assertEqual(mod._active_variant_map(), {"web-app-z": 2}) +class TestForceSharedDbView(unittest.TestCase): + def _keys(self, value): + return unittest.mock.patch.object( + mod, "db_provider_service_keys", return_value=value + ) + + def test_flips_shared_on_existing_db_entries(self): + apps = { + "web-app-x": { + "services": { + "postgres": {"enabled": True, "shared": False}, + "sso": {"enabled": False, "shared": False}, + } + } + } + with self._keys({"postgres", "mariadb"}): + result = mod._force_shared_db_view(apps) + self.assertTrue(result["web-app-x"]["services"]["postgres"]["shared"]) + self.assertFalse(result["web-app-x"]["services"]["sso"]["shared"]) + + def test_missing_entries_are_not_created(self): + apps = {"web-app-x": {"services": {"sso": {"enabled": True}}}} + with self._keys({"mariadb"}): + result = mod._force_shared_db_view(apps) + self.assertNotIn("mariadb", result["web-app-x"]["services"]) + + def test_input_is_not_mutated(self): + apps = {"web-app-x": {"services": {"mariadb": {"shared": False}}}} + with self._keys({"mariadb"}): + mod._force_shared_db_view(apps) + self.assertFalse(apps["web-app-x"]["services"]["mariadb"]["shared"]) + + def test_no_db_keys_returns_input(self): + apps = {"web-app-x": {"services": {}}} + with self._keys(set()): + self.assertIs(mod._force_shared_db_view(apps), apps) + + class TestApplicationsForActiveVariants(unittest.TestCase): def setUp(self): self.base = { diff --git a/utils/tests/swarm/derive_includes.py b/utils/tests/swarm/derive_includes.py index a2d342202a..88c6bcb215 100755 --- a/utils/tests/swarm/derive_includes.py +++ b/utils/tests/swarm/derive_includes.py @@ -15,6 +15,9 @@ Input (env): ``APP_ID``. Optional ``INFINITO_APP_VARIANTS`` (JSON selects the active variant so a variant that pins ``services.*`` flags to ``false`` prunes those providers from the closure instead of the provision step pulling them in from the variant-free base config. + +DB-provider services are exempt from that pruning: the dep walk applies +the same force-shared view as ``utils.tests.swarm.force_shared_db``. """ from __future__ import annotations @@ -30,6 +33,7 @@ from utils.roles.applications.in_group_deps import applications_if_group_and_all from utils.roles.applications.services.registry import ( build_service_registry_from_applications, ) +from utils.tests.swarm.force_shared_db import db_provider_service_keys _ROLES_DIR = PROJECT_ROOT / "roles" @@ -81,16 +85,47 @@ def _applications_for_active_variants( return applications +def _force_shared_db_view(applications: dict[str, Any]) -> dict[str, Any]: + """Mirror ``force_shared_db``: flip ``shared: true`` on every existing + svc-db-* provider service entry so the dep walk sees the topology the + swarm deploy will actually run.""" + db_keys = db_provider_service_keys(_ROLES_DIR) + if not db_keys: + return applications + result = dict(applications) + for app_id, config in applications.items(): + services = config.get("services") if isinstance(config, dict) else None + if not isinstance(services, dict): + continue + flipped = { + key + for key, entry in services.items() + if key in db_keys + and isinstance(entry, dict) + and entry.get("shared") is not True + } + if not flipped: + continue + patched_services = dict(services) + for key in flipped: + patched_services[key] = {**services[key], "shared": True} + result[app_id] = {**config, "services": patched_services} + return result + + def derive_includes(app_id: str) -> list[str]: """Resolve APP_ID's transitive include set under the active variants. The service registry (service key -> provider role) stays built from the full rendered base set so provider discovery is unaffected by the - active variants; only the dep-walk sees the variant configs. + active variants; only the dep-walk sees the variant configs (with the + swarm force-shared DB view applied on top). """ base_applications = get_merged_applications(roles_dir=str(_ROLES_DIR)) service_registry = build_service_registry_from_applications(base_applications) - applications = _applications_for_active_variants(base_applications) + applications = _force_shared_db_view( + _applications_for_active_variants(base_applications) + ) transitive = applications_if_group_and_all_deps( applications, [app_id], diff --git a/utils/tests/swarm/extend_inventory.py b/utils/tests/swarm/extend_inventory.py index 5e46a73052..2f374d8170 100755 --- a/utils/tests/swarm/extend_inventory.py +++ b/utils/tests/swarm/extend_inventory.py @@ -4,7 +4,16 @@ plus the dep-walked ``default_placement: manager`` set, so the static validator (running before ansible) finds every group the swarm deploy will use. +The dep walk delegates to ``derive_includes`` so the group set matches +the provisioned include/credential closure. + +Node base names are the SPOT in default.env (shared with 00_topology.sh); +only the SWARM_NAME prefix is applied here so host names match the +containers. The env get() keeps SWARM_NAME import-safe; main() enforces it +at run time. + Inputs (env): ``APP_ID``, ``INV_PATH`` (default ``/tmp/inv/devices.yml``). +Optional ``INFINITO_APP_VARIANTS`` (consumed by ``derive_includes``). """ from __future__ import annotations @@ -13,13 +22,10 @@ import os from pathlib import Path from utils import PROJECT_ROOT -from utils.cache.applications import get_merged_applications from utils.cache.yaml import dump_yaml, load_yaml_any from utils.env.parser import parse_static_env -from utils.roles.applications.in_group_deps import applications_if_group_and_all_deps from utils.roles.meta_lookup import get_role_default_placement - -_ROLES_DIR = PROJECT_ROOT / "roles" +from utils.tests.swarm.derive_includes import derive_includes _DOCKER_VARS: dict[str, str] = { "ansible_connection": "docker", @@ -27,9 +33,6 @@ _DOCKER_VARS: dict[str, str] = { "ansible_user": "root", } -# Node base names are the SPOT in default.env (shared with 00_topology.sh); only the -# SWARM_NAME prefix is applied here so host names match the containers. The get() -# keeps SWARM_NAME import-safe; main() enforces it at run time. _NAMES = parse_static_env(PROJECT_ROOT / "default.env") _PREFIX = f"{os.environ['SWARM_NAME']}-" if os.environ.get("SWARM_NAME") else "" _MANAGER = f"{_PREFIX}{_NAMES['INFINITO_SWARM_MGR_NAME']}" @@ -42,8 +45,9 @@ _NFS_SERVER = f"{_PREFIX}{_NAMES['INFINITO_SWARM_NFS_NAME']}" def _host_topology(app_id: str) -> list[tuple[str, str]]: app_hosts: list[tuple[str, str]] = [(app_id, _MANAGER)] - # svc-swarm-manager is the IS_STACK_HOST marker group; leaking workers into it - # flips IS_STACK_HOST true on workers and skips the CA fetch. Keep it manager-only. + # Exception: svc-swarm-manager is the IS_STACK_HOST marker group; leaking + # workers into it flips IS_STACK_HOST true on workers and skips the CA + # fetch. Keep it manager-only. if ( app_id != "svc-swarm-manager" and get_role_default_placement(app_id) != "manager" @@ -61,16 +65,9 @@ def _host_topology(app_id: str) -> list[tuple[str, str]]: def _default_placement_dep_groups(app_id: str) -> list[tuple[str, str]]: - applications = get_merged_applications(roles_dir=str(_ROLES_DIR)) - needed = applications_if_group_and_all_deps( - applications, - [app_id], - project_root=str(PROJECT_ROOT), - roles_dir=str(_ROLES_DIR), - ) return [ (role_name, _MANAGER) - for role_name in sorted(needed) + for role_name in derive_includes(app_id) if get_role_default_placement(role_name) == "manager" ]