2636 lines
118 KiB
Python
2636 lines
118 KiB
Python
#!/usr/bin/env python3
|
|
"""Build, describe, and check release images of the Lincodex Compose stack.
|
|
|
|
Subcommands (deploy/Makefile is the supported interface):
|
|
|
|
tag print the release tag of the working tree
|
|
build build the release images with base images pinned to the
|
|
digests resolved from the local image store
|
|
require-images fail unless every image a release run needs is local
|
|
record-evidence record that a check passed against a running project
|
|
manifest publish deploy/release/<id>/manifest.json once
|
|
restore preflight and restore exact images for a selected manifest
|
|
verify compare running containers of a project with a manifest
|
|
check check a manifest's structure and scan it for machine secrets
|
|
demo-override preflight a manifest for the isolated demo stand and write
|
|
the Compose override that pins its exact images
|
|
clean-images remove unretained local lincodex.invalid/* release images
|
|
|
|
Only the standard library is used. Docker is called through the CLI; no
|
|
command here pulls an image unless it is `build`, and `build` pulls only base
|
|
or service images that are missing locally (or all of them with --pull
|
|
always). The manifest and evidence never copy environment values, labels,
|
|
mounts, or local paths from Docker; every written file passes
|
|
forbidden_findings() first.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import base64
|
|
import contextlib
|
|
import datetime as _dt
|
|
import fcntl
|
|
import getpass
|
|
import hashlib
|
|
import io
|
|
import json
|
|
import os
|
|
import re
|
|
import secrets as _secrets
|
|
import stat
|
|
import socket
|
|
import subprocess
|
|
import sys
|
|
import tarfile
|
|
import tempfile
|
|
from dataclasses import dataclass, field
|
|
from pathlib import Path, PurePosixPath
|
|
from typing import Any, Callable, Iterable
|
|
|
|
ROOT = Path(__file__).resolve().parents[2]
|
|
RELEASE_DIR_NAME = "deploy/release"
|
|
MANIFEST_SCHEMA = "lincodex.release-manifest/v2"
|
|
BUILD_SCHEMA = "lincodex.release-build/v1"
|
|
EVIDENCE_SCHEMA = "lincodex.release-evidence/v1"
|
|
DATA_SCHEMA = "lincodex.release-data/v1"
|
|
RELEASE_REGISTRY = "lincodex.invalid"
|
|
POLICY_SOURCE_ARTIFACT = "backend/internal/domain/policy_demo.go"
|
|
# Project name used only to render Compose files; nothing is started under it.
|
|
RENDER_PROJECT = "lincodex-release"
|
|
# Compose requires IDENTITY_KEY_SECRET and .env.example has none; this value only
|
|
# lets a render or build go through and is never deployed.
|
|
RENDER_ONLY_IDENTITY_KEY = "render-only-identity-key-secret-not-for-deployment"
|
|
# The demo overlay requires DEMO_ACCOUNT_PASSWORD; this value only lets a
|
|
# render or build of the demo seed image go through and is never deployed.
|
|
RENDER_ONLY_DEMO_PASSWORD = "render-only-demo-account-password"
|
|
CHECKS = ("smoke", "e2e")
|
|
DATA_COMPONENTS = ("bank", "policy", "seed")
|
|
RELEASE_ID_PATTERN = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,63}")
|
|
DATA_MANIFEST_LIMIT = 1024 * 1024
|
|
DATA_ARTIFACT_LIMIT = 64
|
|
DATA_ARTIFACT_SIZE_LIMIT = 64 * 1024 * 1024
|
|
DATA_TOTAL_SIZE_LIMIT = 256 * 1024 * 1024
|
|
CORE_COMPOSE_FILES = (
|
|
"deploy/docker/docker-compose.yml",
|
|
"deploy/docker/docker-compose.release.yml",
|
|
)
|
|
# The isolated demo stand adds these to the core files; deploy/scripts/demo.sh
|
|
# restores it from a manifest through command_demo_override.
|
|
DEMO_COMPOSE_FILES = (
|
|
"deploy/docker/docker-compose.demo.yml",
|
|
"deploy/docker/docker-compose.demo.release.yml",
|
|
)
|
|
RELEASE_COMPOSE_FILES = CORE_COMPOSE_FILES + DEMO_COMPOSE_FILES
|
|
DEMO_PROFILE = "demo-seed"
|
|
DEMO_SEED_SERVICE = "demo-seed"
|
|
# The demo seed dataset, including its synthetic bank, is Go source compiled
|
|
# into the demo seed image; the manifest versions it by the hash of this
|
|
# package's non-test files.
|
|
SEED_SOURCE_DIR = "backend/internal/usecase/demoseed"
|
|
SEED_DOCKERFILE = "backend/Dockerfile.demo-seed"
|
|
CHECK_SCOPE = {
|
|
"smoke": (
|
|
"deploy/scripts/smoke.sh: Compose startup and health, API routing, PostgreSQL, Redis, and "
|
|
"SeaweedFS readiness and recovery, Redis and storage access rules, disabled mail transport. "
|
|
"Not a business-flow test; Kafka publishing is not checked."
|
|
),
|
|
"e2e": (
|
|
"deploy/scripts/e2e.sh: the Playwright technical browser suite against the stack. "
|
|
"No candidate or employer workflows."
|
|
),
|
|
}
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Group:
|
|
name: str
|
|
compose_file: str
|
|
release_overlay: str | None
|
|
# Groups whose images a passing smoke or E2E run can verify.
|
|
verifiable: bool
|
|
unverified_reason: str
|
|
# Files rendered before compose_file, for a group that is an overlay.
|
|
base_files: tuple[str, ...] = ()
|
|
# A group with a profile takes only the services of that profile.
|
|
profile: str | None = None
|
|
|
|
|
|
GROUPS = (
|
|
Group("core", "deploy/docker/docker-compose.yml", "deploy/docker/docker-compose.release.yml", True, ""),
|
|
Group(
|
|
"demo",
|
|
DEMO_COMPOSE_FILES[0],
|
|
DEMO_COMPOSE_FILES[1],
|
|
False,
|
|
"Built by release-build and pinned for the isolated demo stand, but no release check runs the demo seed.",
|
|
base_files=CORE_COMPOSE_FILES,
|
|
profile=DEMO_PROFILE,
|
|
),
|
|
Group(
|
|
"ml",
|
|
"deploy/docker/docker-compose.ml.yml",
|
|
"deploy/docker/docker-compose.ml.release.yml",
|
|
False,
|
|
"Built by release-build, but no release check starts the ML service, and it has no inference model.",
|
|
),
|
|
Group(
|
|
"monitoring",
|
|
"deploy/docker/docker-compose.monitoring.yml",
|
|
None,
|
|
False,
|
|
"Monitoring is a separate project that no release check starts; images are recorded only if present locally.",
|
|
),
|
|
)
|
|
|
|
# Planned components with no service, image, or Compose file in this repository.
|
|
MISSING_COMPONENTS = {
|
|
"gpu-inference": "Local model inference on a separate GPU host. The ML service has no model, and no GPU runtime or image exists.",
|
|
"judge0": "Isolated code execution host. No service, image, or Compose file exists in this repository.",
|
|
"qdrant": "Vector search. No service, image, or Compose file exists in this repository.",
|
|
}
|
|
|
|
# Only these image metadata keys are copied; everything else stays out.
|
|
VERSION_ENV_KEYS = (
|
|
"GOLANG_VERSION",
|
|
"JAVA_VERSION",
|
|
"NGINX_VERSION",
|
|
"NODE_VERSION",
|
|
"PG_MAJOR",
|
|
"PG_VERSION",
|
|
"PYTHON_VERSION",
|
|
"REDIS_VERSION",
|
|
)
|
|
VERSION_LABEL_KEYS = ("org.opencontainers.image.revision", "org.opencontainers.image.version")
|
|
|
|
LOCKFILES = (
|
|
"backend/go.mod",
|
|
"backend/go.sum",
|
|
"frontend/package.json",
|
|
"frontend/pnpm-lock.yaml",
|
|
"ml/pyproject.toml",
|
|
"ml/uv.lock",
|
|
)
|
|
|
|
|
|
class ReleaseError(RuntimeError):
|
|
"""A release step cannot continue; the message is safe to print."""
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Secret and machine data scanning
|
|
|
|
|
|
SECRET_NAME = re.compile(
|
|
r"(PASS|PWD|SECRET|TOKEN|KEY|AUTH|DSN|COOKIE|SESSION|SIGN|PRIVATE|CREDENTIAL)", re.IGNORECASE
|
|
)
|
|
FORBIDDEN_PATTERNS = (
|
|
("private key block", re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----")),
|
|
("credentials in a URL", re.compile(r"[A-Za-z][A-Za-z0-9+.-]*://[^/\s:@\"]+:[^/\s@\"]+@")),
|
|
("secret assignment", re.compile(r"\b[A-Z0-9_]*(PASSWORD|SECRET|TOKEN|API_KEY)[A-Z0-9_]*=")),
|
|
("AWS access key", re.compile(r"\bAKIA[0-9A-Z]{16}\b")),
|
|
("Resend API key", re.compile(r"\bre_[A-Za-z0-9]{8,}_[A-Za-z0-9_]{8,}")),
|
|
("GitHub token", re.compile(r"\bgh[pousr]_[A-Za-z0-9]{20,}")),
|
|
("Slack token", re.compile(r"\bxox[abprs]-[A-Za-z0-9-]{10,}")),
|
|
("JSON web token", re.compile(r"\beyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.")),
|
|
("absolute local path", re.compile(r"(?<![A-Za-z0-9._-])/(Users|home|root|private|tmp|var/folders|Volumes|mnt|opt/homebrew)/")),
|
|
("Windows path", re.compile(r"(?<![A-Za-z])[A-Za-z]:\\\\")),
|
|
("home directory shorthand", re.compile(r"(?<![A-Za-z0-9])~/")),
|
|
)
|
|
# JSON keys that would carry container configuration rather than identity.
|
|
FORBIDDEN_KEYS = frozenset(
|
|
{"binds", "env", "environment", "hostname", "labels", "mounts", "volumes", "working_dir", "workingdir"}
|
|
)
|
|
# Words that can legitimately appear in a manifest even if a machine uses them
|
|
# as a user or host name.
|
|
NEUTRAL_WORDS = frozenset({"app", "build", "core", "docker", "lincodex", "local", "localhost", "ml", "node", "root"})
|
|
|
|
|
|
def env_file_values(path: Path) -> dict[str, str]:
|
|
values: dict[str, str] = {}
|
|
try:
|
|
text = path.read_text(encoding="utf-8")
|
|
except OSError:
|
|
return values
|
|
for line in text.splitlines():
|
|
line = line.strip()
|
|
if not line or line.startswith("#") or "=" not in line:
|
|
continue
|
|
name, value = line.split("=", 1)
|
|
values[name.strip()] = value.strip().strip("'\"")
|
|
return values
|
|
|
|
|
|
def sensitive_values(root: Path = ROOT, environ: dict[str, str] | None = None) -> dict[str, str]:
|
|
"""Return label -> value for values that must never appear in output.
|
|
|
|
Labels name the source (variable name, user, host) and never the value.
|
|
"""
|
|
environ = dict(os.environ if environ is None else environ)
|
|
found: dict[str, str] = {}
|
|
|
|
def add(label: str, value: str, minimum: int = 6) -> None:
|
|
value = value.strip()
|
|
if len(value) >= minimum and value.lower() not in NEUTRAL_WORDS:
|
|
found.setdefault(label, value)
|
|
|
|
for source, values in (("root .env", env_file_values(root / ".env")), ("environment", environ)):
|
|
for name, value in values.items():
|
|
if SECRET_NAME.search(name):
|
|
add(f"value of {name} from {source}", value)
|
|
try:
|
|
add("local user name", getpass.getuser(), minimum=3)
|
|
except (KeyError, OSError):
|
|
pass
|
|
host = socket.gethostname()
|
|
add("local host name", host, minimum=3)
|
|
add("local host name", host.split(".", 1)[0], minimum=3)
|
|
home = environ.get("HOME", "")
|
|
if home not in ("", "/"):
|
|
add("home directory", home, minimum=3)
|
|
add("repository path", str(root), minimum=3)
|
|
return found
|
|
|
|
|
|
def _walk_keys(value: Any, path: str = "$") -> Iterable[tuple[str, str]]:
|
|
if isinstance(value, dict):
|
|
for key, item in value.items():
|
|
yield path, str(key)
|
|
yield from _walk_keys(item, f"{path}.{key}")
|
|
elif isinstance(value, list):
|
|
for index, item in enumerate(value):
|
|
yield from _walk_keys(item, f"{path}[{index}]")
|
|
|
|
|
|
def value_forms(value: str) -> list[str]:
|
|
"""Return the value and, for long values, its base64 encodings without padding."""
|
|
forms = [value]
|
|
if len(value) >= 8:
|
|
raw = value.encode("utf-8")
|
|
for encoded in (base64.b64encode(raw), base64.urlsafe_b64encode(raw)):
|
|
forms.append(encoded.decode("ascii").rstrip("="))
|
|
return forms
|
|
|
|
|
|
def contains_value(text: str, value: str) -> bool:
|
|
# Long values are searched as substrings; short ones need word boundaries
|
|
# so that, for example, a three-letter user name inside a digest is not a hit.
|
|
if len(value) >= 8:
|
|
lowered = text.lower()
|
|
return any(form.lower() in lowered if form == value else form in text for form in value_forms(value))
|
|
return bool(re.search(rf"(?<![A-Za-z0-9]){re.escape(value)}(?![A-Za-z0-9])", text, re.IGNORECASE))
|
|
|
|
|
|
def forbidden_findings(document: Any, sensitive: dict[str, str] | None = None) -> list[str]:
|
|
"""Describe forbidden content in a JSON document without echoing it."""
|
|
text = json.dumps(document, sort_keys=True) if not isinstance(document, str) else document
|
|
findings: list[str] = []
|
|
for name, pattern in FORBIDDEN_PATTERNS:
|
|
if pattern.search(text):
|
|
findings.append(name)
|
|
for label, value in sorted((sensitive or {}).items()):
|
|
if contains_value(text, value):
|
|
findings.append(label)
|
|
if not isinstance(document, str):
|
|
for where, key in _walk_keys(document):
|
|
if key.lower() in FORBIDDEN_KEYS:
|
|
findings.append(f"configuration key '{key}' at {where}")
|
|
return sorted(set(findings))
|
|
|
|
|
|
def write_json(path: Path, document: dict[str, Any], root: Path = ROOT) -> None:
|
|
findings = forbidden_findings(document, sensitive_values(root))
|
|
if findings:
|
|
raise ReleaseError(f"Refusing to write {display(path, root)}: " + "; ".join(findings))
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
temporary = path.with_name(f".{path.name}.tmp")
|
|
temporary.write_text(json.dumps(document, indent=2, sort_keys=True) + "\n", encoding="utf-8")
|
|
temporary.replace(path)
|
|
|
|
|
|
def validate_release_id(value: str) -> str:
|
|
if not RELEASE_ID_PATTERN.fullmatch(value):
|
|
raise ReleaseError("Release ID must be 1-64 letters, digits, dots, underscores, or hyphens and start with a letter or digit.")
|
|
return value
|
|
|
|
|
|
def release_artifact_dir(release_id: str, root: Path = ROOT) -> Path:
|
|
validate_release_id(release_id)
|
|
base = root / RELEASE_DIR_NAME
|
|
target = base / release_id
|
|
resolved_root = root.resolve()
|
|
for path in (root / "deploy", base, target):
|
|
if path.is_symlink():
|
|
raise ReleaseError("Release artifact paths cannot contain symlinks.")
|
|
try:
|
|
target.resolve(strict=False).relative_to(resolved_root)
|
|
except ValueError as error:
|
|
raise ReleaseError("Release artifact path escapes the repository.") from error
|
|
return target
|
|
|
|
|
|
def project_file(path_text: str, root: Path, *, maximum_size: int, label: str) -> Path:
|
|
if not isinstance(path_text, str) or not path_text or len(path_text) > 512:
|
|
raise ReleaseError(f"{label} path is invalid.")
|
|
if "\\" in path_text or "\0" in path_text:
|
|
raise ReleaseError(f"{label} path must use relative POSIX separators.")
|
|
candidate_name = PurePosixPath(path_text)
|
|
if candidate_name.is_absolute() or str(candidate_name) != path_text or any(
|
|
part in ("", ".", "..") for part in candidate_name.parts
|
|
):
|
|
raise ReleaseError(f"{label} path must be a normalized repository-relative path.")
|
|
if any(part == ".git" or part.startswith(".env") for part in candidate_name.parts):
|
|
raise ReleaseError(f"{label} cannot read repository metadata or environment files.")
|
|
|
|
root_path = root.resolve()
|
|
candidate = root_path.joinpath(*candidate_name.parts)
|
|
current = root_path
|
|
for part in candidate_name.parts:
|
|
current = current / part
|
|
if current.is_symlink():
|
|
raise ReleaseError(f"{label} cannot follow symlinks: {path_text}.")
|
|
try:
|
|
resolved = candidate.resolve(strict=True)
|
|
resolved.relative_to(root_path)
|
|
metadata = resolved.stat()
|
|
except (OSError, ValueError) as error:
|
|
raise ReleaseError(f"{label} file is missing or outside the repository: {path_text}.") from error
|
|
if not stat.S_ISREG(metadata.st_mode):
|
|
raise ReleaseError(f"{label} must reference a regular file: {path_text}.")
|
|
if metadata.st_size > maximum_size:
|
|
raise ReleaseError(f"{label} file exceeds the {maximum_size}-byte limit: {path_text}.")
|
|
return resolved
|
|
|
|
|
|
def bounded_digest(path: Path, *, maximum_size: int, total_limit: int | None = None) -> tuple[str, int]:
|
|
digest = hashlib.sha256()
|
|
size = 0
|
|
try:
|
|
with path.open("rb") as stream:
|
|
while chunk := stream.read(1024 * 1024):
|
|
size += len(chunk)
|
|
if size > maximum_size or (total_limit is not None and size > total_limit):
|
|
raise ReleaseError(f"Data artifact exceeds its size limit: {path.name}.")
|
|
digest.update(chunk)
|
|
except OSError as error:
|
|
raise ReleaseError(f"Could not read data artifact {path.name}.") from error
|
|
return "sha256:" + digest.hexdigest(), size
|
|
|
|
|
|
def default_data_versions(root: Path = ROOT) -> dict[str, Any]:
|
|
result = {
|
|
name: {
|
|
"status": "unavailable",
|
|
"version": None,
|
|
"artifacts": [],
|
|
"reason": "No accepted versioned release data was supplied.",
|
|
}
|
|
for name in DATA_COMPONENTS
|
|
}
|
|
policy_path = root / POLICY_SOURCE_ARTIFACT
|
|
if policy_path.is_symlink():
|
|
raise ReleaseError("Demo policy source cannot be a symlink.")
|
|
if policy_path.is_file():
|
|
policy_file = project_file(
|
|
POLICY_SOURCE_ARTIFACT,
|
|
root,
|
|
maximum_size=DATA_ARTIFACT_SIZE_LIMIT,
|
|
label="Demo policy source",
|
|
)
|
|
digest, size = bounded_digest(policy_file, maximum_size=DATA_ARTIFACT_SIZE_LIMIT)
|
|
result["policy"] = {
|
|
"status": "available",
|
|
"version": "1",
|
|
"source_kind": "bundled_source",
|
|
"artifacts": [{"path": POLICY_SOURCE_ARTIFACT, "sha256": digest, "size_bytes": size}],
|
|
}
|
|
else:
|
|
result["policy"]["reason"] = "No versioned demo policy source is present."
|
|
result["bank"]["reason"] = (
|
|
"No accepted assessment bank release snapshot is present; the synthetic demo bank is versioned with the seed."
|
|
)
|
|
seed_paths = seed_source_paths(root)
|
|
if seed_paths:
|
|
result["seed"] = bundled_source_entry(seed_paths, "demo-seed", "Demo seed source", root)
|
|
else:
|
|
result["seed"]["reason"] = "No versioned demo seed source is present."
|
|
return result
|
|
|
|
|
|
def seed_source_paths(root: Path = ROOT) -> list[str]:
|
|
"""Return the non-test Go files of the demo seed package, sorted."""
|
|
directory = root / SEED_SOURCE_DIR
|
|
if directory.is_symlink():
|
|
raise ReleaseError("Demo seed source directory cannot be a symlink.")
|
|
if not directory.is_dir():
|
|
return []
|
|
return sorted(
|
|
f"{SEED_SOURCE_DIR}/{path.name}"
|
|
for path in directory.iterdir()
|
|
if path.name.endswith(".go") and not path.name.endswith("_test.go")
|
|
)
|
|
|
|
|
|
def bundled_source_entry(paths: list[str], prefix: str, label: str, root: Path = ROOT) -> dict[str, Any]:
|
|
"""Version checked-in source files by a hash over their paths and digests."""
|
|
artifacts: list[dict[str, Any]] = []
|
|
combined = hashlib.sha256()
|
|
for path_text in paths:
|
|
path = project_file(path_text, root, maximum_size=DATA_ARTIFACT_SIZE_LIMIT, label=label)
|
|
digest, size = bounded_digest(path, maximum_size=DATA_ARTIFACT_SIZE_LIMIT)
|
|
artifacts.append({"path": path_text, "sha256": digest, "size_bytes": size})
|
|
combined.update(f"{path_text}\0{digest}\n".encode("utf-8"))
|
|
return {
|
|
"status": "available",
|
|
"version": f"{prefix}.{combined.hexdigest()[:12]}",
|
|
"source_kind": "bundled_source",
|
|
"artifacts": artifacts,
|
|
}
|
|
|
|
|
|
def read_data_versions(path_text: str | None, root: Path = ROOT) -> dict[str, Any]:
|
|
if not path_text:
|
|
return default_data_versions(root)
|
|
path = project_file(path_text, root, maximum_size=DATA_MANIFEST_LIMIT, label="Release data manifest")
|
|
try:
|
|
with path.open("rb") as stream:
|
|
raw = stream.read(DATA_MANIFEST_LIMIT + 1)
|
|
if len(raw) > DATA_MANIFEST_LIMIT:
|
|
raise ReleaseError(f"Release data manifest exceeds the {DATA_MANIFEST_LIMIT}-byte limit.")
|
|
document = json.loads(raw.decode("utf-8"))
|
|
except ReleaseError:
|
|
raise
|
|
except (OSError, UnicodeError, ValueError) as error:
|
|
raise ReleaseError("Release data manifest is unreadable or invalid JSON.") from error
|
|
if not isinstance(document, dict) or document.get("schema") != DATA_SCHEMA:
|
|
raise ReleaseError(f"Release data manifest must use schema {DATA_SCHEMA}.")
|
|
if set(document) != {"schema", *DATA_COMPONENTS}:
|
|
raise ReleaseError("Release data manifest must contain only bank, policy, and seed entries.")
|
|
|
|
result: dict[str, Any] = {}
|
|
artifact_count = 0
|
|
total_size = 0
|
|
for name in DATA_COMPONENTS:
|
|
entry = document.get(name)
|
|
if not isinstance(entry, dict):
|
|
raise ReleaseError(f"Release data entry {name} is malformed.")
|
|
status = entry.get("status")
|
|
if status == "unavailable":
|
|
if set(entry) != {"status", "reason"} or not isinstance(entry.get("reason"), str) or not entry["reason"].strip():
|
|
raise ReleaseError(f"Unavailable release data entry {name} needs a reason.")
|
|
result[name] = {
|
|
"status": "unavailable",
|
|
"version": None,
|
|
"artifacts": [],
|
|
"reason": entry["reason"].strip()[:200],
|
|
}
|
|
continue
|
|
allowed_fields = {"status", "version", "artifacts", "source_kind"}
|
|
if status != "available" or set(entry) not in (allowed_fields - {"source_kind"}, allowed_fields):
|
|
raise ReleaseError(f"Release data entry {name} must be available with a version and artifacts, or unavailable with a reason.")
|
|
source_kind = entry.get("source_kind", "snapshot")
|
|
if source_kind not in {"snapshot", "bundled_source"}:
|
|
raise ReleaseError(f"Release data source kind for {name} is invalid.")
|
|
version = entry.get("version")
|
|
if not isinstance(version, str) or not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._:+-]{0,127}", version):
|
|
raise ReleaseError(f"Release data version for {name} is invalid.")
|
|
artifacts = entry.get("artifacts")
|
|
if not isinstance(artifacts, list) or not artifacts:
|
|
raise ReleaseError(f"Release data entry {name} needs at least one artifact.")
|
|
recorded: list[dict[str, Any]] = []
|
|
for artifact in artifacts:
|
|
artifact_count += 1
|
|
if artifact_count > DATA_ARTIFACT_LIMIT:
|
|
raise ReleaseError(f"Release data manifest exceeds the {DATA_ARTIFACT_LIMIT}-artifact limit.")
|
|
if not isinstance(artifact, dict) or set(artifact) != {"path"}:
|
|
raise ReleaseError(f"Release data artifact in {name} must contain only a path.")
|
|
artifact_path = project_file(
|
|
artifact["path"], root, maximum_size=DATA_ARTIFACT_SIZE_LIMIT, label="Release data artifact"
|
|
)
|
|
remaining = DATA_TOTAL_SIZE_LIMIT - total_size
|
|
if remaining <= 0:
|
|
raise ReleaseError(f"Release data artifacts exceed the {DATA_TOTAL_SIZE_LIMIT}-byte total limit.")
|
|
digest, size = bounded_digest(
|
|
artifact_path, maximum_size=DATA_ARTIFACT_SIZE_LIMIT, total_limit=remaining
|
|
)
|
|
total_size += size
|
|
recorded.append({"path": artifact["path"], "sha256": digest, "size_bytes": size})
|
|
result[name] = {"status": "available", "version": version, "source_kind": source_kind, "artifacts": recorded}
|
|
return result
|
|
|
|
|
|
def verify_data_artifacts(data_versions: dict[str, Any], root: Path = ROOT) -> None:
|
|
total_size = 0
|
|
artifact_count = 0
|
|
for name in DATA_COMPONENTS:
|
|
entry = data_versions.get(name)
|
|
if not isinstance(entry, dict):
|
|
raise ReleaseError(f"Manifest data entry {name} is malformed.")
|
|
if entry.get("status") == "unavailable":
|
|
continue
|
|
if entry.get("status") != "available" or not isinstance(entry.get("artifacts"), list):
|
|
raise ReleaseError(f"Manifest data entry {name} has an unknown status.")
|
|
for artifact in entry["artifacts"]:
|
|
artifact_count += 1
|
|
if artifact_count > DATA_ARTIFACT_LIMIT or not isinstance(artifact, dict):
|
|
raise ReleaseError("Manifest data artifacts exceed their limit or are malformed.")
|
|
path = project_file(
|
|
artifact.get("path"), root, maximum_size=DATA_ARTIFACT_SIZE_LIMIT, label="Manifest data artifact"
|
|
)
|
|
remaining = DATA_TOTAL_SIZE_LIMIT - total_size
|
|
if remaining <= 0:
|
|
raise ReleaseError(f"Manifest data artifacts exceed the {DATA_TOTAL_SIZE_LIMIT}-byte total limit.")
|
|
digest, size = bounded_digest(path, maximum_size=DATA_ARTIFACT_SIZE_LIMIT, total_limit=remaining)
|
|
if digest != artifact.get("sha256") or size != artifact.get("size_bytes"):
|
|
raise ReleaseError(f"Release data artifact is missing or changed: {artifact.get('path')}.")
|
|
total_size += size
|
|
|
|
|
|
def write_json_immutable(path: Path, document: dict[str, Any], root: Path = ROOT) -> bool:
|
|
"""Publish once; return False for an identical rerun without touching the file."""
|
|
findings = forbidden_findings(document, sensitive_values(root))
|
|
if findings:
|
|
raise ReleaseError(f"Refusing to write {display(path, root)}: " + "; ".join(findings))
|
|
if path.is_symlink():
|
|
raise ReleaseError("Refusing to publish through a manifest symlink.")
|
|
encoded = json.dumps(document, indent=2, sort_keys=True).encode("utf-8") + b"\n"
|
|
|
|
def existing_matches() -> bool:
|
|
try:
|
|
previous = json.loads(path.read_text(encoding="utf-8"))
|
|
except (OSError, UnicodeError, ValueError) as error:
|
|
raise ReleaseError(f"An unreadable immutable manifest already exists at {display(path, root)}; it was preserved.") from error
|
|
if not isinstance(previous, dict):
|
|
raise ReleaseError(f"An invalid immutable manifest already exists at {display(path, root)}; it was preserved.")
|
|
if comparable(previous) == comparable(document):
|
|
return True
|
|
raise ReleaseError(
|
|
f"Immutable release {document.get('release', {}).get('id')} already exists at {display(path, root)}. "
|
|
"Use a new RELEASE_ID for a separate delivery."
|
|
)
|
|
|
|
if path.exists():
|
|
existing_matches()
|
|
return False
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
temporary = path.with_name(f".{path.name}.{_secrets.token_hex(8)}.tmp")
|
|
try:
|
|
file_descriptor = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
|
with os.fdopen(file_descriptor, "wb") as stream:
|
|
stream.write(encoded)
|
|
stream.flush()
|
|
os.fsync(stream.fileno())
|
|
try:
|
|
os.link(temporary, path)
|
|
except FileExistsError:
|
|
existing_matches()
|
|
return False
|
|
try:
|
|
directory_fd = os.open(path.parent, os.O_RDONLY)
|
|
try:
|
|
os.fsync(directory_fd)
|
|
finally:
|
|
os.close(directory_fd)
|
|
except OSError:
|
|
pass
|
|
return True
|
|
finally:
|
|
try:
|
|
temporary.unlink()
|
|
except FileNotFoundError:
|
|
pass
|
|
|
|
|
|
@contextlib.contextmanager
|
|
def immutable_release_lock(release_id: str, root: Path = ROOT):
|
|
"""Serialize image retention and manifest publication for one release ID."""
|
|
validate_release_id(release_id)
|
|
release_root = root / RELEASE_DIR_NAME
|
|
lock_dir = release_root / ".locks"
|
|
for path in (root / "deploy", release_root, lock_dir):
|
|
if path.is_symlink():
|
|
raise ReleaseError("Release lock paths cannot contain symlinks.")
|
|
lock_dir.mkdir(parents=True, exist_ok=True)
|
|
lock_path = lock_dir / f"{release_id}.lock"
|
|
flags = os.O_CREAT | os.O_RDWR
|
|
if hasattr(os, "O_NOFOLLOW"):
|
|
flags |= os.O_NOFOLLOW
|
|
try:
|
|
descriptor = os.open(lock_path, flags, 0o600)
|
|
except OSError as error:
|
|
raise ReleaseError("Could not open the release publication lock.") from error
|
|
try:
|
|
metadata = os.fstat(descriptor)
|
|
if not stat.S_ISREG(metadata.st_mode):
|
|
raise ReleaseError("Release publication lock is not a regular file.")
|
|
fcntl.flock(descriptor, fcntl.LOCK_EX)
|
|
yield
|
|
finally:
|
|
try:
|
|
fcntl.flock(descriptor, fcntl.LOCK_UN)
|
|
finally:
|
|
os.close(descriptor)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Source state
|
|
|
|
|
|
def run(args: list[str], *, cwd: Path = ROOT, env: dict[str, str] | None = None, check: bool = True) -> bytes:
|
|
try:
|
|
result = subprocess.run(args, cwd=cwd, env=env, capture_output=True, check=False)
|
|
except OSError as error:
|
|
raise ReleaseError(f"{args[0]} could not run: {error}") from error
|
|
if check and result.returncode != 0:
|
|
message = result.stderr.decode("utf-8", errors="replace").strip().splitlines()
|
|
tail = message[-1] if message else f"exit status {result.returncode}"
|
|
raise ReleaseError(f"{' '.join(args[:3])} failed: {tail}")
|
|
return result.stdout
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Source:
|
|
commit: str
|
|
dirty: bool
|
|
fingerprint: str | None
|
|
|
|
@property
|
|
def tag(self) -> str:
|
|
return self.commit[:12] + ("-dirty" if self.dirty else "")
|
|
|
|
|
|
# Settings that change how git add records content; pinned so that the
|
|
# working tree fingerprint does not depend on local or global git config.
|
|
GIT_PINNED = (
|
|
"-c", "core.autocrlf=false",
|
|
"-c", "core.safecrlf=false",
|
|
"-c", "core.filemode=true",
|
|
"-c", "core.symlinks=true",
|
|
"-c", "core.fsmonitor=false",
|
|
)
|
|
|
|
|
|
def read_source(root: Path = ROOT) -> Source:
|
|
"""Return the commit and, for a changed tree, the Git tree ID of the working tree.
|
|
|
|
The tree is written from a temporary index (seeded from HEAD, then git add -A),
|
|
so it covers modified, deleted, and untracked files that Git does not ignore,
|
|
leaves the real index alone, and does not depend on diff settings.
|
|
"""
|
|
git = ["git", *GIT_PINNED]
|
|
commit = run([*git, "rev-parse", "--verify", "HEAD"], cwd=root).decode().strip()
|
|
head_tree = run([*git, "rev-parse", "--verify", "HEAD^{tree}"], cwd=root).decode().strip()
|
|
with tempfile.TemporaryDirectory(prefix="lincodex-release-index-") as directory:
|
|
env = {name: value for name, value in os.environ.items() if not name.startswith("GIT_")}
|
|
env["GIT_INDEX_FILE"] = str(Path(directory) / "index")
|
|
env["GIT_OPTIONAL_LOCKS"] = "0"
|
|
run([*git, "read-tree", "HEAD"], cwd=root, env=env)
|
|
run([*git, "add", "-A", "--", "."], cwd=root, env=env)
|
|
tree = run([*git, "write-tree"], cwd=root, env=env).decode().strip()
|
|
if tree == head_tree:
|
|
return Source(commit, False, None)
|
|
return Source(commit, True, f"git-tree:{tree}")
|
|
|
|
|
|
def release_dir(tag: str, root: Path = ROOT) -> Path:
|
|
if not re.fullmatch(r"[0-9a-f]{12}(-dirty)?", tag):
|
|
raise ReleaseError(f"Unexpected release tag {tag!r}.")
|
|
return root / RELEASE_DIR_NAME / tag
|
|
|
|
|
|
def release_image_reference(service: str, release_id: str) -> str:
|
|
validate_release_id(release_id)
|
|
if not re.fullmatch(r"[a-z0-9][a-z0-9_.-]*", service):
|
|
raise ReleaseError(f"Unexpected service name {service!r}.")
|
|
return f"{RELEASE_REGISTRY}/release/{service}:{release_id}"
|
|
|
|
|
|
def manifest_restore_command(release_id: str) -> str:
|
|
validate_release_id(release_id)
|
|
return f"make -C deploy release-up RELEASE_MANIFEST=deploy/release/{release_id}/manifest.json"
|
|
|
|
|
|
def demo_restore_command(release_id: str) -> str:
|
|
validate_release_id(release_id)
|
|
return f"make -C deploy demo-seed DEMO_MODE=isolated RELEASE_MANIFEST=deploy/release/{release_id}/manifest.json"
|
|
|
|
|
|
def relative(path: Path, root: Path = ROOT) -> str:
|
|
try:
|
|
return path.resolve().relative_to(root.resolve()).as_posix()
|
|
except ValueError as error:
|
|
raise ReleaseError("A path outside the repository was referenced.") from error
|
|
|
|
|
|
def display(path: Path, root: Path = ROOT) -> str:
|
|
"""Name a file for messages without revealing where the repository lives."""
|
|
try:
|
|
return path.resolve().relative_to(root.resolve()).as_posix()
|
|
except ValueError:
|
|
return path.name
|
|
|
|
|
|
def file_digest(path: Path) -> str | None:
|
|
try:
|
|
return "sha256:" + hashlib.sha256(path.read_bytes()).hexdigest()
|
|
except OSError:
|
|
return None
|
|
|
|
|
|
def utc_now() -> str:
|
|
return _dt.datetime.now(_dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Dockerfile and toolchain policy
|
|
|
|
ARG_LINE = re.compile(r"^\s*ARG\s+([A-Za-z_][A-Za-z0-9_]*)(?:=(\S+))?\s*$", re.IGNORECASE)
|
|
FROM_LINE = re.compile(r"^\s*FROM\s+(?:--platform=\S+\s+)?(\S+)(?:\s+AS\s+(\S+))?\s*$", re.IGNORECASE)
|
|
ARG_REFERENCE = re.compile(r"^\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?$")
|
|
COPY_FROM = re.compile(r"^\s*(?:COPY|ADD)\b.*?\s--from=(\S+)", re.IGNORECASE)
|
|
MOUNT_FROM = re.compile(r"--mount=\S*?\bfrom=([^,\s]+)", re.IGNORECASE)
|
|
|
|
|
|
def logical_lines(text: str) -> list[tuple[int, str]]:
|
|
"""Join backslash continuations and drop comments, keeping first line numbers."""
|
|
result: list[tuple[int, str]] = []
|
|
buffer: list[str] = []
|
|
start = 0
|
|
for number, line in enumerate(text.splitlines(), start=1):
|
|
if not buffer and line.lstrip().startswith("#"):
|
|
continue
|
|
if not buffer:
|
|
start = number
|
|
stripped = line.rstrip()
|
|
if stripped.endswith("\\"):
|
|
buffer.append(stripped[:-1])
|
|
continue
|
|
buffer.append(stripped)
|
|
result.append((start, " ".join(buffer)))
|
|
buffer = []
|
|
if buffer:
|
|
result.append((start, " ".join(buffer)))
|
|
return result
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class BaseImage:
|
|
arg: str
|
|
default: str
|
|
|
|
|
|
def dockerfile_bases(text: str, source: str = "Dockerfile") -> list[BaseImage]:
|
|
"""Return the base image arguments; fail on any base that cannot be pinned.
|
|
|
|
Every FROM must name an earlier stage or a global ARG ending in _IMAGE with
|
|
a default, so release-build can replace each base with a digest.
|
|
"""
|
|
global_args: dict[str, str | None] = {}
|
|
stages: set[str] = set()
|
|
bases: dict[str, BaseImage] = {}
|
|
seen_from = False
|
|
stage_count = 0
|
|
for number, line in logical_lines(text):
|
|
if not seen_from:
|
|
match = ARG_LINE.match(line)
|
|
if match:
|
|
global_args[match.group(1)] = match.group(2)
|
|
continue
|
|
match = FROM_LINE.match(line)
|
|
if not match:
|
|
for source_ref in COPY_FROM.findall(line) + MOUNT_FROM.findall(line):
|
|
if source_ref not in stages and not (source_ref.isdigit() and int(source_ref) < stage_count):
|
|
raise ReleaseError(
|
|
f"{source}:{number}: --from={source_ref} is not an earlier stage; external images cannot be pinned."
|
|
)
|
|
continue
|
|
seen_from = True
|
|
stage_count += 1
|
|
image, stage = match.group(1), match.group(2)
|
|
if image in stages:
|
|
pass
|
|
else:
|
|
reference = ARG_REFERENCE.match(image)
|
|
if not reference or not reference.group(1).endswith("_IMAGE"):
|
|
raise ReleaseError(f"{source}:{number}: FROM {image} is not a pinnable *_IMAGE build argument.")
|
|
name = reference.group(1)
|
|
default = global_args.get(name)
|
|
if not default:
|
|
raise ReleaseError(f"{source}:{number}: build argument {name} has no default before the first FROM.")
|
|
bases[name] = BaseImage(name, default)
|
|
if stage:
|
|
stages.add(stage)
|
|
if not bases:
|
|
raise ReleaseError(f"{source}: no base image found.")
|
|
return [bases[name] for name in sorted(bases)]
|
|
|
|
|
|
def go_build_pin(dockerfile: str, source: str) -> tuple[str, bool]:
|
|
"""Return the GO_IMAGE default and whether its build stage sets GOTOOLCHAIN=local."""
|
|
bases = {base.arg: base.default for base in dockerfile_bases(dockerfile, source)}
|
|
build_stage = dockerfile.split("FROM ${GO_IMAGE}", 1)[-1].split("\nFROM ", 1)[0]
|
|
return bases.get("GO_IMAGE", ""), bool(re.search(r"^ENV\s+GOTOOLCHAIN=local\s*$", build_stage, re.MULTILINE))
|
|
|
|
|
|
def go_policy(root: Path = ROOT) -> dict[str, Any]:
|
|
"""Describe the Go pin and whether go.mod and every Go build image agree."""
|
|
go_mod = (root / "backend/go.mod").read_text(encoding="utf-8")
|
|
directive = re.search(r"^go\s+(\S+)\s*$", go_mod, re.MULTILINE)
|
|
toolchain = re.search(r"^toolchain\s+(\S+)\s*$", go_mod, re.MULTILINE)
|
|
image, gotoolchain_local = go_build_pin((root / "backend/Dockerfile").read_text(encoding="utf-8"), "backend/Dockerfile")
|
|
image_version = re.match(r"^golang:([0-9]+\.[0-9]+\.[0-9]+)-", image)
|
|
version = directive.group(1) if directive else None
|
|
policy = {
|
|
"go_mod": version,
|
|
"toolchain_directive": toolchain.group(1) if toolchain else None,
|
|
"dockerfile_image": image or None,
|
|
"gotoolchain_local": gotoolchain_local,
|
|
"demo_seed_dockerfile_image": None,
|
|
"demo_seed_gotoolchain_local": None,
|
|
}
|
|
# The demo seed image builds the same module, so it must use the same pin.
|
|
seed_matches = True
|
|
seed_dockerfile = root / SEED_DOCKERFILE
|
|
if seed_dockerfile.is_file():
|
|
seed_image, seed_local = go_build_pin(seed_dockerfile.read_text(encoding="utf-8"), SEED_DOCKERFILE)
|
|
policy["demo_seed_dockerfile_image"] = seed_image or None
|
|
policy["demo_seed_gotoolchain_local"] = seed_local
|
|
seed_matches = bool(seed_image and seed_image == image and seed_local)
|
|
policy["consistent"] = bool(
|
|
version
|
|
and re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+", version)
|
|
and image_version
|
|
and image_version.group(1) == version
|
|
and policy["toolchain_directive"] in (None, f"go{version}")
|
|
and policy["gotoolchain_local"]
|
|
and seed_matches
|
|
)
|
|
return policy
|
|
|
|
|
|
def text_match(path: Path, pattern: str) -> str | None:
|
|
try:
|
|
match = re.search(pattern, path.read_text(encoding="utf-8"), re.MULTILINE)
|
|
except OSError:
|
|
return None
|
|
return match.group(1) if match else None
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Go build information
|
|
|
|
|
|
def go_build_version(binary: bytes) -> str | None:
|
|
"""Return the Go version recorded in a Go 1.18+ binary, or None."""
|
|
magic = b"\xff Go buildinf:"
|
|
start = 0
|
|
while True:
|
|
index = binary.find(magic, start)
|
|
if index < 0:
|
|
return None
|
|
if index % 16 == 0 and len(binary) >= index + 32:
|
|
break
|
|
start = index + 1
|
|
flags = binary[index + 15]
|
|
if not flags & 0x2:
|
|
# Pre-1.18 pointer layout; the release build never produces it.
|
|
return None
|
|
position = index + 32
|
|
length, shift = 0, 0
|
|
while position < len(binary):
|
|
byte = binary[position]
|
|
position += 1
|
|
length |= (byte & 0x7F) << shift
|
|
if not byte & 0x80:
|
|
break
|
|
shift += 7
|
|
version = binary[position : position + length]
|
|
try:
|
|
decoded = version.decode("ascii")
|
|
except UnicodeDecodeError:
|
|
return None
|
|
return decoded if re.fullmatch(r"go[0-9][0-9A-Za-z.+-]*", decoded) else None
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Docker access
|
|
|
|
|
|
def docker_env(extra: dict[str, str] | None = None) -> dict[str, str]:
|
|
"""Return a minimal environment so shell secrets never reach Compose."""
|
|
env = {name: value for name, value in os.environ.items() if name in ("PATH", "HOME", "TMPDIR")}
|
|
env.update({name: value for name, value in os.environ.items() if name.startswith(("DOCKER_", "BUILDKIT_"))})
|
|
env.update(extra or {})
|
|
return env
|
|
|
|
|
|
def render_env(tag: str) -> dict[str, str]:
|
|
"""Environment of a render or build from .env.example under RENDER_PROJECT."""
|
|
return docker_env(
|
|
{
|
|
"APP_PROJECT": RENDER_PROJECT,
|
|
"APP_NETWORK": f"{RENDER_PROJECT}_default",
|
|
"LINCODEX_RELEASE_TAG": tag,
|
|
"IDENTITY_KEY_SECRET": RENDER_ONLY_IDENTITY_KEY,
|
|
"DEMO_ACCOUNT_PASSWORD": RENDER_ONLY_DEMO_PASSWORD,
|
|
}
|
|
)
|
|
|
|
|
|
class Docker:
|
|
"""Thin CLI wrapper; tests replace it with a fake."""
|
|
|
|
def __init__(self, binary: str | None = None) -> None:
|
|
self.binary = binary or os.environ.get("DOCKER", "docker")
|
|
|
|
def inspect_image(self, reference: str) -> dict[str, Any] | None:
|
|
result = subprocess.run(
|
|
[self.binary, "image", "inspect", reference], capture_output=True, check=False, env=docker_env()
|
|
)
|
|
if result.returncode != 0:
|
|
return None
|
|
data = json.loads(result.stdout)
|
|
return data[0] if data else None
|
|
|
|
def compose_config(
|
|
self, files: list[str], tag: str, root: Path = ROOT, profile: str | None = None
|
|
) -> dict[str, Any]:
|
|
args = [self.binary, "compose", "--env-file", str(root / ".env.example"), "-p", RENDER_PROJECT]
|
|
for name in files:
|
|
args += ["-f", str(root / name)]
|
|
if profile:
|
|
args += ["--profile", profile]
|
|
args += ["config", "--format", "json"]
|
|
return json.loads(run(args, cwd=root, env=render_env(tag)))
|
|
|
|
def project_containers(self, project: str) -> list[dict[str, Any]]:
|
|
ids = run(
|
|
[self.binary, "ps", "-q", "--filter", f"label=com.docker.compose.project={project}"], env=docker_env()
|
|
).split()
|
|
if not ids:
|
|
return []
|
|
return json.loads(run([self.binary, "inspect", *[item.decode() for item in ids]], env=docker_env()))
|
|
|
|
def read_file(self, image_id: str, path: str) -> bytes | None:
|
|
"""Copy one file out of an image through a created, never started container."""
|
|
name = f"lincodex-release-inspect-{_secrets.token_hex(6)}"
|
|
created = subprocess.run(
|
|
[self.binary, "create", "--pull", "never", "--name", name, image_id],
|
|
capture_output=True,
|
|
check=False,
|
|
env=docker_env(),
|
|
)
|
|
if created.returncode != 0:
|
|
return None
|
|
try:
|
|
archive = subprocess.run(
|
|
[self.binary, "cp", f"{name}:{path}", "-"], capture_output=True, check=False, env=docker_env()
|
|
)
|
|
if archive.returncode != 0:
|
|
return None
|
|
with tarfile.open(fileobj=io.BytesIO(archive.stdout)) as tar:
|
|
for member in tar.getmembers():
|
|
if member.isfile():
|
|
handle = tar.extractfile(member)
|
|
return handle.read() if handle else None
|
|
return None
|
|
finally:
|
|
subprocess.run([self.binary, "rm", "-f", name], capture_output=True, check=False, env=docker_env())
|
|
|
|
def pull(self, reference: str) -> None:
|
|
print(f"Pulling {reference}", flush=True)
|
|
if subprocess.run([self.binary, "pull", reference], check=False, env=docker_env()).returncode != 0:
|
|
raise ReleaseError(f"Could not pull {reference}.")
|
|
|
|
def compose_build(
|
|
self,
|
|
files: list[str],
|
|
tag: str,
|
|
service: str,
|
|
build_args: dict[str, str],
|
|
root: Path = ROOT,
|
|
profile: str | None = None,
|
|
) -> None:
|
|
args = [self.binary, "compose", "--env-file", str(root / ".env.example"), "-p", RENDER_PROJECT]
|
|
for name in files:
|
|
args += ["-f", str(root / name)]
|
|
if profile:
|
|
args += ["--profile", profile]
|
|
args += ["build"]
|
|
for name, value in sorted(build_args.items()):
|
|
args += ["--build-arg", f"{name}={value}"]
|
|
args.append(service)
|
|
print(f"Building {service} for release {tag}", flush=True)
|
|
if subprocess.run(args, cwd=root, env=render_env(tag), check=False).returncode != 0:
|
|
raise ReleaseError(f"Building {service} failed.")
|
|
|
|
def tag_image(self, image_id: str, reference: str) -> None:
|
|
result = subprocess.run(
|
|
[self.binary, "image", "tag", image_id, reference], capture_output=True, check=False, env=docker_env()
|
|
)
|
|
if result.returncode != 0:
|
|
raise ReleaseError("Could not retain the exact local release image.")
|
|
|
|
def compose_restore_config(
|
|
self, project: str, env_file: Path, tag: str, override: Path, root: Path = ROOT
|
|
) -> dict[str, Any]:
|
|
args = [self.binary, "compose", "--env-file", str(env_file), "-p", project]
|
|
for name in (*CORE_COMPOSE_FILES, str(override)):
|
|
args += ["-f", str(root / name) if not Path(name).is_absolute() else name]
|
|
args += ["config", "--format", "json"]
|
|
env = docker_env(
|
|
{
|
|
"APP_PROJECT": project,
|
|
"APP_NETWORK": f"{project}_default",
|
|
"LINCODEX_RELEASE_TAG": tag,
|
|
}
|
|
)
|
|
result = subprocess.run(args, cwd=root, env=env, capture_output=True, check=False)
|
|
if result.returncode != 0:
|
|
raise ReleaseError("Compose could not render the pinned release configuration.")
|
|
try:
|
|
return json.loads(result.stdout)
|
|
except (UnicodeError, ValueError) as error:
|
|
raise ReleaseError("Compose returned an invalid pinned release configuration.") from error
|
|
|
|
def compose_restore(
|
|
self,
|
|
action: str,
|
|
project: str,
|
|
env_file: Path,
|
|
tag: str,
|
|
override: Path,
|
|
root: Path = ROOT,
|
|
) -> None:
|
|
args = [self.binary, "compose", "--env-file", str(env_file), "-p", project]
|
|
for name in (*CORE_COMPOSE_FILES, str(override)):
|
|
args += ["-f", str(root / name) if not Path(name).is_absolute() else name]
|
|
if action == "up":
|
|
args += ["up", "-d", "--no-build", "--pull", "never", "--wait", "--wait-timeout", "180"]
|
|
else:
|
|
args += ["down"]
|
|
env = docker_env(
|
|
{
|
|
"APP_PROJECT": project,
|
|
"APP_NETWORK": f"{project}_default",
|
|
"LINCODEX_RELEASE_TAG": tag,
|
|
}
|
|
)
|
|
result = subprocess.run(args, cwd=root, env=env, capture_output=True, check=False)
|
|
if result.returncode != 0:
|
|
raise ReleaseError(f"Compose release {action} failed with exit status {result.returncode}.")
|
|
|
|
|
|
def normalize_repository(reference: str) -> str:
|
|
"""Return the repository of an image reference in docker.io long form."""
|
|
name = reference.split("@", 1)[0]
|
|
last = name.rsplit("/", 1)[-1]
|
|
if ":" in last:
|
|
name = name[: name.rfind(":")]
|
|
first = name.split("/", 1)[0]
|
|
if "/" not in name:
|
|
name = f"docker.io/library/{name}"
|
|
elif not ("." in first or ":" in first or first == "localhost"):
|
|
name = f"docker.io/{name}"
|
|
return name
|
|
|
|
|
|
def repo_digest(info: dict[str, Any], reference: str) -> str | None:
|
|
wanted = normalize_repository(reference)
|
|
for item in sorted(info.get("RepoDigests") or []):
|
|
if "@" in item and normalize_repository(item) == wanted:
|
|
return item.split("@", 1)[1]
|
|
return None
|
|
|
|
|
|
def image_versions(info: dict[str, Any], labels: bool = True) -> dict[str, str]:
|
|
"""Copy allowlisted version metadata; built images inherit base labels, so skip them there."""
|
|
versions: dict[str, str] = {}
|
|
for entry in (info.get("Config") or {}).get("Env") or []:
|
|
name, _, value = entry.partition("=")
|
|
if name in VERSION_ENV_KEYS and value:
|
|
versions[name] = value
|
|
image_labels = ((info.get("Config") or {}).get("Labels") or {}) if labels else {}
|
|
for name in VERSION_LABEL_KEYS:
|
|
if image_labels.get(name):
|
|
versions[name] = image_labels[name]
|
|
return versions
|
|
|
|
|
|
def image_record(info: dict[str, Any] | None, reference: str, built: bool = False) -> dict[str, Any]:
|
|
if info is None:
|
|
return {"reference": reference, "present": False}
|
|
platform = "/".join(part for part in (info.get("Os"), info.get("Architecture"), info.get("Variant")) if part)
|
|
return {
|
|
"reference": reference,
|
|
"present": True,
|
|
"image_id": info.get("Id"),
|
|
# A local build has no registry digest; its image ID identifies it.
|
|
"repo_digest": None if built else repo_digest(info, reference),
|
|
"repo_digests": [] if built else sorted(item for item in info.get("RepoDigests") or [] if isinstance(item, str)),
|
|
"platform": platform or None,
|
|
"versions": image_versions(info, labels=not built),
|
|
}
|
|
|
|
|
|
def immutable_image_references(service: Service, image: dict[str, Any], release_id: str) -> tuple[str | None, str | None]:
|
|
if not image.get("present") or not image.get("image_id"):
|
|
return None, None
|
|
if service.dockerfile:
|
|
return image["image_id"], release_image_reference(service.name, release_id)
|
|
digest = image.get("repo_digest")
|
|
if not isinstance(digest, str) or not SHA256_PATTERN.fullmatch(digest):
|
|
return None, None
|
|
return f"{normalize_repository(service.reference)}@{digest}", None
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Compose services
|
|
|
|
|
|
@dataclass
|
|
class Service:
|
|
group: str
|
|
name: str
|
|
reference: str
|
|
dockerfile: str | None = None
|
|
context: str | None = None
|
|
compose_file: str = ""
|
|
overlay: str | None = None
|
|
# Every file and the profile Compose needs to render or build the service.
|
|
render_files: tuple[str, ...] = ()
|
|
profile: str | None = None
|
|
|
|
|
|
def group_files(group: Group) -> list[str]:
|
|
return [*group.base_files, group.compose_file] + ([group.release_overlay] if group.release_overlay else [])
|
|
|
|
|
|
def group_services(docker: Docker, group: Group, tag: str, root: Path = ROOT) -> list[Service]:
|
|
files = group_files(group)
|
|
config = docker.compose_config(files, tag, root, profile=group.profile)
|
|
services: list[Service] = []
|
|
for name, spec in sorted((config.get("services") or {}).items()):
|
|
profiles = spec.get("profiles") or []
|
|
if group.profile:
|
|
# An overlay group renders the core services too; keep only its own.
|
|
if group.profile not in profiles:
|
|
continue
|
|
elif profiles:
|
|
continue
|
|
build = spec.get("build")
|
|
reference = spec.get("image")
|
|
if build:
|
|
if not group.release_overlay or not reference:
|
|
raise ReleaseError(f"Built service {name} has no release image name.")
|
|
context = Path(build["context"])
|
|
dockerfile = context / build.get("dockerfile", "Dockerfile")
|
|
services.append(
|
|
Service(
|
|
group.name,
|
|
name,
|
|
reference,
|
|
relative(dockerfile, root),
|
|
relative(context, root) or ".",
|
|
group.compose_file,
|
|
group.release_overlay,
|
|
tuple(files),
|
|
group.profile,
|
|
)
|
|
)
|
|
elif reference:
|
|
services.append(
|
|
Service(group.name, name, reference, compose_file=group.compose_file, render_files=tuple(files), profile=group.profile)
|
|
)
|
|
return services
|
|
|
|
|
|
def release_reference(service: str, tag: str) -> str:
|
|
return f"{RELEASE_REGISTRY}/{service}:{tag}"
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# build
|
|
|
|
|
|
def ensure_local(docker: Docker, reference: str, pull: str) -> dict[str, Any]:
|
|
info = None if pull == "always" else docker.inspect_image(reference)
|
|
if info is None:
|
|
docker.pull(reference)
|
|
info = docker.inspect_image(reference)
|
|
if info is None:
|
|
raise ReleaseError(f"{reference} is not available locally after pulling.")
|
|
return info
|
|
|
|
|
|
def command_build(args: argparse.Namespace, docker: Docker | None = None, root: Path = ROOT) -> int:
|
|
docker = docker or Docker()
|
|
source = read_source(root)
|
|
policy = go_policy(root)
|
|
if not policy["consistent"]:
|
|
raise ReleaseError(
|
|
"The Go pin is inconsistent: backend/go.mod, the toolchain directive, the GO_IMAGE defaults, "
|
|
"and ENV GOTOOLCHAIN=local in backend/Dockerfile and backend/Dockerfile.demo-seed must agree."
|
|
)
|
|
record: dict[str, Any] = {
|
|
"schema": BUILD_SCHEMA,
|
|
"tag": source.tag,
|
|
"commit": source.commit,
|
|
"dirty": source.dirty,
|
|
"source_fingerprint": source.fingerprint,
|
|
"built_at": utc_now(),
|
|
"services": {},
|
|
}
|
|
for group in GROUPS:
|
|
if group.release_overlay is None:
|
|
continue
|
|
for service in group_services(docker, group, source.tag, root):
|
|
if service.dockerfile is None:
|
|
ensure_local(docker, service.reference, args.pull)
|
|
continue
|
|
text = (root / service.dockerfile).read_text(encoding="utf-8")
|
|
build_args: dict[str, str] = {}
|
|
bases = []
|
|
for base in dockerfile_bases(text, service.dockerfile):
|
|
info = ensure_local(docker, base.default, args.pull)
|
|
digest = repo_digest(info, base.default)
|
|
if not digest:
|
|
raise ReleaseError(f"{base.default} has no repository digest; pull it from its registry first.")
|
|
pinned = f"{base.default}@{digest}"
|
|
build_args[base.arg] = pinned
|
|
bases.append(
|
|
{"arg": base.arg, "reference": base.default, "digest": digest, "versions": image_versions(info)}
|
|
)
|
|
files = list(service.render_files) or [service.compose_file] + ([service.overlay] if service.overlay else [])
|
|
docker.compose_build(files, source.tag, service.name, build_args, root, profile=service.profile)
|
|
info = docker.inspect_image(service.reference)
|
|
if info is None:
|
|
raise ReleaseError(f"{service.reference} is missing after the build.")
|
|
record["services"][service.name] = {
|
|
"reference": service.reference,
|
|
"image_id": info.get("Id"),
|
|
"dockerfile": service.dockerfile,
|
|
"dockerfile_digest": file_digest(root / service.dockerfile),
|
|
"context": service.context,
|
|
"build_args": build_args,
|
|
"base_images": bases,
|
|
}
|
|
after = read_source(root)
|
|
if (after.commit, after.fingerprint) != (source.commit, source.fingerprint):
|
|
raise ReleaseError(
|
|
"The source changed during the build, so the images may not match any one source state; "
|
|
"build.json was not written. Rebuild from a tree that does not change."
|
|
)
|
|
path = release_dir(source.tag, root) / "build.json"
|
|
write_json(path, record, root)
|
|
print(f"Release images built for {source.tag}; build record: {display(path, root)}")
|
|
if source.dirty:
|
|
print("The working tree is dirty: a manifest for these images stays unverified.")
|
|
return 0
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# require-images and record-evidence
|
|
|
|
|
|
def command_require_images(args: argparse.Namespace, docker: Docker | None = None, root: Path = ROOT) -> int:
|
|
docker = docker or Docker()
|
|
source = read_source(root)
|
|
expect_tag(args, source)
|
|
group = next(item for item in GROUPS if item.name == args.group)
|
|
missing = [
|
|
service.reference
|
|
for service in group_services(docker, group, source.tag, root)
|
|
if docker.inspect_image(service.reference) is None
|
|
]
|
|
if missing:
|
|
raise ReleaseError(
|
|
"Missing local images: " + ", ".join(missing) + ". Run make -C deploy release-build first."
|
|
)
|
|
return 0
|
|
|
|
|
|
def expect_tag(args: argparse.Namespace, source: Source) -> None:
|
|
if getattr(args, "tag", None) and args.tag != source.tag:
|
|
raise ReleaseError(f"The working tree is now release {source.tag}, not {args.tag}; rebuild and rerun.")
|
|
|
|
|
|
def running_services(containers: list[dict[str, Any]]) -> dict[str, dict[str, Any]]:
|
|
services: dict[str, dict[str, Any]] = {}
|
|
for container in containers:
|
|
labels = (container.get("Config") or {}).get("Labels") or {}
|
|
if labels.get("com.docker.compose.oneoff", "False") == "True":
|
|
continue
|
|
if not (container.get("State") or {}).get("Running"):
|
|
continue
|
|
name = labels.get("com.docker.compose.service")
|
|
if name:
|
|
services[name] = {
|
|
"reference": (container.get("Config") or {}).get("Image"),
|
|
"image_id": container.get("Image"),
|
|
}
|
|
return services
|
|
|
|
|
|
def command_record_evidence(args: argparse.Namespace, docker: Docker | None = None, root: Path = ROOT) -> int:
|
|
docker = docker or Docker()
|
|
source = read_source(root)
|
|
expect_tag(args, source)
|
|
group = next(item for item in GROUPS if item.name == "core")
|
|
expected = group_services(docker, group, source.tag, root)
|
|
running = running_services(docker.project_containers(args.project))
|
|
services: dict[str, Any] = {}
|
|
for service in expected:
|
|
actual = running.get(service.name)
|
|
if actual is None:
|
|
raise ReleaseError(f"Service {service.name} is not running in project {args.project}.")
|
|
if actual["reference"] != service.reference:
|
|
raise ReleaseError(f"Service {service.name} runs {actual['reference']}, not {service.reference}.")
|
|
services[service.name] = actual
|
|
tools: dict[str, Any] = {}
|
|
for item in args.tool_image or []:
|
|
name, _, reference = item.partition("=")
|
|
info = docker.inspect_image(reference)
|
|
if info is None:
|
|
raise ReleaseError(f"Tool image {reference} is not present locally.")
|
|
tools[name] = {"reference": reference, "image_id": info.get("Id")}
|
|
evidence = {
|
|
"schema": EVIDENCE_SCHEMA,
|
|
"check": args.check,
|
|
"result": "passed",
|
|
"tag": source.tag,
|
|
"commit": source.commit,
|
|
"source_fingerprint": source.fingerprint,
|
|
"finished_at": utc_now(),
|
|
"services": services,
|
|
"tool_images": tools,
|
|
}
|
|
path = release_dir(source.tag, root) / f"evidence-{args.check}.json"
|
|
write_json(path, evidence, root)
|
|
print(f"Recorded passing {args.check} evidence for {source.tag}: {display(path, root)}")
|
|
return 0
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# manifest
|
|
|
|
|
|
def load_json(path: Path) -> dict[str, Any] | None:
|
|
try:
|
|
document = json.loads(path.read_text(encoding="utf-8"))
|
|
except (OSError, ValueError):
|
|
return None
|
|
return document if isinstance(document, dict) else None
|
|
|
|
|
|
IMAGE_ID = re.compile(r"sha256:[0-9a-f]+")
|
|
|
|
|
|
def _is_str_map(value: Any) -> bool:
|
|
return isinstance(value, dict) and all(isinstance(k, str) and isinstance(v, str) for k, v in value.items())
|
|
|
|
|
|
def _is_image_map(value: Any) -> bool:
|
|
return isinstance(value, dict) and all(
|
|
isinstance(name, str)
|
|
and isinstance(item, dict)
|
|
and isinstance(item.get("reference"), str)
|
|
and isinstance(item.get("image_id"), str)
|
|
and IMAGE_ID.fullmatch(item["image_id"])
|
|
for name, item in value.items()
|
|
)
|
|
|
|
|
|
def evidence_problem(document: dict[str, Any], check: str, source: Source) -> str | None:
|
|
"""Return why an evidence document cannot count for this source, or None."""
|
|
if (
|
|
document.get("schema") != EVIDENCE_SCHEMA
|
|
or document.get("check") != check
|
|
or document.get("result") != "passed"
|
|
or not isinstance(document.get("finished_at"), str)
|
|
or not isinstance(document.get("tag"), str)
|
|
or not isinstance(document.get("commit"), str)
|
|
or not isinstance(document.get("source_fingerprint"), (str, type(None)))
|
|
or not _is_image_map(document.get("services"))
|
|
or not _is_image_map(document.get("tool_images", {}))
|
|
):
|
|
return "The evidence file is malformed."
|
|
if document["tag"] != source.tag:
|
|
return "The evidence was recorded for another release tag."
|
|
if document["commit"] != source.commit:
|
|
return "The evidence was recorded for another commit."
|
|
if document["source_fingerprint"] != source.fingerprint:
|
|
return "The evidence was recorded for another working tree state."
|
|
return None
|
|
|
|
|
|
def accept_evidence(
|
|
documents: dict[str, dict[str, Any] | None], source: Source
|
|
) -> tuple[dict[str, dict[str, Any]], dict[str, str]]:
|
|
"""Split evidence into documents bound to this exact source and rejected ones."""
|
|
accepted: dict[str, dict[str, Any]] = {}
|
|
rejected: dict[str, str] = {}
|
|
for check, document in sorted(documents.items()):
|
|
if document is None:
|
|
continue
|
|
problem = evidence_problem(document, check, source)
|
|
if problem:
|
|
rejected[check] = problem
|
|
else:
|
|
accepted[check] = document
|
|
return accepted, rejected
|
|
|
|
|
|
def build_record_problem(document: dict[str, Any]) -> str | None:
|
|
services = document.get("services")
|
|
if (
|
|
document.get("schema") != BUILD_SCHEMA
|
|
or not isinstance(document.get("commit"), str)
|
|
or not isinstance(document.get("source_fingerprint"), (str, type(None)))
|
|
or not isinstance(services, dict)
|
|
):
|
|
return "The build record is malformed."
|
|
for item in services.values():
|
|
bases = item.get("base_images") if isinstance(item, dict) else None
|
|
if (
|
|
not isinstance(item, dict)
|
|
or not isinstance(item.get("image_id"), str)
|
|
or not _is_str_map(item.get("build_args"))
|
|
or not isinstance(bases, list)
|
|
or not all(
|
|
isinstance(base, dict)
|
|
and all(isinstance(base.get(key), str) for key in ("arg", "reference", "digest"))
|
|
and _is_str_map(base.get("versions", {}))
|
|
for base in bases
|
|
)
|
|
):
|
|
return "The build record is malformed."
|
|
return None
|
|
|
|
|
|
@dataclass
|
|
class Inputs:
|
|
"""Everything the manifest is derived from, so tests can supply fakes."""
|
|
|
|
source: Source
|
|
services: list[Service]
|
|
images: dict[str, dict[str, Any] | None]
|
|
build_record: dict[str, Any] | None
|
|
evidence: dict[str, dict[str, Any]]
|
|
go_binary: str | None
|
|
go: dict[str, Any]
|
|
files: dict[str, str | None] = field(default_factory=dict)
|
|
rejected_checks: dict[str, str] = field(default_factory=dict)
|
|
build_problem: str | None = None
|
|
seed_go_binary: str | None = None
|
|
|
|
|
|
def image_go_version(docker: Docker, info: dict[str, Any] | None) -> str | None:
|
|
"""Return the Go version recorded in the entrypoint binary of a local image."""
|
|
if not info:
|
|
return None
|
|
entrypoint = (info.get("Config") or {}).get("Entrypoint") or []
|
|
if not entrypoint:
|
|
return None
|
|
content = docker.read_file(info["Id"], entrypoint[0])
|
|
return go_build_version(content) if content else None
|
|
|
|
|
|
def collect_inputs(docker: Docker, root: Path = ROOT) -> Inputs:
|
|
source = read_source(root)
|
|
services: list[Service] = []
|
|
for group in GROUPS:
|
|
services.extend(group_services(docker, group, source.tag, root))
|
|
images = {service.reference: docker.inspect_image(service.reference) for service in services}
|
|
directory = release_dir(source.tag, root)
|
|
evidence, rejected = accept_evidence(
|
|
{check: load_json(directory / f"evidence-{check}.json") for check in CHECKS}, source
|
|
)
|
|
build = load_json(directory / "build.json")
|
|
build_problem = build_record_problem(build) if build is not None else None
|
|
if build_problem:
|
|
build = None
|
|
go_binary = image_go_version(docker, images.get(release_reference("backend", source.tag)))
|
|
seed_go_binary = image_go_version(docker, images.get(release_reference(DEMO_SEED_SERVICE, source.tag)))
|
|
files = {name: file_digest(root / name) for name in LOCKFILES}
|
|
files[".node-version"] = text_match(root / "frontend/.node-version", r"^\s*(\S+)\s*$")
|
|
files["packageManager"] = text_match(root / "frontend/package.json", r'"packageManager":\s*"([^"]+)"')
|
|
files["dockerfile_pnpm"] = text_match(root / "frontend/Dockerfile", r"pnpm@([0-9][^\s\"]*)")
|
|
files["playwright"] = text_match(root / "frontend/package.json", r'"@playwright/test":\s*"([^"]+)"')
|
|
files[".python-version"] = text_match(root / "ml/.python-version", r"^\s*(\S+)\s*$")
|
|
files["requires-python"] = text_match(root / "ml/pyproject.toml", r'^requires-python\s*=\s*"([^"]+)"')
|
|
files["dockerfile_uv"] = text_match(root / "ml/Dockerfile", r"uv==([0-9][^\s\"]*)")
|
|
for service in services:
|
|
if service.dockerfile:
|
|
files[service.dockerfile] = file_digest(root / service.dockerfile)
|
|
return Inputs(
|
|
source, services, images, build, evidence, go_binary, go_policy(root), files, rejected, build_problem, seed_go_binary
|
|
)
|
|
|
|
|
|
def base_version(build: dict[str, Any] | None, service: str, key: str) -> str | None:
|
|
if not build:
|
|
return None
|
|
for base in (build.get("services", {}).get(service) or {}).get("base_images", []):
|
|
if key in (base.get("versions") or {}):
|
|
return base["versions"][key]
|
|
return None
|
|
|
|
|
|
def build_manifest(
|
|
inputs: Inputs,
|
|
generated_at: str,
|
|
release_id: str | None = None,
|
|
data_versions: dict[str, Any] | None = None,
|
|
compose_files: dict[str, str | None] | None = None,
|
|
root: Path = ROOT,
|
|
) -> dict[str, Any]:
|
|
release_id = validate_release_id(release_id or inputs.source.tag)
|
|
data_versions = data_versions if data_versions is not None else default_data_versions(root)
|
|
compose_files = compose_files if compose_files is not None else {
|
|
name: file_digest(root / name) for name in RELEASE_COMPOSE_FILES
|
|
}
|
|
source = inputs.source
|
|
build = inputs.build_record
|
|
files = inputs.files
|
|
build_matches_source = bool(
|
|
build and build.get("commit") == source.commit and build.get("source_fingerprint") == source.fingerprint
|
|
)
|
|
components: list[dict[str, Any]] = []
|
|
reasons: list[str] = []
|
|
restore_reasons: list[str] = []
|
|
demo_reasons: list[str] = []
|
|
demo_present = False
|
|
for service in inputs.services:
|
|
image = image_record(inputs.images.get(service.reference), service.reference, built=bool(service.dockerfile))
|
|
image["restore_reference"], image["retention_reference"] = immutable_image_references(service, image, release_id)
|
|
if service.group == "core" and image["restore_reference"] is None:
|
|
restore_reasons.append(f"Core component {service.name} has no immutable local image reference.")
|
|
if service.group == "demo":
|
|
demo_present = demo_present or bool(image.get("present"))
|
|
if image["restore_reference"] is None:
|
|
demo_reasons.append(f"Demo component {service.name} has no immutable local image reference.")
|
|
component: dict[str, Any] = {
|
|
"name": service.name,
|
|
"group": service.group,
|
|
"kind": "built" if service.dockerfile else "pulled",
|
|
"compose_file": service.compose_file,
|
|
"image": image,
|
|
}
|
|
if service.dockerfile:
|
|
recorded = (build or {}).get("services", {}).get(service.name)
|
|
matches = bool(recorded and image.get("present") and recorded.get("image_id") == image.get("image_id"))
|
|
component["build"] = {
|
|
"dockerfile": service.dockerfile,
|
|
"dockerfile_digest": files.get(service.dockerfile),
|
|
"context": service.context,
|
|
"recorded_by_release_build": matches,
|
|
"build_args": recorded.get("build_args", {}) if matches else {},
|
|
"base_images": recorded.get("base_images", []) if matches else [],
|
|
}
|
|
if not matches:
|
|
component["build"]["reason"] = "The local image was not built by release-build for this tag."
|
|
if component["build"]["dockerfile_digest"] is None:
|
|
reasons.append(f"The Dockerfile of {service.name} is missing.")
|
|
group = next(item for item in GROUPS if item.name == service.group)
|
|
if not image.get("present"):
|
|
verification = {"status": "not_verified", "reason": "The image is not present locally.", "checks": []}
|
|
elif not group.verifiable:
|
|
verification = {"status": "not_verified", "reason": group.unverified_reason, "checks": []}
|
|
else:
|
|
passed = sorted(
|
|
check
|
|
for check, document in inputs.evidence.items()
|
|
if (document.get("services", {}).get(service.name) or {}).get("image_id") == image.get("image_id")
|
|
)
|
|
if passed:
|
|
verification = {"status": "verified", "checks": passed}
|
|
else:
|
|
verification = {
|
|
"status": "not_verified",
|
|
"reason": "No passing smoke or E2E run of this source state is recorded for this image ID.",
|
|
"checks": [],
|
|
}
|
|
component["verification"] = verification
|
|
components.append(component)
|
|
if service.group == "core":
|
|
if verification["status"] != "verified":
|
|
reasons.append(f"Core component {service.name} is not verified.")
|
|
elif set(verification["checks"]) != set(CHECKS):
|
|
reasons.append("Smoke and E2E were not both recorded for the current core images.")
|
|
if service.dockerfile and not component["build"]["recorded_by_release_build"]:
|
|
reasons.append(f"Core image {service.name} was not built by release-build.")
|
|
if not service.dockerfile and image.get("present") and not image.get("repo_digest"):
|
|
reasons.append(f"Core image {service.name} has no registry digest.")
|
|
if service.group == "demo" and service.dockerfile and not component["build"]["recorded_by_release_build"]:
|
|
demo_reasons.append(f"Demo image {service.name} was not built by release-build for this tag.")
|
|
if not any(service.group == "demo" for service in inputs.services):
|
|
demo_reasons.append("No demo seed service was found in the demo stand Compose files.")
|
|
for name, reason in sorted(MISSING_COMPONENTS.items()):
|
|
components.append(
|
|
{
|
|
"name": name,
|
|
"group": "missing",
|
|
"kind": "absent",
|
|
"image": None,
|
|
"verification": {"status": "missing", "reason": reason, "checks": []},
|
|
}
|
|
)
|
|
components.sort(key=lambda item: (COMPONENT_GROUP_ORDER.index(item["group"]), item["name"]))
|
|
|
|
go = dict(inputs.go)
|
|
go["build_image_version"] = base_version(build, "backend", "GOLANG_VERSION")
|
|
go["binary"] = inputs.go_binary
|
|
go["binary_matches"] = bool(go["go_mod"] and inputs.go_binary == f"go{go['go_mod']}")
|
|
if not go["consistent"]:
|
|
reasons.append("The Go pin in go.mod and backend/Dockerfile is inconsistent.")
|
|
if not go["binary_matches"]:
|
|
reasons.append("The backend binary was not confirmed to be built with the go.mod Go version.")
|
|
go["demo_seed_binary"] = inputs.seed_go_binary
|
|
go["demo_seed_binary_matches"] = bool(go["go_mod"] and inputs.seed_go_binary == f"go{go['go_mod']}")
|
|
if demo_present and not go["demo_seed_binary_matches"]:
|
|
# The demo seed image is delivered with the release, so a Go drift in
|
|
# it is a silent toolchain change too.
|
|
reasons.append("The demo seed binary was not confirmed to be built with the go.mod Go version.")
|
|
demo_reasons.append("The demo seed binary was not confirmed to be built with the go.mod Go version.")
|
|
|
|
node_image = base_version(build, "frontend", "NODE_VERSION")
|
|
node_matches = bool(node_image and node_image == files.get(".node-version"))
|
|
if node_image and not node_matches:
|
|
reasons.append("Node in the frontend build image differs from frontend/.node-version.")
|
|
python_image = base_version(build, "ml", "PYTHON_VERSION")
|
|
# ML is outside the release scope, so a Python mismatch is reported but
|
|
# does not keep the core release unverified.
|
|
python_matches = bool(python_image and python_image == files.get(".python-version"))
|
|
|
|
for name in LOCKFILES:
|
|
if files.get(name) is None:
|
|
reasons.append(f"Lockfile {name} is missing.")
|
|
if source.dirty:
|
|
reasons.append("The working tree has uncommitted changes.")
|
|
if inputs.build_problem:
|
|
reasons.append(inputs.build_problem)
|
|
if not build_matches_source:
|
|
reasons.append("The build record does not match the current source state.")
|
|
for check, problem in sorted(inputs.rejected_checks.items()):
|
|
reasons.append(f"{check} evidence was not accepted: {problem}")
|
|
|
|
for name, digest in sorted(compose_files.items()):
|
|
if digest is None:
|
|
(demo_reasons if name in DEMO_COMPOSE_FILES else restore_reasons).append(f"Compose file {name} is missing.")
|
|
if any(name not in compose_files for name in DEMO_COMPOSE_FILES):
|
|
demo_reasons.append("The demo stand Compose files are not recorded.")
|
|
if restore_reasons:
|
|
demo_reasons.append("The core restore is blocked.")
|
|
data_states = [data_versions[name]["status"] for name in DATA_COMPONENTS]
|
|
product_data_status = "versioned" if all(state == "available" for state in data_states) else (
|
|
"partial" if any(state == "available" for state in data_states) else "unavailable"
|
|
)
|
|
restore_command = manifest_restore_command(release_id)
|
|
|
|
checks = {}
|
|
for name, document in sorted(inputs.evidence.items()):
|
|
checks[name] = {
|
|
"scope": CHECK_SCOPE[name],
|
|
"finished_at": document.get("finished_at"),
|
|
"commit": document.get("commit"),
|
|
"source_fingerprint": document.get("source_fingerprint"),
|
|
"tool_images": document.get("tool_images", {}),
|
|
"image_ids": {
|
|
service: evidence.get("image_id")
|
|
for service, evidence in sorted((document.get("services") or {}).items())
|
|
},
|
|
}
|
|
|
|
return {
|
|
"schema": MANIFEST_SCHEMA,
|
|
"generated_at": generated_at,
|
|
"release": {
|
|
"id": release_id,
|
|
"tag": source.tag,
|
|
"status": "unverified" if reasons else "verified",
|
|
"scope": "core",
|
|
"product_data_status": product_data_status,
|
|
"required_checks": list(CHECKS),
|
|
"reasons": sorted(set(reasons)),
|
|
},
|
|
"restore": {
|
|
"status": "blocked" if restore_reasons else "available",
|
|
"scope": "core",
|
|
"command": restore_command,
|
|
"reasons": sorted(set(restore_reasons)),
|
|
"demo": {
|
|
"status": "blocked" if demo_reasons else "available",
|
|
"command": demo_restore_command(release_id),
|
|
"reasons": sorted(set(demo_reasons)),
|
|
},
|
|
},
|
|
"source": {
|
|
"commit": source.commit,
|
|
"dirty": source.dirty,
|
|
"fingerprint": source.fingerprint,
|
|
"build_matches_source": build_matches_source,
|
|
},
|
|
"toolchains": {
|
|
"go": go,
|
|
"node": {
|
|
"node_version_file": files.get(".node-version"),
|
|
"package_manager": files.get("packageManager"),
|
|
"dockerfile_pnpm": files.get("dockerfile_pnpm"),
|
|
"build_image_version": node_image,
|
|
"matches_version_file": node_matches,
|
|
},
|
|
"python": {
|
|
"python_version_file": files.get(".python-version"),
|
|
"requires_python": files.get("requires-python"),
|
|
"dockerfile_uv": files.get("dockerfile_uv"),
|
|
"build_image_version": python_image,
|
|
"matches_version_file": python_matches,
|
|
},
|
|
"playwright": {"package_version": files.get("playwright")},
|
|
},
|
|
"lockfiles": {name: files.get(name) for name in LOCKFILES},
|
|
"configuration": {"compose_files": dict(sorted(compose_files.items()))},
|
|
"data_versions": data_versions,
|
|
"checks": checks,
|
|
"rejected_checks": dict(sorted(inputs.rejected_checks.items())),
|
|
"components": components,
|
|
}
|
|
|
|
|
|
def comparable(document: dict[str, Any] | None) -> dict[str, Any] | None:
|
|
if document is None:
|
|
return None
|
|
return {key: value for key, value in document.items() if key != "generated_at"}
|
|
|
|
|
|
def block_restore(section: dict[str, Any], problem: str) -> None:
|
|
section["status"] = "blocked"
|
|
section["reasons"] = sorted(set(section["reasons"] + [problem]))
|
|
|
|
|
|
def add_restore_problem(manifest: dict[str, Any], problem: str, group: str = "core") -> None:
|
|
"""Block the restore of a group; the demo stand also needs the core images."""
|
|
restore = manifest["restore"]
|
|
if group == "core":
|
|
block_restore(restore, problem)
|
|
problem = "The core restore is blocked."
|
|
if isinstance(restore.get("demo"), dict):
|
|
block_restore(restore["demo"], problem)
|
|
|
|
|
|
def prepare_manifest_images(manifest: dict[str, Any], docker: Docker) -> None:
|
|
"""Retain built core and demo image IDs and confirm pulled digests before publication."""
|
|
for component in manifest["components"]:
|
|
group = component.get("group")
|
|
if group not in ("core", "demo"):
|
|
continue
|
|
label = "Core" if group == "core" else "Demo"
|
|
image = component.get("image") or {}
|
|
reference = image.get("restore_reference")
|
|
retention_reference = image.get("retention_reference")
|
|
image_id = image.get("image_id")
|
|
if not image.get("present") or not isinstance(image_id, str) or not reference:
|
|
add_restore_problem(
|
|
manifest, f"{label} component {component.get('name')} has no immutable local image reference.", group
|
|
)
|
|
continue
|
|
if component.get("kind") == "built":
|
|
if reference != image_id or not retention_reference:
|
|
add_restore_problem(manifest, f"Built image {component.get('name')} is not pinned to its image ID.", group)
|
|
continue
|
|
existing = docker.inspect_image(retention_reference)
|
|
if existing is None:
|
|
source = docker.inspect_image(image_id)
|
|
if source is None or source.get("Id") != image_id:
|
|
add_restore_problem(manifest, f"Exact local image {image_id} for {component.get('name')} is missing.", group)
|
|
continue
|
|
docker.tag_image(image_id, retention_reference)
|
|
existing = docker.inspect_image(retention_reference)
|
|
if existing is None or existing.get("Id") != image_id:
|
|
raise ReleaseError(f"Retained image reference for {component.get('name')} does not match {image_id}.")
|
|
else:
|
|
existing = docker.inspect_image(reference)
|
|
if existing is None or existing.get("Id") != image_id:
|
|
add_restore_problem(
|
|
manifest, f"Pulled digest for {component.get('name')} does not resolve to the recorded image ID.", group
|
|
)
|
|
if manifest["restore"]["reasons"]:
|
|
manifest["restore"]["status"] = "blocked"
|
|
|
|
|
|
def require_verified_release(manifest: dict[str, Any]) -> None:
|
|
"""Reject public publication unless the candidate passed every release check."""
|
|
release = manifest.get("release")
|
|
if isinstance(release, dict) and release.get("status") == "verified":
|
|
return
|
|
|
|
reasons = release.get("reasons") if isinstance(release, dict) else None
|
|
details = (
|
|
"; ".join(reason for reason in reasons if isinstance(reason, str))
|
|
if isinstance(reasons, list)
|
|
else ""
|
|
)
|
|
message = "Refusing to publish an unverified release manifest; no manifest was written."
|
|
if details:
|
|
message += " " + details
|
|
raise ReleaseError(message)
|
|
|
|
|
|
def manifest_file(path_text: str | None, root: Path = ROOT) -> Path:
|
|
if not path_text:
|
|
return default_manifest(root)
|
|
path = Path(path_text)
|
|
candidates = [path] if path.is_absolute() else [root / path, root / "deploy" / path]
|
|
for candidate in candidates:
|
|
if candidate.exists():
|
|
try:
|
|
candidate.resolve(strict=True).relative_to(root.resolve())
|
|
except (OSError, ValueError) as error:
|
|
raise ReleaseError("Release manifest must be inside the repository.") from error
|
|
if candidate.is_symlink():
|
|
raise ReleaseError("Release manifest cannot be a symlink.")
|
|
return candidate
|
|
return candidates[0]
|
|
|
|
|
|
def validate_manifest_location(path: Path, manifest: dict[str, Any], root: Path = ROOT) -> None:
|
|
release_info = manifest.get("release") or {}
|
|
release_id = release_info.get("id") if isinstance(release_info, dict) else None
|
|
try:
|
|
expected = release_artifact_dir(release_id, root) / "manifest.json"
|
|
actual = path.resolve(strict=True)
|
|
expected_path = expected.resolve(strict=False)
|
|
except (OSError, ReleaseError, TypeError, ValueError) as error:
|
|
raise ReleaseError("Release manifest is not stored under its immutable release ID.") from error
|
|
if actual != expected_path:
|
|
raise ReleaseError("Release manifest is not stored under its immutable release ID.")
|
|
|
|
|
|
def load_manifest(path: Path, root: Path = ROOT) -> dict[str, Any]:
|
|
try:
|
|
if path.stat().st_size > 4 * 1024 * 1024:
|
|
raise ReleaseError("Release manifest exceeds the 4 MiB limit.")
|
|
document = json.loads(path.read_text(encoding="utf-8"))
|
|
except ReleaseError:
|
|
raise
|
|
except (OSError, UnicodeError, ValueError) as error:
|
|
raise ReleaseError(f"No readable release manifest at {display(path, root)}.") from error
|
|
if not isinstance(document, dict):
|
|
raise ReleaseError(f"No readable release manifest at {display(path, root)}.")
|
|
return document
|
|
|
|
|
|
def command_manifest(args: argparse.Namespace, docker: Docker | None = None, root: Path = ROOT) -> int:
|
|
docker = docker or Docker()
|
|
inputs = collect_inputs(docker, root)
|
|
release_id = validate_release_id(args.release_id or inputs.source.tag)
|
|
data_versions = read_data_versions(args.data_manifest, root)
|
|
compose_files = {name: file_digest(root / name) for name in RELEASE_COMPOSE_FILES}
|
|
manifest = build_manifest(inputs, utc_now(), release_id, data_versions, compose_files, root)
|
|
require_verified_release(manifest)
|
|
path = release_artifact_dir(release_id, root) / "manifest.json"
|
|
with immutable_release_lock(release_id, root):
|
|
if path.exists():
|
|
previous = load_manifest(path, root)
|
|
if comparable(previous) != comparable(manifest):
|
|
raise ReleaseError(
|
|
f"Immutable release {release_id} already exists at {display(path, root)}. "
|
|
"Use a new RELEASE_ID for a separate delivery."
|
|
)
|
|
print(f"Release manifest: {display(path, root)} (unchanged)")
|
|
print(
|
|
f"Release {release_id}: core {manifest['release']['status']}; "
|
|
f"product data {manifest['release']['product_data_status']}; restore {manifest['restore']['status']}"
|
|
)
|
|
return 0
|
|
prepare_manifest_images(manifest, docker)
|
|
published = write_json_immutable(path, manifest, root)
|
|
print(f"Release manifest: {display(path, root)}")
|
|
print(
|
|
f"Release {release_id} ({manifest['release']['tag']}): core {manifest['release']['status']}; "
|
|
f"product data {manifest['release']['product_data_status']}; restore {manifest['restore']['status']}"
|
|
)
|
|
for reason in manifest["release"]["reasons"]:
|
|
print(f" - {reason}")
|
|
for reason in manifest["restore"]["reasons"]:
|
|
print(f" - restore blocked: {reason}")
|
|
demo = manifest["restore"]["demo"]
|
|
print(f"Demo stand restore {demo['status']}: {demo['command']}")
|
|
for reason in demo["reasons"]:
|
|
print(f" - demo restore blocked: {reason}")
|
|
for component in manifest["components"]:
|
|
image = component["image"] or {}
|
|
status = component["verification"]["status"]
|
|
presence = "" if component["image"] is None or image.get("present") else " (image missing locally)"
|
|
print(f" {component['group']:<10} {component['name']:<20} {status}{presence}")
|
|
if not published:
|
|
print("The existing manifest was preserved unchanged.")
|
|
return 0
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# verify and check
|
|
|
|
|
|
def default_manifest(root: Path = ROOT) -> Path:
|
|
return release_artifact_dir(read_source(root).tag, root) / "manifest.json"
|
|
|
|
|
|
def compare_running(manifest: dict[str, Any], running: dict[str, dict[str, Any]]) -> tuple[bool, list[str]]:
|
|
components = {
|
|
item["name"]: item for item in manifest.get("components", []) if item.get("group") != "missing"
|
|
}
|
|
groups = {components[name]["group"] for name in running if name in components}
|
|
ok = True
|
|
lines: list[str] = []
|
|
if not running:
|
|
return False, ["No running containers found in the project."]
|
|
for name in sorted(running):
|
|
if name not in components:
|
|
ok = False
|
|
lines.append(f"{name:<16} UNKNOWN runs {running[name]['reference']}, which the manifest does not list")
|
|
for name, component in sorted(components.items()):
|
|
if component["group"] not in groups:
|
|
continue
|
|
image = component.get("image") or {}
|
|
versions = " ".join(f"{key}={value}" for key, value in sorted((image.get("versions") or {}).items()))
|
|
if name not in running:
|
|
ok = False
|
|
lines.append(f"{name:<16} MISSING not running")
|
|
continue
|
|
actual = running[name]
|
|
if not image.get("present"):
|
|
ok = False
|
|
lines.append(f"{name:<16} MISMATCH the manifest has no image ID for {image.get('reference')}")
|
|
elif actual["image_id"] != image.get("image_id"):
|
|
ok = False
|
|
lines.append(
|
|
f"{name:<16} MISMATCH runs {actual['image_id']}, manifest {image.get('image_id')} ({image.get('reference')})"
|
|
)
|
|
else:
|
|
note = "" if actual["reference"] == image.get("reference") else f" (started as {actual['reference']})"
|
|
lines.append(
|
|
f"{name:<16} OK {image.get('reference')} {image.get('image_id')}{note}"
|
|
+ (f" {versions}" if versions else "")
|
|
)
|
|
go_binary = (manifest.get("toolchains", {}).get("go") or {}).get("binary")
|
|
if "backend" in running and go_binary:
|
|
lines.append(f"backend binary built with {go_binary} (from the manifest)")
|
|
return ok, lines
|
|
|
|
|
|
def command_verify(args: argparse.Namespace, docker: Docker | None = None, root: Path = ROOT) -> int:
|
|
docker = docker or Docker()
|
|
path = manifest_file(args.manifest, root)
|
|
manifest = load_manifest(path, root)
|
|
validate_manifest_location(path, manifest, root)
|
|
problems = structure_errors(manifest, root)
|
|
if problems:
|
|
raise ReleaseError(f"Release manifest at {display(path, root)} is invalid: " + "; ".join(problems))
|
|
running = running_services(docker.project_containers(args.project))
|
|
ok, lines = compare_running(manifest, running)
|
|
release_info = manifest.get("release") or {}
|
|
print(
|
|
f"Project {args.project} against {display(path, root)} "
|
|
f"(release {release_info.get('tag')}, status {release_info.get('status')}):"
|
|
)
|
|
for line in lines:
|
|
print(f" {line}")
|
|
print("All running containers match the manifest." if ok else "Running containers differ from the manifest.")
|
|
return 0 if ok else 1
|
|
|
|
|
|
REQUIRED_KEYS = (
|
|
"schema",
|
|
"generated_at",
|
|
"release",
|
|
"restore",
|
|
"source",
|
|
"toolchains",
|
|
"lockfiles",
|
|
"configuration",
|
|
"data_versions",
|
|
"checks",
|
|
"rejected_checks",
|
|
"components",
|
|
)
|
|
STATUSES = frozenset({"verified", "not_verified", "missing"})
|
|
COMPONENT_GROUP_ORDER = ("core", "demo", "ml", "monitoring", "missing")
|
|
SHA256_PATTERN = re.compile(r"sha256:[0-9a-f]{64}")
|
|
IMAGE_ID_PATTERN = SHA256_PATTERN
|
|
|
|
|
|
def structure_errors(manifest: dict[str, Any], root: Path = ROOT) -> list[str]:
|
|
if not isinstance(manifest, dict):
|
|
return ["manifest must be a JSON object"]
|
|
errors = [f"missing key {key}" for key in REQUIRED_KEYS if key not in manifest]
|
|
if manifest.get("schema") != MANIFEST_SCHEMA:
|
|
errors.append("unexpected schema")
|
|
release = manifest.get("release")
|
|
if not isinstance(release, dict):
|
|
errors.append("release must be an object")
|
|
release = {}
|
|
try:
|
|
validate_release_id(release.get("id"))
|
|
except (ReleaseError, TypeError):
|
|
errors.append("release ID is invalid")
|
|
if release.get("product_data_status") not in {"versioned", "partial", "unavailable"}:
|
|
errors.append("product data status is invalid")
|
|
if release.get("status") not in {"verified", "unverified"} or release.get("scope") != "core":
|
|
errors.append("release status or scope is invalid")
|
|
if release.get("required_checks") != list(CHECKS):
|
|
errors.append("required release checks are invalid")
|
|
tag = release.get("tag")
|
|
if not isinstance(tag, str) or not re.fullmatch(r"[0-9a-f]{12}(-dirty)?", tag):
|
|
errors.append("release source tag is invalid")
|
|
try:
|
|
expected_restore_command = manifest_restore_command(release.get("id"))
|
|
except (ReleaseError, TypeError):
|
|
expected_restore_command = None
|
|
|
|
components = manifest.get("components")
|
|
if not isinstance(components, list):
|
|
errors.append("components must be a list")
|
|
components = []
|
|
checks = manifest.get("checks")
|
|
if not isinstance(checks, dict):
|
|
errors.append("checks must be an object")
|
|
checks = {}
|
|
seen: set[str] = set()
|
|
core_components: list[dict[str, Any]] = []
|
|
for component in components:
|
|
if not isinstance(component, dict):
|
|
errors.append("component entry must be an object")
|
|
continue
|
|
name = component.get("name")
|
|
if not isinstance(name, str) or not re.fullmatch(r"[a-z0-9][a-z0-9_.-]*", name):
|
|
errors.append("component name is invalid")
|
|
elif name in seen:
|
|
errors.append(f"duplicate component {name}")
|
|
else:
|
|
seen.add(name)
|
|
if component.get("group") == "core":
|
|
core_components.append(component)
|
|
verification = component.get("verification")
|
|
if not isinstance(verification, dict):
|
|
errors.append(f"component {component.get('name')} verification must be an object")
|
|
verification = {}
|
|
status = verification.get("status")
|
|
if status not in STATUSES:
|
|
errors.append(f"component {component.get('name')} has status {status!r}")
|
|
verified_checks = verification.get("checks", [])
|
|
if not isinstance(verified_checks, list):
|
|
errors.append(f"component {component.get('name')} checks must be a list")
|
|
verified_checks = []
|
|
if status == "verified" and not verification.get("checks"):
|
|
errors.append(f"component {component.get('name')} is verified without a check")
|
|
if status == "verified" and any(
|
|
check not in checks for check in verified_checks
|
|
):
|
|
errors.append(f"component {component.get('name')} names an unrecorded check")
|
|
image = component.get("image")
|
|
if component.get("group") == "missing":
|
|
if image is not None:
|
|
errors.append(f"missing component {name} must not name an image")
|
|
continue
|
|
if not isinstance(image, dict):
|
|
errors.append(f"component {name} image must be an object")
|
|
continue
|
|
if image.get("present"):
|
|
image_id = image.get("image_id")
|
|
if not isinstance(image_id, str) or not IMAGE_ID_PATTERN.fullmatch(image_id):
|
|
errors.append(f"component {name} image ID is invalid")
|
|
restore_reference = image.get("restore_reference")
|
|
if restore_reference is not None and (not isinstance(restore_reference, str) or not restore_reference.strip()):
|
|
errors.append(f"component {name} restore reference is invalid")
|
|
if status == "verified" and isinstance(image_id, str):
|
|
for check in verified_checks:
|
|
evidence = checks.get(check)
|
|
ids = evidence.get("image_ids") if isinstance(evidence, dict) else None
|
|
if not isinstance(ids, dict) or ids.get(name) != image_id:
|
|
errors.append(f"verified component {name} does not match the recorded {check} image ID")
|
|
group = component.get("group")
|
|
if group in ("core", "demo") and component.get("kind") == "built":
|
|
if image.get("restore_reference") != image_id:
|
|
errors.append(f"built {group} component {name} is not pinned to its exact image ID")
|
|
try:
|
|
expected_retention = release_image_reference(name, release.get("id"))
|
|
except (ReleaseError, TypeError):
|
|
expected_retention = None
|
|
if image.get("retention_reference") != expected_retention:
|
|
errors.append(f"built {group} component {name} has an invalid retention reference")
|
|
elif group == "core":
|
|
if component.get("kind") == "pulled":
|
|
digest = image.get("repo_digest")
|
|
if not isinstance(digest, str) or not SHA256_PATTERN.fullmatch(digest):
|
|
errors.append(f"pulled core component {name} has no repository digest")
|
|
else:
|
|
try:
|
|
expected_reference = f"{normalize_repository(image.get('reference', ''))}@{digest}"
|
|
except (AttributeError, TypeError):
|
|
expected_reference = None
|
|
if image.get("restore_reference") != expected_reference:
|
|
errors.append(f"pulled core component {name} is not pinned to its repository digest")
|
|
if image.get("retention_reference") is not None:
|
|
errors.append(f"pulled core component {name} has an unexpected retention reference")
|
|
else:
|
|
errors.append(f"core component {name} has an unsupported image kind")
|
|
elif image.get("restore_reference") is not None or image.get("retention_reference") is not None:
|
|
errors.append(f"component {name} without an image must not have immutable image references")
|
|
if not any(item.get("group") == "missing" for item in components if isinstance(item, dict)):
|
|
errors.append("missing components are not listed")
|
|
|
|
restore = manifest.get("restore")
|
|
if not isinstance(restore, dict):
|
|
errors.append("restore must be an object")
|
|
restore = {}
|
|
if restore.get("scope") != "core" or restore.get("status") not in {"available", "blocked"}:
|
|
errors.append("restore scope or status is invalid")
|
|
if (
|
|
not isinstance(restore.get("command"), str)
|
|
or restore.get("command") != expected_restore_command
|
|
or not isinstance(restore.get("reasons"), list)
|
|
or not all(isinstance(reason, str) for reason in restore.get("reasons", []))
|
|
):
|
|
errors.append("restore command or reasons are malformed")
|
|
if restore.get("status") == "available":
|
|
if restore.get("reasons"):
|
|
errors.append("available restore has blocking reasons")
|
|
for component in core_components:
|
|
image = component.get("image") or {}
|
|
if not image.get("present") or not image.get("restore_reference"):
|
|
errors.append(f"available restore has no exact image for {component.get('name')}")
|
|
elif restore.get("status") == "blocked" and not restore.get("reasons"):
|
|
errors.append("blocked restore has no reason")
|
|
|
|
config = manifest.get("configuration")
|
|
compose_inventory: dict[str, Any] = {}
|
|
if not isinstance(config, dict) or not isinstance(config.get("compose_files"), dict):
|
|
errors.append("Compose file digests are malformed")
|
|
else:
|
|
compose_inventory = config["compose_files"]
|
|
# Manifests written before the demo stand was pinned list the core files only.
|
|
if set(compose_inventory) not in (set(CORE_COMPOSE_FILES), set(RELEASE_COMPOSE_FILES)):
|
|
errors.append("Compose file digest inventory is incomplete")
|
|
for name, digest in compose_inventory.items():
|
|
if digest is not None and (not isinstance(digest, str) or not SHA256_PATTERN.fullmatch(digest)):
|
|
errors.append(f"Compose file digest for {name} is invalid")
|
|
errors += demo_restore_errors(manifest, restore, components, compose_inventory)
|
|
|
|
data = manifest.get("data_versions")
|
|
if not isinstance(data, dict) or set(data) != set(DATA_COMPONENTS):
|
|
errors.append("bank, policy, and seed version entries are required")
|
|
else:
|
|
states: list[str] = []
|
|
artifact_count = 0
|
|
total_size = 0
|
|
for name in DATA_COMPONENTS:
|
|
entry = data[name]
|
|
if not isinstance(entry, dict):
|
|
errors.append(f"data entry {name} must be an object")
|
|
continue
|
|
state = entry.get("status")
|
|
states.append(state)
|
|
if state == "unavailable":
|
|
if (
|
|
set(entry) != {"status", "version", "artifacts", "reason"}
|
|
or entry.get("version") is not None
|
|
or entry.get("artifacts") != []
|
|
or not isinstance(entry.get("reason"), str)
|
|
or not entry["reason"].strip()
|
|
):
|
|
errors.append(f"unavailable data entry {name} is malformed")
|
|
continue
|
|
if state != "available":
|
|
errors.append(f"data entry {name} status is invalid")
|
|
continue
|
|
if set(entry) != {"status", "version", "source_kind", "artifacts"}:
|
|
errors.append(f"available data entry {name} has unexpected fields")
|
|
if entry.get("source_kind") not in {"snapshot", "bundled_source"}:
|
|
errors.append(f"data source kind for {name} is invalid")
|
|
version = entry.get("version")
|
|
if not isinstance(version, str) or not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._:+-]{0,127}", version):
|
|
errors.append(f"data version for {name} is invalid")
|
|
artifacts = entry.get("artifacts")
|
|
if not isinstance(artifacts, list) or not artifacts:
|
|
errors.append(f"available data entry {name} needs artifacts")
|
|
continue
|
|
for artifact in artifacts:
|
|
artifact_count += 1
|
|
if not isinstance(artifact, dict):
|
|
errors.append(f"data artifact in {name} is malformed")
|
|
continue
|
|
if set(artifact) != {"path", "sha256", "size_bytes"}:
|
|
errors.append(f"data artifact in {name} has unexpected fields")
|
|
artifact_path = artifact.get("path")
|
|
digest = artifact.get("sha256")
|
|
size = artifact.get("size_bytes")
|
|
if not isinstance(artifact_path, str) or not isinstance(digest, str) or not SHA256_PATTERN.fullmatch(digest):
|
|
errors.append(f"data artifact in {name} has an invalid path or hash")
|
|
if not isinstance(size, int) or isinstance(size, bool) or size < 0:
|
|
errors.append(f"data artifact in {name} has an invalid size")
|
|
else:
|
|
if size > DATA_ARTIFACT_SIZE_LIMIT:
|
|
errors.append(f"data artifact in {name} exceeds the per-file limit")
|
|
total_size += size
|
|
if isinstance(artifact_path, str):
|
|
try:
|
|
project_file(
|
|
artifact_path,
|
|
root,
|
|
maximum_size=DATA_ARTIFACT_SIZE_LIMIT,
|
|
label="Manifest data artifact",
|
|
)
|
|
except ReleaseError:
|
|
errors.append(f"data artifact in {name} has an unsafe or missing path")
|
|
if artifact_count > DATA_ARTIFACT_LIMIT or total_size > DATA_TOTAL_SIZE_LIMIT:
|
|
errors.append("data artifact inventory exceeds its limit")
|
|
expected_data_status = "versioned" if states and all(state == "available" for state in states) else (
|
|
"partial" if any(state == "available" for state in states) else "unavailable"
|
|
)
|
|
if release.get("product_data_status") != expected_data_status:
|
|
errors.append("product data status does not match the recorded versions")
|
|
return errors
|
|
|
|
|
|
def demo_restore_errors(
|
|
manifest: dict[str, Any], restore: dict[str, Any], components: list[Any], compose_inventory: dict[str, Any]
|
|
) -> list[str]:
|
|
"""Check the optional demo stand restore entry; older manifests have none."""
|
|
if "demo" not in restore:
|
|
return []
|
|
demo = restore["demo"]
|
|
if not isinstance(demo, dict) or set(demo) != {"status", "command", "reasons"}:
|
|
return ["demo restore entry is malformed"]
|
|
errors: list[str] = []
|
|
release_info = manifest.get("release") if isinstance(manifest.get("release"), dict) else {}
|
|
try:
|
|
expected_command = demo_restore_command(release_info.get("id"))
|
|
except (ReleaseError, TypeError):
|
|
expected_command = None
|
|
reasons = demo.get("reasons")
|
|
if (
|
|
demo.get("status") not in {"available", "blocked"}
|
|
or demo.get("command") != expected_command
|
|
or not isinstance(reasons, list)
|
|
or not all(isinstance(reason, str) for reason in reasons)
|
|
):
|
|
return ["demo restore status, command, or reasons are malformed"]
|
|
if demo["status"] == "blocked":
|
|
if not reasons:
|
|
errors.append("blocked demo restore has no reason")
|
|
return errors
|
|
if reasons:
|
|
errors.append("available demo restore has blocking reasons")
|
|
if restore.get("status") != "available":
|
|
errors.append("available demo restore needs an available core restore")
|
|
if any(not compose_inventory.get(name) for name in DEMO_COMPOSE_FILES):
|
|
errors.append("available demo restore has no demo stand Compose file digests")
|
|
demo_components = [item for item in components if isinstance(item, dict) and item.get("group") == "demo"]
|
|
if not demo_components:
|
|
errors.append("available demo restore has no demo component")
|
|
for component in demo_components:
|
|
image = component.get("image") if isinstance(component.get("image"), dict) else {}
|
|
if not image.get("present") or not image.get("restore_reference"):
|
|
errors.append(f"available demo restore has no exact image for {component.get('name')}")
|
|
return errors
|
|
|
|
|
|
def command_check(args: argparse.Namespace, docker: Docker | None = None, root: Path = ROOT) -> int:
|
|
path = manifest_file(args.manifest, root)
|
|
try:
|
|
load_manifest(path, root)
|
|
text = path.read_text(encoding="utf-8")
|
|
manifest = json.loads(text)
|
|
except (OSError, UnicodeError, ValueError) as error:
|
|
raise ReleaseError(f"No readable release manifest at {display(path, root)}.") from error
|
|
try:
|
|
validate_manifest_location(path, manifest, root)
|
|
except ReleaseError as error:
|
|
return_code_problem = str(error)
|
|
else:
|
|
return_code_problem = None
|
|
problems = structure_errors(manifest, root)
|
|
if return_code_problem:
|
|
problems.append(return_code_problem)
|
|
problems += forbidden_findings(text, sensitive_values(root))
|
|
problems += [item for item in forbidden_findings(manifest) if item.startswith("configuration key")]
|
|
if problems:
|
|
print(f"{display(path, root)} failed the check:")
|
|
for problem in sorted(set(problems)):
|
|
print(f" - {problem}")
|
|
return 1
|
|
print(f"{display(path, root)}: structure valid; no secrets, local paths, user or host names found.")
|
|
return 0
|
|
|
|
|
|
def check_compose_files(
|
|
manifest: dict[str, Any], root: Path = ROOT, names: tuple[str, ...] = CORE_COMPOSE_FILES
|
|
) -> None:
|
|
expected = (manifest.get("configuration") or {}).get("compose_files") or {}
|
|
for name in names:
|
|
want = expected.get(name)
|
|
actual = file_digest(root / name)
|
|
if not want or actual != want:
|
|
raise ReleaseError(f"Compose file {name} differs from the immutable release manifest.")
|
|
|
|
|
|
def restore_images(manifest: dict[str, Any], docker: Docker, root: Path = ROOT) -> dict[str, str]:
|
|
release_info = manifest["release"]
|
|
release_id = release_info["id"]
|
|
source_tag = release_info["tag"]
|
|
expected_services = {item.name for item in group_services(docker, next(g for g in GROUPS if g.name == "core"), source_tag, root)}
|
|
components = {item["name"]: item for item in manifest["components"] if item.get("group") == "core"}
|
|
if set(components) != expected_services:
|
|
raise ReleaseError("Core Compose services differ from the immutable release manifest.")
|
|
|
|
result: dict[str, str] = {}
|
|
to_tag: list[tuple[str, str, str]] = []
|
|
for name, component in sorted(components.items()):
|
|
image = component.get("image") or {}
|
|
image_id = image.get("image_id")
|
|
if not image.get("present") or not isinstance(image_id, str):
|
|
raise ReleaseError(f"Core image {name} is missing from the manifest.")
|
|
if component.get("kind") == "built":
|
|
expected_reference = image_id
|
|
retention_reference = release_image_reference(name, release_id)
|
|
if image.get("restore_reference") != expected_reference or image.get("retention_reference") != retention_reference:
|
|
raise ReleaseError(f"Built image reference for {name} is not the manifest's immutable release reference.")
|
|
local = docker.inspect_image(image_id)
|
|
if local is None or local.get("Id") != image_id:
|
|
raise ReleaseError(f"Exact local image {image_id} for {name} is missing; restore will not rebuild it.")
|
|
retained = docker.inspect_image(retention_reference)
|
|
if retained is not None and retained.get("Id") != image_id:
|
|
raise ReleaseError(f"Retained release reference for {name} points to a different image ID.")
|
|
if retained is None:
|
|
to_tag.append((image_id, retention_reference, name))
|
|
elif component.get("kind") == "pulled":
|
|
digest = image.get("repo_digest")
|
|
if not isinstance(digest, str) or not SHA256_PATTERN.fullmatch(digest):
|
|
raise ReleaseError(f"Pulled core image {name} has no recorded repository digest.")
|
|
expected_reference = f"{normalize_repository(image.get('reference', ''))}@{digest}"
|
|
if image.get("restore_reference") != expected_reference:
|
|
raise ReleaseError(f"Pulled image reference for {name} is not the recorded repository digest.")
|
|
exact = docker.inspect_image(expected_reference)
|
|
if exact is None or exact.get("Id") != image_id:
|
|
raise ReleaseError(f"Recorded digest for {name} is missing or resolves to a different image ID.")
|
|
actual_digest = repo_digest(exact, image.get("reference", ""))
|
|
if actual_digest != digest:
|
|
raise ReleaseError(f"Recorded digest for {name} does not match its local image metadata.")
|
|
else:
|
|
raise ReleaseError(f"Core component {name} has an unsupported image kind.")
|
|
result[name] = expected_reference
|
|
|
|
for image_id, reference, name in to_tag:
|
|
docker.tag_image(image_id, reference)
|
|
retained = docker.inspect_image(reference)
|
|
if retained is None or retained.get("Id") != image_id:
|
|
raise ReleaseError(f"Could not retain exact image {image_id} for {name}.")
|
|
result[name] = image_id
|
|
return result
|
|
|
|
|
|
def restore_demo_images(manifest: dict[str, Any], docker: Docker, root: Path = ROOT) -> dict[str, str]:
|
|
"""Return the exact image IDs of the demo services, retaining them like core images."""
|
|
release_id = manifest["release"]["id"]
|
|
demo_group = next(group for group in GROUPS if group.name == "demo")
|
|
expected_services = {item.name for item in group_services(docker, demo_group, manifest["release"]["tag"], root)}
|
|
components = {item["name"]: item for item in manifest["components"] if item.get("group") == "demo"}
|
|
if not components or set(components) != expected_services:
|
|
raise ReleaseError("Demo stand Compose services differ from the immutable release manifest.")
|
|
result: dict[str, str] = {}
|
|
for name, component in sorted(components.items()):
|
|
image = component.get("image") or {}
|
|
image_id = image.get("image_id")
|
|
retention_reference = release_image_reference(name, release_id)
|
|
if (
|
|
component.get("kind") != "built"
|
|
or not image.get("present")
|
|
or not isinstance(image_id, str)
|
|
or image.get("restore_reference") != image_id
|
|
or image.get("retention_reference") != retention_reference
|
|
):
|
|
raise ReleaseError(f"Demo image {name} is not pinned to its exact image ID in the manifest.")
|
|
local = docker.inspect_image(image_id)
|
|
if local is None or local.get("Id") != image_id:
|
|
raise ReleaseError(f"Exact local image {image_id} for {name} is missing; restore will not rebuild it.")
|
|
retained = docker.inspect_image(retention_reference)
|
|
if retained is None:
|
|
docker.tag_image(image_id, retention_reference)
|
|
retained = docker.inspect_image(retention_reference)
|
|
if retained is None or retained.get("Id") != image_id:
|
|
raise ReleaseError(f"Retained release reference for {name} points to a different image ID.")
|
|
result[name] = image_id
|
|
return result
|
|
|
|
|
|
def write_compose_override(directory: Path, images: dict[str, str]) -> Path:
|
|
if any(not re.fullmatch(r"[a-z0-9][a-z0-9_.-]*", name) for name in images):
|
|
raise ReleaseError("Compose override contains an invalid service name.")
|
|
lines = ["services:"] if images else ["services: {}"]
|
|
for name, reference in sorted(images.items()):
|
|
if not isinstance(reference, str) or any(character.isspace() for character in reference):
|
|
raise ReleaseError(f"Compose override contains an invalid image reference for {name}.")
|
|
lines.extend((f" {name}:", f" image: {json.dumps(reference)}", " pull_policy: never"))
|
|
path = directory / "release-restore.yml"
|
|
try:
|
|
file_descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
|
with os.fdopen(file_descriptor, "w", encoding="utf-8") as stream:
|
|
stream.write("\n".join(lines) + "\n")
|
|
except OSError as error:
|
|
raise ReleaseError("Could not create the temporary pinned Compose override.") from error
|
|
return path
|
|
|
|
|
|
def command_restore(args: argparse.Namespace, docker: Docker | None = None, root: Path = ROOT) -> int:
|
|
docker = docker or Docker()
|
|
project = args.project
|
|
if not isinstance(project, str) or not re.fullmatch(r"[a-z0-9][a-z0-9_-]{0,62}", project):
|
|
raise ReleaseError("Compose project name is invalid.")
|
|
env_file = Path(args.env_file)
|
|
if not env_file.is_absolute():
|
|
env_file = root / env_file
|
|
if not env_file.is_file():
|
|
raise ReleaseError("The explicit Compose environment file is missing.")
|
|
path = manifest_file(args.manifest, root)
|
|
manifest = load_manifest(path, root)
|
|
validate_manifest_location(path, manifest, root)
|
|
problems = structure_errors(manifest, root)
|
|
problems += forbidden_findings(manifest)
|
|
if problems:
|
|
raise ReleaseError(f"Release manifest at {display(path, root)} is invalid: " + "; ".join(sorted(set(problems))))
|
|
|
|
source_tag = manifest["release"]["tag"]
|
|
if args.action == "down":
|
|
images: dict[str, str] = {}
|
|
else:
|
|
if manifest["restore"]["status"] != "available":
|
|
reasons = "; ".join(manifest["restore"]["reasons"])
|
|
raise ReleaseError("Manifest restore is blocked" + (f": {reasons}" if reasons else "."))
|
|
check_compose_files(manifest, root)
|
|
verify_data_artifacts(manifest["data_versions"], root)
|
|
images = restore_images(manifest, docker, root)
|
|
|
|
with tempfile.TemporaryDirectory(prefix="lincodex-release-") as temporary:
|
|
override = write_compose_override(Path(temporary), images)
|
|
if args.action == "up":
|
|
configuration = docker.compose_restore_config(project, env_file, source_tag, override, root)
|
|
actual = configuration.get("services") or {}
|
|
for name, reference in images.items():
|
|
if (actual.get(name) or {}).get("image") != reference:
|
|
raise ReleaseError(f"Compose did not retain the pinned image reference for {name}.")
|
|
docker.compose_restore(args.action, project, env_file, source_tag, override, root)
|
|
|
|
if args.action == "up":
|
|
running = running_services(docker.project_containers(project))
|
|
matches, lines = compare_running(manifest, running)
|
|
if not matches:
|
|
raise ReleaseError("Compose started, but running images do not match the manifest: " + "; ".join(lines))
|
|
print(f"Restored {display(path, root)} in project {project} using recorded image IDs.")
|
|
if manifest["release"]["product_data_status"] != "versioned":
|
|
print(f"Product data status: {manifest['release']['product_data_status']}; this is not a full MVP readiness result.")
|
|
else:
|
|
print(f"Stopped release project {project}.")
|
|
return 0
|
|
|
|
|
|
def command_demo_override(args: argparse.Namespace, docker: Docker | None = None, root: Path = ROOT) -> int:
|
|
"""Preflight a manifest for the isolated demo stand and write its pinned override.
|
|
|
|
deploy/scripts/demo.sh combines the override with docker-compose.yml and
|
|
docker-compose.demo.yml, so the demo stand starts and seeds from the exact
|
|
image IDs and digests of the delivery instead of building or resolving tags.
|
|
"""
|
|
docker = docker or Docker()
|
|
directory = Path(args.output_dir)
|
|
if not directory.is_absolute() or directory.is_symlink() or not directory.is_dir():
|
|
raise ReleaseError("The override directory must be an existing absolute directory.")
|
|
path = manifest_file(args.manifest, root)
|
|
manifest = load_manifest(path, root)
|
|
validate_manifest_location(path, manifest, root)
|
|
problems = structure_errors(manifest, root) + forbidden_findings(manifest)
|
|
if problems:
|
|
raise ReleaseError(f"Release manifest at {display(path, root)} is invalid: " + "; ".join(sorted(set(problems))))
|
|
demo = manifest["restore"].get("demo")
|
|
if not isinstance(demo, dict):
|
|
raise ReleaseError("The manifest has no demo stand restore entry; publish a new manifest for the demo stand.")
|
|
if manifest["restore"]["status"] != "available" or demo["status"] != "available":
|
|
reasons = "; ".join(manifest["restore"]["reasons"] + demo["reasons"])
|
|
raise ReleaseError("Demo stand restore is blocked" + (f": {reasons}" if reasons else "."))
|
|
check_compose_files(manifest, root, RELEASE_COMPOSE_FILES)
|
|
verify_data_artifacts(manifest["data_versions"], root)
|
|
images = restore_images(manifest, docker, root)
|
|
images.update(restore_demo_images(manifest, docker, root))
|
|
override = write_compose_override(directory, images)
|
|
print(f"Pinned the demo stand to {display(path, root)} (release {manifest['release']['id']}) in {override.name}.")
|
|
return 0
|
|
|
|
|
|
def retained_image_references(root: Path = ROOT) -> set[str]:
|
|
release_root = root / RELEASE_DIR_NAME
|
|
if release_root.is_symlink():
|
|
raise ReleaseError("Release artifact directory cannot be a symlink.")
|
|
retained: set[str] = set()
|
|
if not release_root.is_dir():
|
|
return retained
|
|
for path in sorted(release_root.glob("*/manifest.json")):
|
|
if path.is_symlink():
|
|
raise ReleaseError(f"Cannot clean images while an immutable manifest is a symlink: {display(path, root)}.")
|
|
manifest = load_manifest(path, root)
|
|
components = manifest.get("components")
|
|
if not isinstance(components, list):
|
|
raise ReleaseError(f"Cannot clean images; {display(path, root)} has no component inventory.")
|
|
for component in components:
|
|
if not isinstance(component, dict):
|
|
raise ReleaseError(f"Cannot clean images; {display(path, root)} has a malformed component.")
|
|
image = component.get("image")
|
|
if not isinstance(image, dict):
|
|
continue
|
|
for reference in (image.get("reference"), image.get("retention_reference")):
|
|
if isinstance(reference, str) and reference.startswith(f"{RELEASE_REGISTRY}/"):
|
|
retained.add(reference)
|
|
return retained
|
|
|
|
|
|
def command_clean_images(args: argparse.Namespace, docker: Docker | None = None, root: Path = ROOT) -> int:
|
|
"""Remove local release references that no immutable manifest retains."""
|
|
docker = docker or Docker()
|
|
listing = run([docker.binary, "image", "ls", "--format", "{{.Repository}}:{{.Tag}}"], env=docker_env())
|
|
retained = retained_image_references(root)
|
|
references = sorted(
|
|
{
|
|
line
|
|
for line in listing.decode().splitlines()
|
|
if line.startswith(f"{RELEASE_REGISTRY}/") and line not in retained
|
|
}
|
|
)
|
|
if not references:
|
|
print("No unretained release images to remove.")
|
|
return 0
|
|
run([docker.binary, "image", "rm", *references], env=docker_env())
|
|
for reference in references:
|
|
print(f"Removed {reference}")
|
|
return 0
|
|
|
|
|
|
def command_tag(args: argparse.Namespace, docker: Docker | None = None, root: Path = ROOT) -> int:
|
|
print(read_source(root).tag)
|
|
return 0
|
|
|
|
|
|
def parser() -> argparse.ArgumentParser:
|
|
result = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
commands = result.add_subparsers(dest="command", required=True)
|
|
commands.add_parser("tag").set_defaults(handler=command_tag)
|
|
commands.add_parser("clean-images").set_defaults(handler=command_clean_images)
|
|
build = commands.add_parser("build")
|
|
build.add_argument("--pull", choices=("missing", "always"), default="missing")
|
|
build.set_defaults(handler=command_build)
|
|
require = commands.add_parser("require-images")
|
|
require.add_argument("--group", choices=("core",), default="core")
|
|
require.add_argument("--tag")
|
|
require.set_defaults(handler=command_require_images)
|
|
record = commands.add_parser("record-evidence")
|
|
record.add_argument("--check", choices=CHECKS, required=True)
|
|
record.add_argument("--project", required=True)
|
|
record.add_argument("--tag")
|
|
record.add_argument("--tool-image", action="append", help="name=reference of a test tool image")
|
|
record.set_defaults(handler=command_record_evidence)
|
|
manifest = commands.add_parser("manifest")
|
|
manifest.add_argument("--release-id")
|
|
manifest.add_argument("--data-manifest")
|
|
manifest.set_defaults(handler=command_manifest)
|
|
restore = commands.add_parser("restore")
|
|
restore.add_argument("--action", choices=("up", "down"), required=True)
|
|
restore.add_argument("--project", required=True)
|
|
restore.add_argument("--env-file", required=True)
|
|
restore.add_argument("--manifest")
|
|
restore.set_defaults(handler=command_restore)
|
|
verify = commands.add_parser("verify")
|
|
verify.add_argument("--project", required=True)
|
|
verify.add_argument("--manifest")
|
|
verify.set_defaults(handler=command_verify)
|
|
check = commands.add_parser("check")
|
|
check.add_argument("--manifest")
|
|
check.set_defaults(handler=command_check)
|
|
demo_override = commands.add_parser("demo-override")
|
|
demo_override.add_argument("--manifest", required=True)
|
|
demo_override.add_argument("--output-dir", required=True)
|
|
demo_override.set_defaults(handler=command_demo_override)
|
|
return result
|
|
|
|
|
|
def main(argv: list[str] | None = None) -> int:
|
|
args = parser().parse_args(argv)
|
|
handler: Callable[[argparse.Namespace], int] = args.handler
|
|
try:
|
|
return handler(args)
|
|
except ReleaseError as error:
|
|
print(f"release: {error}", file=sys.stderr)
|
|
return 2
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|