diff --git a/cli/create/inventory/services_disabler.py b/cli/create/inventory/services_disabler.py index 97aa615a91..463613ee8e 100644 --- a/cli/create/inventory/services_disabler.py +++ b/cli/create/inventory/services_disabler.py @@ -8,6 +8,16 @@ import yaml from ruamel.yaml import YAML from ruamel.yaml.comments import CommentedMap +from utils.service_registry import ( + build_service_registry_from_roles_dir, + canonical_service_key, + equivalent_service_keys, +) + + +class ServicesDisabledConflictError(RuntimeError): + """Raised when SERVICES_DISABLED conflicts with an existing inventory.""" + def parse_services_disabled(env_value: str) -> list[str]: """Parse a space- or comma-separated list of service names.""" @@ -210,3 +220,115 @@ def apply_services_disabled_from_env( apply_services_disabled( host_vars_file, services, roles_dir=roles_dir, inventory_file=inventory_file ) + + +def _load_yaml_mapping(path: Path) -> dict: + if not path.exists(): + return {} + with path.open("r", encoding="utf-8") as f: + data = yaml.safe_load(f) or {} + return data if isinstance(data, dict) else {} + + +def _inventory_application_ids(inventory_file: Path) -> set[str]: + doc = _load_yaml_mapping(inventory_file) + all_section = doc.get("all") or {} + children = all_section.get("children") or {} + if not isinstance(children, dict): + return set() + return {app_id for app_id, value in children.items() if isinstance(value, dict)} + + +def find_services_disabled_conflicts( + inventory_dir: Path, + services: list[str], + roles_dir: Path, +) -> list[str]: + """ + Return human-readable conflicts when SERVICES_DISABLED disagrees with the + existing inventory/host_vars state. + """ + if not services: + return [] + + inventory_file = inventory_dir / "devices.yml" + deployed_app_ids = _inventory_application_ids(inventory_file) + host_vars_dir = inventory_dir / "host_vars" + host_vars_files = ( + sorted(host_vars_dir.glob("*.yml")) if host_vars_dir.is_dir() else [] + ) + service_registry = build_service_registry_from_roles_dir(roles_dir) + + conflicts: list[str] = [] + for service in services: + primary_service = ( + canonical_service_key(service_registry, service) + if service in service_registry + else service + ) + equivalent_keys = ( + equivalent_service_keys(service_registry, primary_service) + if primary_service in service_registry + else [service] + ) + provider_role = (service_registry.get(primary_service) or {}).get("role") + if isinstance(provider_role, str) and provider_role in deployed_app_ids: + conflicts.append( + f"service '{service}' is disabled, but provider role " + f"'{provider_role}' is still active in {inventory_file}" + ) + + for host_vars_file in host_vars_files: + doc = _load_yaml_mapping(host_vars_file) + applications = doc.get("applications") or {} + if not isinstance(applications, dict): + continue + for app_id in sorted(deployed_app_ids): + app_conf = applications.get(app_id) or {} + compose = app_conf.get("compose") or {} + service_map = compose.get("services") or {} + if not isinstance(service_map, dict): + continue + for service_key in equivalent_keys: + service_conf = service_map.get(service_key) or {} + if not isinstance(service_conf, dict): + continue + enabled = bool(service_conf.get("enabled", False)) + shared = bool(service_conf.get("shared", False)) + if enabled or shared: + conflicts.append( + f"service '{service}' is disabled, but " + f"{host_vars_file}:{app_id}.compose.services.{service_key} " + f"still has enabled={enabled}, shared={shared}" + ) + + return conflicts + + +def assert_services_disabled_inventory_consistency_from_env( + inventory_dir: Path, + roles_dir: Path, +) -> None: + """Fail fast when SERVICES_DISABLED conflicts with the existing inventory.""" + raw = os.environ.get("SERVICES_DISABLED", "").strip() + if not raw: + return + + services = parse_services_disabled(raw) + conflicts = find_services_disabled_conflicts( + inventory_dir=inventory_dir, + services=services, + roles_dir=roles_dir, + ) + if not conflicts: + return + + details = "\n - ".join(conflicts) + raise ServicesDisabledConflictError( + "SERVICES_DISABLED conflicts with the current inventory state.\n" + f"SERVICES_DISABLED={raw!r}\n" + "Conflicts:\n" + f" - {details}\n" + "Recreate or clean the inventory, or remove the conflicting service from " + "SERVICES_DISABLED." + ) diff --git a/cli/deploy/dedicated/runner.py b/cli/deploy/dedicated/runner.py index 60171bddeb..2e5e45035b 100644 --- a/cli/deploy/dedicated/runner.py +++ b/cli/deploy/dedicated/runner.py @@ -4,8 +4,14 @@ import datetime import os import subprocess import sys +from pathlib import Path from typing import Any, Dict, List, Optional +from cli.create.inventory.services_disabler import ( + ServicesDisabledConflictError, + assert_services_disabled_inventory_consistency_from_env, +) + from .proc import run, run_make @@ -47,7 +53,19 @@ def run_ansible_playbook( print("\n🛠️ Build skipped (--skip-build)\n") # --------------------------------------------------------- - # 3) Inventory Validation Phase + # 3) SERVICES_DISABLED consistency guard + # --------------------------------------------------------- + try: + assert_services_disabled_inventory_consistency_from_env( + inventory_dir=Path(inventory).resolve().parent, + roles_dir=Path(repo_root).resolve() / "roles", + ) + except ServicesDisabledConflictError as exc: + print(f"\n[ERROR] {exc}\n", file=sys.stderr) + sys.exit(1) + + # --------------------------------------------------------- + # 4) Inventory Validation Phase # --------------------------------------------------------- if modes.get("MODE_ASSERT", None) is False: print("\n🔍 Inventory assertion explicitly disabled (MODE_ASSERT=false)\n") @@ -67,7 +85,7 @@ def run_ansible_playbook( sys.exit(1) # --------------------------------------------------------- - # 4) Build ansible-playbook command + # 5) Build ansible-playbook command # --------------------------------------------------------- cmd: List[str] = ["ansible-playbook", "-i", inventory, playbook_path] diff --git a/cli/deploy/development/exec.py b/cli/deploy/development/exec.py index 7675022e95..c86da35f30 100644 --- a/cli/deploy/development/exec.py +++ b/cli/deploy/development/exec.py @@ -31,5 +31,10 @@ def handler(args: argparse.Namespace) -> int: if not cmd: raise SystemExit("exec requires a command (e.g. exec -- sh -lc 'whoami')") - r = compose.exec(cmd, check=False) + extra_env: dict[str, str] = {} + services_disabled = os.environ.get("SERVICES_DISABLED", "") + if services_disabled: + extra_env["SERVICES_DISABLED"] = services_disabled + + r = compose.exec(cmd, check=False, extra_env=extra_env or None) return int(r.returncode) diff --git a/scripts/tests/deploy/local/deploy/reuse-kept-app.sh b/scripts/tests/deploy/local/deploy/reuse-kept-app.sh index 1d33728fdb..1948ffe4e2 100755 --- a/scripts/tests/deploy/local/deploy/reuse-kept-app.sh +++ b/scripts/tests/deploy/local/deploy/reuse-kept-app.sh @@ -38,7 +38,9 @@ esac echo "=== rapid deploy: type=${TEST_DEPLOY_TYPE} app=${APPS} container=${INFINITO_CONTAINER} debug=${DEBUG} ===" echo "inventory_dir=${INVENTORY_DIR}" -docker exec "${INFINITO_CONTAINER}" bash -c " +docker exec \ + -e SERVICES_DISABLED="${SERVICES_DISABLED:-}" \ + "${INFINITO_CONTAINER}" bash -c " set -euo pipefail cd /opt/src/infinito diff --git a/tests/unit/cli/create/inventory/test_services_disabler.py b/tests/unit/cli/create/inventory/test_services_disabler.py index 2473126d6c..8fac1e0964 100644 --- a/tests/unit/cli/create/inventory/test_services_disabler.py +++ b/tests/unit/cli/create/inventory/test_services_disabler.py @@ -12,7 +12,9 @@ from ruamel.yaml import YAML from cli.create.inventory.services_disabler import ( apply_services_disabled, apply_services_disabled_from_env, + assert_services_disabled_inventory_consistency_from_env, find_provider_roles, + find_services_disabled_conflicts, parse_services_disabled, remove_roles_from_inventory, ) @@ -175,10 +177,15 @@ class TestApplyServicesDisabled(unittest.TestCase): def _make_role(self, role_name: str, services: dict) -> None: role_dir = self.roles_dir / role_name (role_dir / "config").mkdir(parents=True) + (role_dir / "vars").mkdir(parents=True) with (role_dir / "config" / "main.yml").open("w") as f: import yaml yaml.dump({"compose": {"services": services}}, f) + with (role_dir / "vars" / "main.yml").open("w") as f: + import yaml + + yaml.dump({"application_id": role_name}, f) def test_disables_service_in_host_vars_and_removes_from_inventory(self): self._write_host_vars( @@ -383,10 +390,15 @@ class TestApplyServicesDisabledFromEnv(unittest.TestCase): def _make_role(self, role_name: str, services: dict) -> None: role_dir = self.roles_dir / role_name (role_dir / "config").mkdir(parents=True) + (role_dir / "vars").mkdir(parents=True) with (role_dir / "config" / "main.yml").open("w") as f: import yaml yaml.dump({"compose": {"services": services}}, f) + with (role_dir / "vars" / "main.yml").open("w") as f: + import yaml + + yaml.dump({"application_id": role_name}, f) def test_reads_env_var(self): self._write( @@ -418,5 +430,138 @@ class TestApplyServicesDisabledFromEnv(unittest.TestCase): self.assertEqual(self._read(), {"applications": {}}) +class TestServicesDisabledConflicts(unittest.TestCase): + def setUp(self): + self.tmp = TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + self.roles_dir = self.root / "roles" + self.roles_dir.mkdir() + self.inventory_dir = self.root / "inventory" + self.inventory_dir.mkdir() + self.inventory_file = self.inventory_dir / "devices.yml" + self.host_vars_dir = self.inventory_dir / "host_vars" + self.host_vars_dir.mkdir() + self.host_vars_file = self.host_vars_dir / "localhost.yml" + self.yaml_rt = YAML(typ="rt") + self.yaml_rt.preserve_quotes = True + + def _make_role(self, role_name: str, services: dict) -> None: + role_dir = self.roles_dir / role_name + (role_dir / "config").mkdir(parents=True) + (role_dir / "vars").mkdir(parents=True) + with (role_dir / "config" / "main.yml").open("w") as f: + import yaml + + yaml.dump({"compose": {"services": services}}, f) + with (role_dir / "vars" / "main.yml").open("w") as f: + import yaml + + yaml.dump({"application_id": role_name}, f) + + def _write_inventory(self, data: dict) -> None: + with self.inventory_file.open("w") as f: + self.yaml_rt.dump(data, f) + + def _write_host_vars(self, data: dict) -> None: + with self.host_vars_file.open("w") as f: + self.yaml_rt.dump(data, f) + + def test_reports_provider_role_conflict_for_provides_alias(self): + self._make_role( + "web-app-mailu", + {"mailu": {"image": "mailu", "provides": "email", "shared": True}}, + ) + self._make_role( + "web-app-fider", + {"email": {"enabled": False, "shared": False}}, + ) + self._write_inventory( + { + "all": { + "children": { + "web-app-mailu": {"hosts": {"localhost": {}}}, + "web-app-fider": {"hosts": {"localhost": {}}}, + } + } + } + ) + self._write_host_vars( + { + "applications": { + "web-app-fider": { + "compose": { + "services": {"email": {"enabled": False, "shared": False}} + } + } + } + } + ) + + conflicts = find_services_disabled_conflicts( + inventory_dir=self.inventory_dir, + services=["email"], + roles_dir=self.roles_dir, + ) + + self.assertEqual(len(conflicts), 1) + self.assertIn("provider role 'web-app-mailu'", conflicts[0]) + + def test_reports_enabled_service_conflict_for_deployed_app(self): + self._make_role( + "web-app-fider", + {"email": {"enabled": True, "shared": True}}, + ) + self._write_inventory( + {"all": {"children": {"web-app-fider": {"hosts": {"localhost": {}}}}}} + ) + self._write_host_vars( + { + "applications": { + "web-app-fider": { + "compose": { + "services": {"email": {"enabled": True, "shared": True}} + } + } + } + } + ) + + conflicts = find_services_disabled_conflicts( + inventory_dir=self.inventory_dir, + services=["email"], + roles_dir=self.roles_dir, + ) + + self.assertEqual(len(conflicts), 1) + self.assertIn("enabled=True, shared=True", conflicts[0]) + + def test_assert_from_env_noops_when_inventory_is_consistent(self): + self._make_role( + "web-app-fider", + {"email": {"enabled": False, "shared": False}}, + ) + self._write_inventory( + {"all": {"children": {"web-app-fider": {"hosts": {"localhost": {}}}}}} + ) + self._write_host_vars( + { + "applications": { + "web-app-fider": { + "compose": { + "services": {"email": {"enabled": False, "shared": False}} + } + } + } + } + ) + + with unittest.mock.patch.dict(os.environ, {"SERVICES_DISABLED": "email"}): + assert_services_disabled_inventory_consistency_from_env( + inventory_dir=self.inventory_dir, + roles_dir=self.roles_dir, + ) + + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/cli/deploy/dedicated/test_runner.py b/tests/unit/cli/deploy/dedicated/test_runner.py index 396955209c..9451db88e7 100644 --- a/tests/unit/cli/deploy/dedicated/test_runner.py +++ b/tests/unit/cli/deploy/dedicated/test_runner.py @@ -4,6 +4,7 @@ import subprocess import unittest from typing import Any, Dict, List, Tuple +from cli.create.inventory.services_disabler import ServicesDisabledConflictError from cli.deploy.dedicated import runner @@ -63,20 +64,25 @@ class TestRunAnsiblePlaybook(unittest.TestCase): allowed_apps = ["web-app-foo", "web-app-bar"] password_file = "/etc/inventories/github-ci/.password" - runner.run_ansible_playbook( - repo_root=repo_root, - playbook_path=playbook_path, - inventory_validator_path=inventory_validator_path, - inventory=inventory_path, - modes=modes, - limit=limit, - allowed_applications=allowed_apps, - password_file=password_file, - verbose=1, - skip_build=False, - diff=True, - ansible_args=None, - ) + with unittest.mock.patch( + "cli.deploy.dedicated.runner.assert_services_disabled_inventory_consistency_from_env" + ) as mock_services_disabled_guard: + runner.run_ansible_playbook( + repo_root=repo_root, + playbook_path=playbook_path, + inventory_validator_path=inventory_validator_path, + inventory=inventory_path, + modes=modes, + limit=limit, + allowed_applications=allowed_apps, + password_file=password_file, + verbose=1, + skip_build=False, + diff=True, + ansible_args=None, + ) + + mock_services_disabled_guard.assert_called_once() def was_called(cmd: List[str]) -> bool: return any(call_cmd == cmd for call_cmd, _kw in calls) @@ -178,20 +184,23 @@ class TestRunAnsiblePlaybook(unittest.TestCase): "MODE_DEBUG=true", ] - runner.run_ansible_playbook( - repo_root=repo_root, - playbook_path=playbook_path, - inventory_validator_path=inventory_validator_path, - inventory=inventory_path, - modes=modes, - limit=None, - allowed_applications=["web-app-foo"], - password_file=None, - verbose=0, - skip_build=True, - diff=False, - ansible_args=passthrough, - ) + with unittest.mock.patch( + "cli.deploy.dedicated.runner.assert_services_disabled_inventory_consistency_from_env" + ): + runner.run_ansible_playbook( + repo_root=repo_root, + playbook_path=playbook_path, + inventory_validator_path=inventory_validator_path, + inventory=inventory_path, + modes=modes, + limit=None, + allowed_applications=["web-app-foo"], + password_file=None, + verbose=0, + skip_build=True, + diff=False, + ansible_args=passthrough, + ) last_cmd, _last_kw = calls[-1] self.assertEqual(last_cmd[0], "ansible-playbook") @@ -222,21 +231,24 @@ class TestRunAnsiblePlaybook(unittest.TestCase): "MODE_DEBUG": False, } - with self.assertRaises(SystemExit) as ctx: - runner.run_ansible_playbook( - repo_root=repo_root, - playbook_path=playbook_path, - inventory_validator_path=inventory_validator_path, - inventory="/etc/inventories/github-ci/devices.yml", - modes=modes, - limit=None, - allowed_applications=None, - password_file=None, - verbose=0, - skip_build=True, - diff=False, - ansible_args=None, - ) + with unittest.mock.patch( + "cli.deploy.dedicated.runner.assert_services_disabled_inventory_consistency_from_env" + ): + with self.assertRaises(SystemExit) as ctx: + runner.run_ansible_playbook( + repo_root=repo_root, + playbook_path=playbook_path, + inventory_validator_path=inventory_validator_path, + inventory="/etc/inventories/github-ci/devices.yml", + modes=modes, + limit=None, + allowed_applications=None, + password_file=None, + verbose=0, + skip_build=True, + diff=False, + ansible_args=None, + ) self.assertEqual(ctx.exception.code, 4) @@ -260,6 +272,42 @@ class TestRunAnsiblePlaybook(unittest.TestCase): "Inventory validation should be skipped when MODE_ASSERT is False", ) + @unittest.mock.patch("subprocess.run") + def test_run_ansible_playbook_fails_early_on_services_disabled_conflict( + self, mock_run + ): + calls: List[Tuple[List[str], Dict[str, Any]]] = [] + mock_run.side_effect = self._fake_run_side_effect(calls, ansible_rc=0) + + with unittest.mock.patch( + "cli.deploy.dedicated.runner.assert_services_disabled_inventory_consistency_from_env", + side_effect=ServicesDisabledConflictError("boom"), + ): + with self.assertRaises(SystemExit) as ctx: + runner.run_ansible_playbook( + repo_root="/repo", + playbook_path="/repo/playbook.yml", + inventory_validator_path="/repo/cli/validate/inventory/__main__.py", + inventory="/etc/inventories/github-ci/devices.yml", + modes={ + "MODE_CLEANUP": False, + "MODE_ASSERT": True, + "MODE_DEBUG": False, + }, + limit=None, + allowed_applications=None, + password_file=None, + verbose=0, + skip_build=True, + diff=False, + ansible_args=None, + ) + + self.assertEqual(ctx.exception.code, 1) + self.assertFalse( + any(call_cmd and call_cmd[0] == "ansible-playbook" for call_cmd, _ in calls) + ) + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/cli/deploy/development/test_exec.py b/tests/unit/cli/deploy/development/test_exec.py new file mode 100644 index 0000000000..ac43a8df0c --- /dev/null +++ b/tests/unit/cli/deploy/development/test_exec.py @@ -0,0 +1,60 @@ +from __future__ import annotations + +import argparse +import os +import unittest +import unittest.mock + +from cli.deploy.development import exec as exec_cmd + + +class TestDevelopmentExec(unittest.TestCase): + def test_handler_forwards_services_disabled(self): + compose = unittest.mock.Mock() + compose.exec.return_value.returncode = 0 + + args = argparse.Namespace(distro="debian", cmd=["--", "sh", "-lc", "true"]) + + with unittest.mock.patch( + "cli.deploy.development.exec.make_compose", + return_value=compose, + ): + with unittest.mock.patch.dict( + os.environ, {"SERVICES_DISABLED": "email"}, clear=False + ): + rc = exec_cmd.handler(args) + + self.assertEqual(rc, 0) + compose.exec.assert_called_once_with( + ["sh", "-lc", "true"], + check=False, + extra_env={"SERVICES_DISABLED": "email"}, + ) + + def test_handler_omits_extra_env_when_services_disabled_unset(self): + compose = unittest.mock.Mock() + compose.exec.return_value.returncode = 0 + + args = argparse.Namespace(distro="debian", cmd=["echo", "hi"]) + + env = {k: v for k, v in os.environ.items() if k != "SERVICES_DISABLED"} + with unittest.mock.patch( + "cli.deploy.development.exec.make_compose", + return_value=compose, + ): + with unittest.mock.patch.dict(os.environ, env, clear=True): + rc = exec_cmd.handler(args) + + self.assertEqual(rc, 0) + compose.exec.assert_called_once_with( + ["echo", "hi"], check=False, extra_env=None + ) + + def test_handler_requires_command(self): + args = argparse.Namespace(distro="debian", cmd=[]) + with self.assertRaises(SystemExit): + exec_cmd.handler(args) + + +if __name__ == "__main__": + unittest.main()