feat(deploy): pin the demo seed in release manifests and restore the demo stand from them
This commit is contained in:
1 parent
e1df4ff77c
commit
b768f7e53f
14 files changed
+789
-147
No files matched your search
@@ -12,6 +12,8 @@ Subcommands (deploy/Makefile is the supported interface):
|
||||
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
|
||||
@@ -59,6 +61,9 @@ 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}")
|
||||
@@ -70,6 +75,20 @@ 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 "
|
||||
@@ -91,10 +110,23 @@ class Group:
|
||||
# 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",
|
||||
@@ -374,11 +406,48 @@ def default_data_versions(root: Path = ROOT) -> dict[str, Any]:
|
||||
}
|
||||
else:
|
||||
result["policy"]["reason"] = "No versioned demo policy source is present."
|
||||
result["bank"]["reason"] = "No accepted assessment bank release snapshot is present."
|
||||
result["seed"]["reason"] = "No versioned demo seed release snapshot 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)
|
||||
@@ -641,6 +710,11 @@ def manifest_restore_command(release_id: str) -> str:
|
||||
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()
|
||||
@@ -751,23 +825,37 @@ def dockerfile_bases(text: str, source: str = "Dockerfile") -> list[BaseImage]:
|
||||
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 the build image agree."""
|
||||
"""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)
|
||||
dockerfile = (root / "backend/Dockerfile").read_text(encoding="utf-8")
|
||||
bases = {base.arg: base.default for base in dockerfile_bases(dockerfile, "backend/Dockerfile")}
|
||||
image = bases.get("GO_IMAGE", "")
|
||||
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)
|
||||
build_stage = dockerfile.split("FROM ${GO_IMAGE}", 1)[-1].split("\nFROM ", 1)[0]
|
||||
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": bool(re.search(r"^ENV\s+GOTOOLCHAIN=local\s*$", build_stage, re.MULTILINE)),
|
||||
"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)
|
||||
@@ -775,6 +863,7 @@ def go_policy(root: Path = ROOT) -> dict[str, Any]:
|
||||
and image_version.group(1) == version
|
||||
and policy["toolchain_directive"] in (None, f"go{version}")
|
||||
and policy["gotoolchain_local"]
|
||||
and seed_matches
|
||||
)
|
||||
return policy
|
||||
|
||||
@@ -835,6 +924,19 @@ def docker_env(extra: dict[str, str] | None = None) -> dict[str, str]:
|
||||
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."""
|
||||
|
||||
@@ -850,20 +952,16 @@ class Docker:
|
||||
data = json.loads(result.stdout)
|
||||
return data[0] if data else None
|
||||
|
||||
def compose_config(self, files: list[str], tag: str, root: Path = ROOT) -> dict[str, Any]:
|
||||
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"]
|
||||
env = docker_env(
|
||||
{
|
||||
"APP_PROJECT": RENDER_PROJECT,
|
||||
"APP_NETWORK": f"{RENDER_PROJECT}_default",
|
||||
"LINCODEX_RELEASE_TAG": tag,
|
||||
"IDENTITY_KEY_SECRET": RENDER_ONLY_IDENTITY_KEY,
|
||||
}
|
||||
)
|
||||
return json.loads(run(args, cwd=root, env=env))
|
||||
return json.loads(run(args, cwd=root, env=render_env(tag)))
|
||||
|
||||
def project_containers(self, project: str) -> list[dict[str, Any]]:
|
||||
ids = run(
|
||||
@@ -904,24 +1002,26 @@ class Docker:
|
||||
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) -> None:
|
||||
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)
|
||||
env = docker_env(
|
||||
{
|
||||
"APP_PROJECT": RENDER_PROJECT,
|
||||
"APP_NETWORK": f"{RENDER_PROJECT}_default",
|
||||
"LINCODEX_RELEASE_TAG": tag,
|
||||
"IDENTITY_KEY_SECRET": RENDER_ONLY_IDENTITY_KEY,
|
||||
}
|
||||
)
|
||||
print(f"Building {service} for release {tag}", flush=True)
|
||||
if subprocess.run(args, cwd=root, env=env, check=False).returncode != 0:
|
||||
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:
|
||||
@@ -1057,14 +1157,26 @@ class Service:
|
||||
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.compose_file] + ([group.release_overlay] if group.release_overlay else [])
|
||||
config = docker.compose_config(files, tag, root)
|
||||
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()):
|
||||
if spec.get("profiles"):
|
||||
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")
|
||||
@@ -1074,10 +1186,22 @@ def group_services(docker: Docker, group: Group, tag: str, root: Path = ROOT) ->
|
||||
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)
|
||||
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))
|
||||
services.append(
|
||||
Service(group.name, name, reference, compose_file=group.compose_file, render_files=tuple(files), profile=group.profile)
|
||||
)
|
||||
return services
|
||||
|
||||
|
||||
@@ -1105,8 +1229,8 @@ def command_build(args: argparse.Namespace, docker: Docker | None = None, 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 default, "
|
||||
"and ENV GOTOOLCHAIN=local in backend/Dockerfile must agree."
|
||||
"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,
|
||||
@@ -1137,8 +1261,8 @@ def command_build(args: argparse.Namespace, docker: Docker | None = None, root:
|
||||
bases.append(
|
||||
{"arg": base.arg, "reference": base.default, "digest": digest, "versions": image_versions(info)}
|
||||
)
|
||||
files = [service.compose_file] + ([service.overlay] if service.overlay else [])
|
||||
docker.compose_build(files, source.tag, service.name, build_args, root)
|
||||
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.")
|
||||
@@ -1358,6 +1482,18 @@ class Inputs:
|
||||
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:
|
||||
@@ -1374,13 +1510,8 @@ def collect_inputs(docker: Docker, root: Path = ROOT) -> Inputs:
|
||||
build_problem = build_record_problem(build) if build is not None else None
|
||||
if build_problem:
|
||||
build = None
|
||||
go_binary = None
|
||||
backend = images.get(release_reference("backend", source.tag))
|
||||
if backend:
|
||||
entrypoint = (backend.get("Config") or {}).get("Entrypoint") or []
|
||||
if entrypoint:
|
||||
content = docker.read_file(backend["Id"], entrypoint[0])
|
||||
go_binary = go_build_version(content) if content else 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*"([^"]+)"')
|
||||
@@ -1393,7 +1524,7 @@ def collect_inputs(docker: Docker, root: Path = ROOT) -> Inputs:
|
||||
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
|
||||
source, services, images, build, evidence, go_binary, go_policy(root), files, rejected, build_problem, seed_go_binary
|
||||
)
|
||||
|
||||
|
||||
@@ -1417,7 +1548,7 @@ def build_manifest(
|
||||
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 CORE_COMPOSE_FILES
|
||||
name: file_digest(root / name) for name in RELEASE_COMPOSE_FILES
|
||||
}
|
||||
source = inputs.source
|
||||
build = inputs.build_record
|
||||
@@ -1428,11 +1559,17 @@ def build_manifest(
|
||||
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,
|
||||
@@ -1485,6 +1622,10 @@ def build_manifest(
|
||||
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(
|
||||
{
|
||||
@@ -1495,7 +1636,7 @@ def build_manifest(
|
||||
"verification": {"status": "missing", "reason": reason, "checks": []},
|
||||
}
|
||||
)
|
||||
components.sort(key=lambda item: (["core", "ml", "monitoring", "missing"].index(item["group"]), item["name"]))
|
||||
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")
|
||||
@@ -1505,6 +1646,13 @@ def build_manifest(
|
||||
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"))
|
||||
@@ -1529,7 +1677,11 @@ def build_manifest(
|
||||
|
||||
for name, digest in sorted(compose_files.items()):
|
||||
if digest is None:
|
||||
restore_reasons.append(f"Compose file {name} is missing.")
|
||||
(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"
|
||||
@@ -1567,6 +1719,11 @@ def build_manifest(
|
||||
"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,
|
||||
@@ -1607,33 +1764,46 @@ def comparable(document: dict[str, Any] | None) -> dict[str, Any] | None:
|
||||
return {key: value for key, value in document.items() if key != "generated_at"}
|
||||
|
||||
|
||||
def add_restore_problem(manifest: dict[str, Any], problem: str) -> None:
|
||||
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"]
|
||||
restore["status"] = "blocked"
|
||||
restore["reasons"] = sorted(set(restore["reasons"] + [problem]))
|
||||
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 image IDs and confirm pulled digests before publication."""
|
||||
"""Retain built core and demo image IDs and confirm pulled digests before publication."""
|
||||
for component in manifest["components"]:
|
||||
if component.get("group") != "core":
|
||||
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"Core component {component.get('name')} has no immutable local image 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.")
|
||||
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.")
|
||||
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)
|
||||
@@ -1642,7 +1812,9 @@ def prepare_manifest_images(manifest: dict[str, Any], docker: Docker) -> None:
|
||||
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.")
|
||||
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"
|
||||
|
||||
@@ -1714,7 +1886,7 @@ def command_manifest(args: argparse.Namespace, docker: Docker | None = None, roo
|
||||
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 CORE_COMPOSE_FILES}
|
||||
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"
|
||||
@@ -1743,6 +1915,10 @@ def command_manifest(args: argparse.Namespace, docker: Docker | None = None, roo
|
||||
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"]
|
||||
@@ -1840,6 +2016,7 @@ REQUIRED_KEYS = (
|
||||
"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
|
||||
|
||||
@@ -1933,17 +2110,18 @@ def structure_errors(manifest: dict[str, Any], root: Path = ROOT) -> list[str]:
|
||||
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")
|
||||
if component.get("group") == "core":
|
||||
if component.get("kind") == "built":
|
||||
if image.get("restore_reference") != image_id:
|
||||
errors.append(f"built core 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 core component {name} has an invalid retention reference")
|
||||
elif component.get("kind") == "pulled":
|
||||
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")
|
||||
@@ -1987,15 +2165,18 @@ def structure_errors(manifest: dict[str, Any], root: Path = ROOT) -> list[str]:
|
||||
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:
|
||||
files = config["compose_files"]
|
||||
if set(files) != set(CORE_COMPOSE_FILES):
|
||||
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 files.items():
|
||||
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):
|
||||
@@ -2073,6 +2254,49 @@ def structure_errors(manifest: dict[str, Any], root: Path = ROOT) -> list[str]:
|
||||
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:
|
||||
@@ -2101,9 +2325,11 @@ def command_check(args: argparse.Namespace, docker: Docker | None = None, root:
|
||||
return 0
|
||||
|
||||
|
||||
def check_compose_files(manifest: dict[str, Any], root: Path = ROOT) -> None:
|
||||
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 CORE_COMPOSE_FILES:
|
||||
for name in names:
|
||||
want = expected.get(name)
|
||||
actual = file_digest(root / name)
|
||||
if not want or actual != want:
|
||||
@@ -2165,6 +2391,40 @@ def restore_images(manifest: dict[str, Any], docker: Docker, root: Path = ROOT)
|
||||
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.")
|
||||
@@ -2235,6 +2495,38 @@ def command_restore(args: argparse.Namespace, docker: Docker | None = None, root
|
||||
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():
|
||||
@@ -2322,6 +2614,10 @@ def parser() -> argparse.ArgumentParser:
|
||||
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
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user