mirror of
https://github.com/kevinveenbirkenbach/computer-playbook.git
synced 2026-11-12 05:36:40 +00:00
Single atomic landing for three back-to-back role-meta refactor requirements
(see docs/requirements/008-role-meta-layout.md, 009-per-role-networks-and-ports.md,
010-role-meta-runafter-lifecycle-migration.md).
req-008 — role meta layout
* Move every role's metadata under meta/<topic>.yml with file-root
convention (no wrapping key matching the basename):
- schema/main.yml + config/main.yml.credentials → meta/schema.yml
- users/main.yml → meta/users.yml
- config/main.yml.server → meta/server.yml
- config/main.yml.rbac → meta/rbac.yml
- config/main.yml.compose.services + every other top-level key
of config/main.yml inlined under <entity>.<key>
→ meta/services.yml
- config/main.yml.compose.volumes → meta/volumes.yml
* Drop the legacy schema/, users/, config/ directories from every role.
* meta/schema.yml: support nested credential keys, optional `default:`
field (Jinja literal, not rendered/validated/regenerated), implicit
`algorithm: plain`.
* Materialised paths drop the `compose.` prefix:
compose.services.<e>.<…> → services.<e>.<…>
compose.volumes.<k> → volumes.<k>
<former-top-level>.<…> → services.<entity_name>.<former-top-level>.<…>
* Update every Python consumer (utils/cache, utils/manager, utils/applications,
plugins/lookup, plugins/filter, cli/*) plus every Jinja template, vars/*.yml
and task file to the new paths.
* No legacy fallback. Repository-wide grep for `compose.services.` /
`compose.volumes.` / `schema/main.yml` / `users/main.yml` / `config/main.yml`
is empty outside docs/requirements/ and tasks/utils/migrate_meta_layout.py.
* Add tests/lint/repository/test_role_meta_layout.py guarding against the
old paths returning, and an explicit lint guard that meta/variants.yml
files do not carry a `compose:` wrapper.
req-009 — per-role networks/ports
* Move group_vars/all/08_networks.yml.defaults_networks.local.<role>.{subnet,
dns_resolver} into roles/<role>/meta/server.yml.networks.local.{subnet,
dns_resolver}.
* Delete group_vars/all/09_ports.yml entirely; ports now live on the
service entity that exposes them at
roles/<role>/meta/services.yml.<entity>.ports.{inter,local,public}.
* Rename + int-cast every former top-level `services.<entity>.port`
field to `services.<entity>.ports.inter` (single int).
* Always-category-keyed maps for ports.local / ports.public; relay
spans use {start, end} integers.
* Add PORT_BANDS map to group_vars/all/08_networks.yml — single source
of truth for the per-<scope>.<category> band ranges, consumed by both
the new CLI helpers and the lint test.
* New CLI helpers (cli meta ports suggest, cli meta networks suggest)
walk the live role tree gap-first then increment-fallback, with
deterministic output and non-zero exit on capacity overflow.
* cli create role consumes both helpers when scaffolding a new role.
* Lint extensions: bare-int port shape rejection, host-bound port
collision check (single ints + relay span integers, inter excluded),
band-membership check with documented allow-list for the legacy
web-app-bigbluebutton.bigbluebutton.local.http: 48087 entry.
req-010 — run_after / lifecycle migration
* Move galaxy_info.run_after and galaxy_info.lifecycle out of
meta/main.yml into meta/services.yml.<primary_entity>.{run_after,
lifecycle}; <primary_entity> is the value returned by
get_entity_name(role_name).
* For multi-entity roles whose primary entity has no compose service
(web-app-bluesky → bluesky, web-app-matrix → matrix, desk/dev/drv/
gen roles), create a dedicated metadata-only top-level entry under
<primary_entity>.
* Introduce utils/roles/meta_lookup.py with get_role_run_after /
get_role_lifecycle that resolve <primary_entity> once and read from
meta/services.yml; degrade gracefully when meta/services.yml is
absent OR the field is absent; raise MetaServicesShapeError when the
file exists but is malformed.
* Update every consumer (utils/service_registry, utils/invokable,
cli/meta/applications/resolution/run_after/__main__, cli/meta/roles/
lifecycle_filter/__main__, cli/meta/applications/resolution/combined,
cli/build/{tree,graph,role_include}, cli/deploy/development/{common,
init,deps,deploy}, plugins/filter/canonical_domains_map, etc.) to
use the helper.
* Lint guards: no run_after/lifecycle in meta/main.yml; lifecycle
values restricted to {planned,pre-alpha,alpha,beta,stable,deprecated};
run_after/lifecycle never on a non-primary entity; empty run_after
lists rejected.
Also folded into this change set
* services_disabler now writes `services.<svc>.{enabled,shared}` into
host_vars instead of the old `compose.services.<svc>.{...}` path; the
discover/find pair walks meta/services.yml and only treats entries
carrying enabled/shared/provides as provider declarations (so
metadata-only entries from req-010 do not create spurious provider
rows).
* service_registry skips `run_after` deps whose target was filtered
out via SERVICES_DISABLED instead of failing the whole load.
* cli/mirror/resolver and cli/create/inventory/mirror_overrides emit/
consume the new applications.<role>.services.<svc>.image shape
(mirror.md updated to match).
* utils/domains/list.build_applications_from_roles now reads
meta/server.yml directly (it had been silently returning {} since
config/main.yml stopped existing).
* utils/roles/resource_validation.filter_roles_by_min_storage reads
meta/services.yml.<entity>.min_storage instead of the legacy
compose.services path.
* web-app-bluesky pre-clones the social-app build context BEFORE
sys-svc-compose so the build context is on disk by the time
sys-stk-front-proxy/tasks/main.yml flushes the docker build handler.
* 4 meta/variants.yml files (svc-ai-ollama, web-app-phpmyadmin,
web-app-wordpress, web-app-keycloak) lose their `compose: services:`
wrapper so deep-merge over meta/services.yml lands on the new
file-root shape.
Validation
* Unit tests: 1571 passed.
* Lint tests: 50 passed.
* Integration tests: 161 passed (1 skipped).
* Full-cycle fresh-purged-apps deploy succeeded for the 8-app validation
set: web-app-{nextcloud,wordpress,yourls,bigbluebutton,bluesky,gitea,
discourse,mattermost}.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
291 lines
10 KiB
Python
291 lines
10 KiB
Python
"""SPOT for development inventory creation.
|
|
|
|
Anything that wants to materialise the development inventory MUST go
|
|
through `build_dev_inventory` (single folder) or
|
|
`build_dev_inventory_matrix` (one folder per matrix-deploy round). Both
|
|
flow through `DevInventorySpec` and own:
|
|
|
|
* the SPOT vars-file (`DEV_INVENTORY_VARS_FILE`),
|
|
* per-app variant baking (each role's `meta/variants.yml` is resolved at
|
|
build time and emitted as `applications.<app>` overrides into the
|
|
inventory's `host_vars`, with variant 0 as the fallback for apps
|
|
without `meta/variants.yml`),
|
|
* the vault password file.
|
|
|
|
The deploy wrapper consumes `plan_dev_inventory_matrix` to know which
|
|
folder to deploy against in each round; the planner is a pure function
|
|
so wrapper and init step compute the same plan independently.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
from dataclasses import dataclass
|
|
from typing import TYPE_CHECKING, Any, Mapping, Sequence
|
|
|
|
from utils.cache.applications import get_variants
|
|
|
|
from .common import DEV_INVENTORY_VARS_FILE
|
|
from .mirrors import generate_ci_mirrors_file, should_use_mirrors_on_ci
|
|
|
|
if TYPE_CHECKING:
|
|
from .compose import Compose
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class DevInventorySpec:
|
|
"""Everything `infinito create inventory` needs to materialise one
|
|
development inventory folder.
|
|
|
|
`extra_vars` wins over the implicit `STORAGE_CONSTRAINED` / `RUNTIME`
|
|
overrides so callers (and tests) keep the documented "user-provided
|
|
vars always win" behaviour without re-implementing the merge.
|
|
|
|
`active_variants` is the per-app variant index for the round this
|
|
folder represents. Apps absent from the mapping (or with an out-of-
|
|
range index) fall back to variant 0. The resolved variant payload
|
|
for every app in `include` is baked into the inventory as an
|
|
`applications.<app>` override, so the deploy stage no longer needs
|
|
a runtime variant selector — the inventory itself is variant-resolved.
|
|
"""
|
|
|
|
inventory_dir: str
|
|
include: tuple[str, ...]
|
|
storage_constrained: bool
|
|
runtime: str
|
|
extra_vars: Mapping[str, Any] | None = None
|
|
services_disabled: str = ""
|
|
active_variants: Mapping[str, int] | None = None
|
|
|
|
def __post_init__(self) -> None:
|
|
if not self.include:
|
|
raise ValueError("DevInventorySpec.include must not be empty")
|
|
if not isinstance(self.include, tuple):
|
|
object.__setattr__(self, "include", tuple(self.include))
|
|
|
|
def overrides(self) -> dict[str, Any]:
|
|
merged: dict[str, Any] = {
|
|
"STORAGE_CONSTRAINED": bool(self.storage_constrained),
|
|
"RUNTIME": self.runtime,
|
|
}
|
|
if self.extra_vars:
|
|
merged.update(self.extra_vars)
|
|
return merged
|
|
|
|
def variant_selectors(self) -> dict[str, int]:
|
|
return dict(self.active_variants or {})
|
|
|
|
def inventory_root(self) -> str:
|
|
return str(self.inventory_dir).rstrip("/")
|
|
|
|
|
|
def _resolve_variant_payloads(
|
|
*,
|
|
roles_dir: str,
|
|
include: Sequence[str],
|
|
active_variants: Mapping[str, int],
|
|
) -> dict[str, Any]:
|
|
"""Return ``{app_id: variant_payload}`` for the requested round.
|
|
|
|
Apps without `meta/variants.yml` collapse to a single empty variant
|
|
in the loader, so this just picks variant 0 (= `meta/services.yml`
|
|
unchanged) for them. Out-of-range indices clamp to 0.
|
|
"""
|
|
variants_per_app = get_variants(roles_dir=roles_dir)
|
|
resolved: dict[str, Any] = {}
|
|
for app_id in include:
|
|
variant_list = variants_per_app.get(app_id) or [{}]
|
|
if not variant_list:
|
|
continue
|
|
index = active_variants.get(app_id, 0)
|
|
if not 0 <= index < len(variant_list):
|
|
index = 0
|
|
resolved[app_id] = variant_list[index]
|
|
return resolved
|
|
|
|
|
|
def _bake_overrides(
|
|
*,
|
|
base_overrides: Mapping[str, Any],
|
|
variant_payloads: Mapping[str, Any],
|
|
) -> dict[str, Any]:
|
|
"""Merge the per-app variant payloads under `applications:` into the
|
|
`--vars` JSON the init step will hand to `infinito create inventory`.
|
|
Caller-supplied `extra_vars` (already inside `base_overrides`) win
|
|
over the variant bake when the same key is set on both sides — that
|
|
matches the existing "user vars always win" rule."""
|
|
merged: dict[str, Any] = dict(base_overrides)
|
|
if not variant_payloads:
|
|
return merged
|
|
existing_apps = merged.get("applications")
|
|
if not isinstance(existing_apps, Mapping):
|
|
existing_apps = {}
|
|
apps: dict[str, Any] = {
|
|
app_id: payload for app_id, payload in variant_payloads.items()
|
|
}
|
|
# Caller-supplied `applications.*` entries deep-overlay the variant
|
|
# payload so overrides like `applications.web-app-foo.feature_flag` from
|
|
# `--vars` still take precedence.
|
|
for app_id, override in existing_apps.items():
|
|
base_payload = apps.get(app_id)
|
|
if isinstance(base_payload, Mapping) and isinstance(override, Mapping):
|
|
apps[app_id] = {**base_payload, **override}
|
|
else:
|
|
apps[app_id] = override
|
|
merged["applications"] = apps
|
|
return merged
|
|
|
|
|
|
def build_dev_inventory(compose: Compose, spec: DevInventorySpec) -> None:
|
|
"""Build the inventory folder described by `spec` and ensure its
|
|
vault password file exists. Two side-effects, no return value: after
|
|
this call, `spec.inventory_dir` contains a complete, variant-resolved
|
|
inventory.
|
|
"""
|
|
inv_root = spec.inventory_root()
|
|
|
|
variant_payloads = _resolve_variant_payloads(
|
|
roles_dir=str(compose.repo_root / "roles"),
|
|
include=spec.include,
|
|
active_variants=spec.variant_selectors(),
|
|
)
|
|
vars_payload = _bake_overrides(
|
|
base_overrides=spec.overrides(),
|
|
variant_payloads=variant_payloads,
|
|
)
|
|
|
|
cmd = [
|
|
"infinito",
|
|
"create",
|
|
"inventory",
|
|
inv_root,
|
|
"--host",
|
|
"localhost",
|
|
"--ssl-disabled",
|
|
"--vars-file",
|
|
DEV_INVENTORY_VARS_FILE,
|
|
"--vars",
|
|
json.dumps(vars_payload, sort_keys=True),
|
|
"--include",
|
|
",".join(spec.include),
|
|
]
|
|
|
|
if should_use_mirrors_on_ci():
|
|
mirrors_file = generate_ci_mirrors_file(compose, inventory_dir=inv_root)
|
|
cmd += ["--mirror", mirrors_file]
|
|
|
|
extra_env: dict[str, str] = {}
|
|
if spec.services_disabled:
|
|
extra_env["SERVICES_DISABLED"] = spec.services_disabled
|
|
|
|
compose.exec(
|
|
cmd,
|
|
check=True,
|
|
workdir="/opt/src/infinito",
|
|
extra_env=extra_env or None,
|
|
)
|
|
_ensure_vault_password_file(compose, inventory_dir=inv_root)
|
|
|
|
|
|
def filter_plan_to_variant(
|
|
plan: list[tuple[int, str, dict[str, int]]],
|
|
variant: int | None,
|
|
) -> list[tuple[int, str, dict[str, int]]]:
|
|
"""Pin a matrix plan to a single round when `variant` is set.
|
|
|
|
`variant=None` returns the plan unchanged (full-matrix mode). An
|
|
explicit variant index is matched against the plan's round indices;
|
|
if it's out of range, raises `ValueError` so callers can surface a
|
|
clean operator-facing error rather than silently doing nothing.
|
|
"""
|
|
if variant is None:
|
|
return plan
|
|
for entry in plan:
|
|
if entry[0] == variant:
|
|
return [entry]
|
|
available = sorted(idx for idx, _, _ in plan)
|
|
raise ValueError(f"variant {variant} out of range; available rounds: {available}")
|
|
|
|
|
|
def plan_dev_inventory_matrix(
|
|
*,
|
|
roles_dir: str,
|
|
include: Sequence[str],
|
|
base_inventory_dir: str,
|
|
) -> list[tuple[int, str, dict[str, int]]]:
|
|
"""Return ``[(round_index, inventory_dir, round_variants), ...]``.
|
|
|
|
`total_rounds = max(variant_count)` across the included apps. In each
|
|
round R, every app uses variant index R when its variant list is long
|
|
enough, otherwise variant 0 (the legacy `meta/services.yml` payload).
|
|
Inventory paths are suffixed with `-<round>` only when `total_rounds
|
|
> 1`, so single-variant deploys keep the historical unsuffixed path.
|
|
|
|
Pure function — does not touch disk.
|
|
"""
|
|
if not include:
|
|
raise ValueError("plan_dev_inventory_matrix: include must not be empty")
|
|
variants_per_app = get_variants(roles_dir=roles_dir)
|
|
variant_counts = {
|
|
app_id: max(1, len(variants_per_app.get(app_id) or [{}])) for app_id in include
|
|
}
|
|
total_rounds = max(variant_counts.values(), default=1)
|
|
base = str(base_inventory_dir).rstrip("/")
|
|
|
|
plan: list[tuple[int, str, dict[str, int]]] = []
|
|
for round_index in range(total_rounds):
|
|
round_variants = {
|
|
app_id: round_index if round_index < count else 0
|
|
for app_id, count in variant_counts.items()
|
|
}
|
|
inv_dir = f"{base}-{round_index}" if total_rounds > 1 else base
|
|
plan.append((round_index, inv_dir, round_variants))
|
|
return plan
|
|
|
|
|
|
def build_dev_inventory_matrix(
|
|
compose: Compose,
|
|
*,
|
|
base_inventory_dir: str,
|
|
include: Sequence[str],
|
|
storage_constrained: bool,
|
|
runtime: str,
|
|
extra_vars: Mapping[str, Any] | None = None,
|
|
services_disabled: str = "",
|
|
) -> list[tuple[int, str, dict[str, int]]]:
|
|
"""Build every folder in the matrix plan and return that plan so the
|
|
caller can iterate it (typically by handing each folder to the deploy
|
|
stage in turn)."""
|
|
plan = plan_dev_inventory_matrix(
|
|
roles_dir=str(compose.repo_root / "roles"),
|
|
include=include,
|
|
base_inventory_dir=base_inventory_dir,
|
|
)
|
|
for _round_index, inv_dir, round_variants in plan:
|
|
spec = DevInventorySpec(
|
|
inventory_dir=inv_dir,
|
|
include=tuple(include),
|
|
storage_constrained=storage_constrained,
|
|
runtime=runtime,
|
|
extra_vars=extra_vars,
|
|
services_disabled=services_disabled,
|
|
active_variants=round_variants,
|
|
)
|
|
build_dev_inventory(compose, spec)
|
|
return plan
|
|
|
|
|
|
def _ensure_vault_password_file(compose: Compose, *, inventory_dir: str) -> None:
|
|
inv_root = str(inventory_dir).rstrip("/")
|
|
pw_file = f"{inv_root}/.password"
|
|
compose.exec(
|
|
[
|
|
"sh",
|
|
"-lc",
|
|
f"mkdir -p {inv_root} && "
|
|
f"[ -f {pw_file} ] || "
|
|
f"printf '%s\n' 'ci-vault-password' > {pw_file}",
|
|
],
|
|
check=True,
|
|
)
|