from __future__ import annotations import argparse import json import os import subprocess from typing import TYPE_CHECKING, Any from cli.administration.inventory.provision.services_disabler import ( find_provider_roles, parse_services_disabled, ) from . import PROJECT_ROOT from .common import ( make_compose, resolve_container, ) from .inventory import plan_dev_inventory_matrix from .variant_select import add_variant_args, apply_variant_filter if TYPE_CHECKING: from collections.abc import Mapping def _env_full_cycle() -> bool: return os.environ.get("full_cycle", "").strip().lower() == "true" def _run_deploy( compose, *, deploy_ids: list[str], debug: bool, passthrough: list[str], inventory_dir: str, container_name: str, extra_ansible_vars: Mapping[str, Any] | None = None, ) -> int: inv_root = str(inventory_dir).rstrip("/") inv_file = f"{inv_root}/devices.yml" pw_file = f"{inv_root}/.password" cmd = [ "python3", "-m", "cli.administration.deploy.dedicated", inv_file, "-p", pw_file, "-vv", "--assert", "true", "--diff", "--id", *deploy_ids, ] if debug: cmd.insert(cmd.index("--diff") + 1, "--debug") if extra_ansible_vars: for key, value in extra_ansible_vars.items(): cmd.extend(["-e", f"{key}={json.dumps(value)}"]) if passthrough: cmd.extend(passthrough) extra_env: dict[str, str] = { "ANSIBLE_FORCE_COLOR": "1", "PY_COLORS": "1", "TERM": "xterm-256color", } services_disabled = os.environ.get("disable", "") if services_disabled: extra_env["disable"] = services_disabled ansible_log_path = ( os.environ.get("ANSIBLE_LOG_PATH") or "/tmp/infinito-deploy.log" # noqa: S108 ) extra_env["ANSIBLE_LOG_PATH"] = ansible_log_path for key in ( "GH_TOKEN", "GITHUB_TOKEN", "GITHUB_REPOSITORY_OWNER", "GITHUB_REPOSITORY", "INFINITO_IMAGE_TAG", "INFINITO_GHCR_MIRROR_PREFIX", ): val = os.environ.get(key) if val: extra_env[key] = val r = compose.exec( cmd, check=False, live=True, extra_env=extra_env, ) return int(r.returncode) def _maybe_recover_drill(compose, plan_index: int) -> None: """Verify recovery between PASS 1 and PASS 2 of the first round: seed a backup tree and `recover full` it back on this single host. Gated by INFINITO_RECOVER_DRILL (off by default); raises on drill failure so the deploy fails fast before the async pass.""" if plan_index != 0: return if (os.environ.get("INFINITO_RECOVER_DRILL") or "").strip().lower() != "true": return print("=== recover drill (backup/recover verification between passes) ===") compose.exec( ["bash", "/opt/src/infinito/scripts/tests/deploy/ci/recover_drill.sh"], extra_env={"INFINITO_REPO_ROOT": "/opt/src/infinito"}, live=True, ) def _purge_app_entities(*, container: str, app_ids: list[str]) -> None: """Run the per-app cleanup script for every app from the previous matrix-deploy round before the next round starts. `scripts/tests/deploy/local/purge/entity.sh` removes the application's containers, networks, and Ansible-managed state on the host so the next round boots from a clean slate. Failures are surfaced (the matrix MUST NOT silently mix variant state across rounds). """ if not app_ids: return repo_root = PROJECT_ROOT purge_script = ( repo_root / "scripts" / "tests" / "deploy" / "local" / "purge" / "entity.sh" ) env = os.environ.copy() env["apps"] = ",".join(app_ids) env["INFINITO_CONTAINER"] = container print( "=== matrix-deploy: purging entities between rounds for " f"{', '.join(app_ids)} ===" ) subprocess.run( ["bash", str(purge_script)], cwd=str(repo_root), env=env, check=True, ) def add_parser(sub: argparse._SubParsersAction) -> None: p = sub.add_parser( "deploy", help="Run deploy inside the infinito container (requires inventory)." ) p.add_argument( "--inventory-dir", default=os.environ.get("INFINITO_INVENTORY_DIR"), required=os.environ.get("INFINITO_INVENTORY_DIR") is None, help=( "Inventory directory base (default: $INFINITO_INVENTORY_DIR). When the " "primary apps declare more than one matrix-deploy variant, the " "wrapper iterates the sibling folders `