mirror of
https://github.com/kevinveenbirkenbach/computer-playbook.git
synced 2026-11-08 11:46:35 +00:00
Single SPOT for matrix-deploy topology
=======================================
Before this change two paths derived the deploy plan from different
sources and could disagree:
* Group inclusion (`--include` / `group_names`): driven by
`cli.meta.applications.resolution.combined.CombinedResolver`,
which read each role's `meta/services.yml` raw and ignored
`meta/variants.yml` entirely. A variant that flipped
`services.<X>.enabled` to a literal `true` did NOT pull `<X>`'s
provider role into the deploy plan.
* Inventory bake (`host_vars/applications.<app>.*`): driven by the
variant-aware payload merge in `cli.deploy.development.inventory`,
so the role saw the variant-merged services map at deploy time.
The split surfaced concretely for `web-app-wordpress` variant 0
(`services.discourse.enabled: true` in `meta/variants.yml`): the
inventory baked `discourse.enabled = true`, the wp-discourse plugin
task gate fired, and the install loop tried `docker exec discourse`
against a container the variant-blind resolver had never pulled.
This commit collapses both consumers onto the same per-round,
variant-merged services map. The variant-aware resolver (Phase 1+2)
is the additive plumbing, but the deploy/init wiring (Phase 3-5) is
what actually changes behaviour at runtime.
Variant-aware resolver (Phase 1+2)
----------------------------------
`role_introspection.load_shared_service_roles_for_app` accepts a
`services_override` kwarg; `CombinedResolver.__init__` accepts a
`{role_name: services_dict}` map and routes it through the loader.
A `CombinedResolver` instance is round-specific when overrides are
supplied — its per-role edge cache is variant-resolved, do NOT reuse
across rounds. The combined-resolver CLI gains
`--services-overrides <path>`.
`cli.deploy.development.deps.resolve_run_after` threads the
in-container path of the overrides JSON into the resolver
invocation.
Per-round include planner (Phase 3)
-----------------------------------
`cli.deploy.development.inventory.plan_dev_inventory_matrix` now
takes `primary_apps` (just the user-named apps) instead of a
pre-resolved `include` list and returns a 4-tuple per round
`(round_index, inv_dir, round_variants, include_R)`. Per round it:
1. Computes `round_variants` clamped to each primary's variant
count.
2. Builds variant-merged services overrides for every role with a
`meta/variants.yml`, picking that role's variant for the round
(clamped) — so transitive deps with their own variants follow
the round.
3. Runs `CombinedResolver(services_overrides=...)` per primary and
unions the result with the primary apps in user order.
4. Extends `round_variants` with the discovered deps' clamped
variant indices so the deploy step's per-round purge logic stays
accurate.
`build_dev_inventory_matrix` keeps its name but signature changes:
it now takes `primary_apps` and an optional `include_filter` for
SERVICES_DISABLED-style consumer filters.
Init / deploy wiring (Phase 4-5)
--------------------------------
`init.py` and `deploy.py` consume the per-round `include_R`
directly, drop the old `resolve_deploy_ids_for_apps` pre-resolution
step, and apply the SERVICES_DISABLED provider filter on the
include set so the inventory `--include` flag and the final ansible
deploy ids stay in lockstep.
Behaviour invariance for non-variant roles
------------------------------------------
Apps with no `meta/variants.yml`, or without a `services.<X>.enabled`
override on any variant, behave identically to before:
* The override map for those roles is empty — resolver falls
through to the disk-only path.
* Per-round `include_R` collapses to the same set every round.
* Inventory bake outputs the same `applications.<app>.*` shape.
The behaviour change is scoped to roles that legitimately use
variants to flip topology. In the current repo only
`web-app-wordpress` is affected (variant 0 pulls
`web-app-discourse` in; variant 1 leaves it out, exercising the
multisite-without-discourse path).
Test surface
------------
* `tests/unit/cli/deploy/development/test_inventory.py` updated
for the new planner signature, mocking
`_resolve_round_include` / `_build_services_overrides_for_round`
so the planner's tuple shape is asserted independently of the
live resolver.
* `tests/unit/cli/deploy/development/test_matrix_deploy.py` adds a
`_entry()` helper that defaults `include` to the keys of
`round_variants`, so existing fixtures stay terse — round 0 of
the deploy loop deploys whatever is in `include_R`, and the
variant-aware planner naturally emits the same set.
* `tests/unit/utils/cache/test_data.py` pins the planner contract
(`primary_apps=`, 4-tuple plan entries with `include_R`).
* `tests/utils/__init__.py` added so the
`tests.lint.filesystem.test_init_files` lint test passes
end-to-end (the directory existed in the tree without an
__init__.py and tripped the lint).
Verification
------------
* `make test` green (162 tests, 1 skipped) on the merged tree.
* `make deploy-fresh-kept-apps APPS="web-app-wordpress"
FULL_CYCLE=true SERVICES_DISABLED="matomo,email"` end-to-end:
round 0 (variant 0, single-site + Discourse integration) and
round 1 (variant 1, multisite) each ran PASS 1 (sync) and PASS 2
(async), all four passes with `failed=0 rescued=0`. Round 0's
per-round include contained `web-app-discourse`; round 1's did
not — exactly the variant-driven topology the resolver is
supposed to produce.
The unrelated Joomla CLI install race (CI run 25079786137 `Deploy
web-app-joomla`) is parked separately as infinito-nexus/core#209;
its candidate fix is in that issue body, not in this commit.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
206 lines
7.0 KiB
Python
206 lines
7.0 KiB
Python
# cli/deploy/development/init.py
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import json
|
|
import os
|
|
from typing import Any, Dict
|
|
|
|
from cli.create.inventory.services_disabler import (
|
|
find_provider_roles,
|
|
parse_services_disabled,
|
|
)
|
|
|
|
from .common import make_compose
|
|
from .inventory import (
|
|
DevInventorySpec,
|
|
build_dev_inventory,
|
|
filter_plan_to_variant,
|
|
plan_dev_inventory_matrix,
|
|
)
|
|
from .storage import detect_storage_constrained
|
|
from ...meta.runtime import detect_runtime
|
|
|
|
|
|
def add_parser(sub: argparse._SubParsersAction) -> None:
|
|
p = sub.add_parser(
|
|
"init",
|
|
help="Create development inventory inside the infinito container.",
|
|
)
|
|
p.add_argument(
|
|
"--inventory-dir",
|
|
default=os.environ.get("INVENTORY_DIR"),
|
|
required=os.environ.get("INVENTORY_DIR") is None,
|
|
help=(
|
|
"Inventory directory base (default: $INVENTORY_DIR). "
|
|
"When the included apps declare more than one matrix-deploy "
|
|
"variant, sibling folders `<dir>-0`, `<dir>-1`, ... are "
|
|
"created; otherwise the directory is used as-is."
|
|
),
|
|
)
|
|
|
|
g = p.add_mutually_exclusive_group(required=True)
|
|
g.add_argument(
|
|
"--apps",
|
|
help="One or more application ids (will include run_after deps automatically).",
|
|
)
|
|
g.add_argument(
|
|
"--include",
|
|
help="Comma-separated list of application ids to include (no deps resolution).",
|
|
)
|
|
|
|
p.add_argument(
|
|
"--threshold-gib",
|
|
type=int,
|
|
default=100,
|
|
help="Free-space threshold (GiB) below which STORAGE_CONSTRAINED is enabled (default: 100).",
|
|
)
|
|
p.add_argument(
|
|
"--force-storage-constrained",
|
|
choices=["true", "false"],
|
|
default=None,
|
|
help="Override storage detection explicitly.",
|
|
)
|
|
p.add_argument(
|
|
"--vars",
|
|
default=None,
|
|
help="JSON object merged into inventory variables (overrides win).",
|
|
)
|
|
p.add_argument(
|
|
"--variant",
|
|
type=int,
|
|
default=_env_variant(),
|
|
help=(
|
|
"Pin the matrix init to a single round (zero-based index). "
|
|
"Useful when only one variant of a multi-variant app needs to "
|
|
"be (re-)materialised. Defaults to the VARIANT environment "
|
|
"variable when set, otherwise full-matrix mode."
|
|
),
|
|
)
|
|
p.set_defaults(_handler=handler)
|
|
|
|
|
|
def _env_variant() -> int | None:
|
|
raw = os.environ.get("VARIANT", "").strip()
|
|
if not raw:
|
|
return None
|
|
try:
|
|
return int(raw)
|
|
except ValueError:
|
|
raise SystemExit(
|
|
f"VARIANT environment variable must be an integer, got {raw!r}"
|
|
)
|
|
|
|
|
|
def handler(args: argparse.Namespace) -> int:
|
|
compose = make_compose()
|
|
|
|
# `primary_apps` is the user-facing app list before transitive resolution.
|
|
# The variant-aware planner expands each round's full include set
|
|
# itself (services edges depend on variant-merged services maps), so
|
|
# init no longer pre-resolves run_after / service deps here.
|
|
if args.apps:
|
|
primary_apps = [
|
|
x.strip() for x in args.apps.replace(",", " ").split() if x.strip()
|
|
]
|
|
else:
|
|
primary_apps = [x.strip() for x in (args.include or "").split(",") if x.strip()]
|
|
|
|
if not primary_apps:
|
|
raise SystemExit("Primary app list is empty")
|
|
|
|
# SERVICES_DISABLED removes provider roles from the inventory at
|
|
# `infinito create inventory` time anyway, so do the same filter on
|
|
# the primary list here. Otherwise the variant-aware resolver would
|
|
# still pull a disabled provider in via service edges, only to have
|
|
# the inventory step strip it back out — leaving the round's
|
|
# include list inconsistent with what the inventory actually
|
|
# contains.
|
|
raw_disabled = os.environ.get("SERVICES_DISABLED", "").strip()
|
|
disabled_app_ids: set[str] = set()
|
|
if raw_disabled:
|
|
services = parse_services_disabled(raw_disabled)
|
|
roles_dir = compose.repo_root / "roles"
|
|
provider_map = find_provider_roles(services, roles_dir)
|
|
disabled_app_ids = set(provider_map.values())
|
|
primary_apps = [a for a in primary_apps if a not in disabled_app_ids]
|
|
|
|
if not primary_apps:
|
|
raise SystemExit(
|
|
"All primary apps disabled by SERVICES_DISABLED — nothing to initialise"
|
|
)
|
|
|
|
extra_vars: Dict[str, Any] | None = None
|
|
if args.vars is not None:
|
|
try:
|
|
parsed = json.loads(args.vars)
|
|
except Exception as exc:
|
|
raise SystemExit(f"--vars must be valid JSON: {exc}")
|
|
if not isinstance(parsed, dict):
|
|
raise SystemExit("--vars must be a JSON object")
|
|
extra_vars = parsed
|
|
|
|
if args.force_storage_constrained is not None:
|
|
storage_constrained = args.force_storage_constrained == "true"
|
|
else:
|
|
storage_constrained = detect_storage_constrained(
|
|
compose, threshold_gib=int(args.threshold_gib)
|
|
)
|
|
|
|
plan = plan_dev_inventory_matrix(
|
|
roles_dir=str(compose.repo_root / "roles"),
|
|
primary_apps=primary_apps,
|
|
base_inventory_dir=str(args.inventory_dir),
|
|
)
|
|
try:
|
|
plan = filter_plan_to_variant(plan, args.variant)
|
|
except ValueError as exc:
|
|
raise SystemExit(f"--variant: {exc}")
|
|
|
|
runtime = os.environ.get("RUNTIME") or detect_runtime()
|
|
services_disabled = os.environ.get("SERVICES_DISABLED", "")
|
|
for _round_index, inv_dir, round_variants, include_R in plan:
|
|
round_include = tuple(
|
|
role for role in include_R if role not in disabled_app_ids
|
|
)
|
|
if not round_include:
|
|
print(
|
|
f">>> Skipping inventory at {inv_dir}: include set is empty "
|
|
"after SERVICES_DISABLED filter"
|
|
)
|
|
continue
|
|
spec = DevInventorySpec(
|
|
inventory_dir=inv_dir,
|
|
include=round_include,
|
|
storage_constrained=storage_constrained,
|
|
runtime=runtime,
|
|
extra_vars=extra_vars,
|
|
services_disabled=services_disabled,
|
|
active_variants=round_variants,
|
|
)
|
|
build_dev_inventory(compose, spec)
|
|
|
|
if len(plan) == 1:
|
|
_, inv_dir, round_variants, include_R = plan[0]
|
|
non_zero = {a: i for a, i in round_variants.items() if i}
|
|
suffix = f" variants={non_zero}" if non_zero else ""
|
|
print(
|
|
f">>> Inventory initialized at {inv_dir} "
|
|
f"(include={','.join(include_R)} "
|
|
f"storage_constrained={storage_constrained}){suffix}"
|
|
)
|
|
else:
|
|
print(
|
|
f">>> Matrix inventory initialized in {len(plan)} folders "
|
|
f"(primary_apps={','.join(primary_apps)} "
|
|
f"storage_constrained={storage_constrained}):"
|
|
)
|
|
for round_index, inv_dir, round_variants, include_R in plan:
|
|
non_zero = {a: i for a, i in round_variants.items() if i}
|
|
print(
|
|
f" [round {round_index}] {inv_dir} "
|
|
f"include={','.join(include_R)}"
|
|
+ (f" variants={non_zero}" if non_zero else "")
|
|
)
|
|
return 0
|