feat(deploy): add the recurring Device Core release domain and durable queue policy

This commit is contained in:
Codex
2026-09-29 18:41:21 +03:00
parent d87a0c48b4
commit d161d7fb91
5 changed files with 941 additions and 1 deletions
+307 -1
View File
@@ -2960,6 +2960,13 @@ GITEA_SALVAGE_UNSUPPORTED_SCHEMA_TABLES = tuple(
)
COMPONENTS = {
"device-core-release": {
"payload_root": DEVICE_PLANE_ROOT,
"compose_root": DEVICE_PLANE_ROOT,
"compose_project": "nodedc-device-plane",
"compose_no_deps": True,
"services": ("device-control-core", "device-manager"),
},
"mission-core-map-access": {
"payload_root": Path("/volume1/docker/nodedc-platform/mission-core-map-access"),
"bootstrap_root": True,
@@ -4956,6 +4963,8 @@ def denied_payload_path(component, rel):
def allowed_payload_path(component, rel):
validate_posix_path(rel)
if component == "device-core-release":
return device_release_payload_path(rel)
reason = denied_payload_path(component, rel)
if reason:
die(f"path rejected: {rel}: {reason}")
@@ -11570,6 +11579,8 @@ def load_artifact(artifact, work_dir):
die(f"files.txt entry missing in payload: {rel}")
validate_payload_tree(manifest["component"], payload_dir, entries)
if manifest["component"] == "device-core-release":
validate_device_release_payload(payload_dir, entries, manifest["id"])
if manifest["component"] == "gitea-actions-config":
validate_gitea_actions_payload(payload_dir, entries, manifest["id"])
if manifest["component"] == "gitea-ci":
@@ -22414,6 +22425,10 @@ def is_platform_provider_catalog_only(entries):
def component_services(component, entries=None):
if component == "device-core-release":
if tuple(entries or ()) != DEVICE_RELEASE_ENTRIES:
die("Device Core release service selection requires exact entries")
return DEVICE_RELEASE_SERVICES
if is_device_plane_control_core_release_slice(component, entries):
return ("device-control-core",)
@@ -22738,6 +22753,8 @@ def component_compose_files(
allow_prepared_engine_backend=False,
expected_node_intelligence_gateway_sha256=None,
):
if component == "device-core-release":
return component_compose_files("device-plane")
if component == "engine":
root = component_root(component)
files = [root / "docker-compose.yml"]
@@ -23017,6 +23034,12 @@ def component_build_args(component, entries=None):
def component_builds(component, entries=None):
if component == "device-core-release":
component_services(component, entries)
return (
(DEVICE_PLANE_ROOT, ("build", "--no-cache", "--network=host", "-f", "services/device-control-core/Dockerfile", "-t", "nodedc/device-control-core:local", ".")),
(DEVICE_PLANE_ROOT / "services/device-manager", ("build", "--no-cache", "-t", "nodedc/device-manager:local", ".")),
)
if is_platform_device_core_hub_trust_slice(component, entries):
return ()
@@ -32257,6 +32280,255 @@ def rollback_gitea_ci(root, backup_dir, entries, current_stamp, runtime_started)
# and are never archived in the data-only source partition.
# Recurring application releases: a separate domain from immutable historical
# Device Plane transitions. No Compose, database, secret or controller payload.
DEVICE_RELEASE_ENTRY = "deployment/device-core-release-v1.json"
DEVICE_RELEASE_ENTRIES = (
".dockerignore", "package.json", "package-lock.json",
"packages/device-protocol-contract", "packages/device-edge-channel-contract",
"packages/infrastructure-telemetry-contract", "services/device-control-core",
"services/device-manager", DEVICE_RELEASE_ENTRY,
)
DEVICE_RELEASE_SERVICES = ("device-control-core", "device-manager")
DEVICE_RELEASE_INVENTORY = (*DEVICE_PLANE_RUNTIME_SERVICES, "device-manager", "device-backhaul-target")
DEVICE_RELEASE_BASELINES = (
("device-edge-core-channel-upgrade-v4-20260812-023", "c10d5b6b7d55ab239f85b6c8130e34ce9f84985e3b46e6e5534733156c7982fc"),
("device-control-core-release-v4-20260823-047", "4aecceeb8d400fdd3dbec8fc86b151691f389d165e72677f396f8994823b6b5c"),
("device-manager-release-v13-20260823-051", "3d4b5c01330a73ae9ba82475d0029a5bb54763261ff105e8d04626e597fdf84c"),
)
DEVICE_RELEASE_STEPS = ["design-install", "design-core", "design-react", "device-install",
"unit-tests", "ci-contract", "build", "artifact-contracts"]
def device_release_payload_path(rel):
# Reuse the established deny rules, then narrow them to the two app trees.
reason = denied_payload_path("device-plane", rel)
if any(part.lower() in {"runtime", "runtime-data", "secrets", "credentials", "uploads", "logs", "data", "node_modules", ".git", "__pycache__"} for part in PurePosixPath(rel).parts):
reason = "runtime or secret subtree"
if reason:
die("Device Core release rejected path: " + rel + ": " + reason)
parents = {str(p) for entry in DEVICE_RELEASE_ENTRIES for p in PurePosixPath(entry).parents if str(p) != "."}
if rel in parents or rel in DEVICE_RELEASE_ENTRIES or any(
rel.startswith(entry + "/") for entry in DEVICE_RELEASE_ENTRIES[3:8]
):
return True
die("Device Core release path is outside the application scope: " + rel)
def validate_device_release_payload(payload, entries, patch_id):
if tuple(entries) != DEVICE_RELEASE_ENTRIES:
die("Device Core release requires the exact application entry set")
d = read_strict_json(payload / DEVICE_RELEASE_ENTRY, "Device Core release", max_bytes=256 * 1024)
if (set(d) != {"schemaVersion", "releaseId", "repository", "repositoryId", "branch",
"sourceCommit", "runId", "runNumber", "qualification", "filesSha256", "packagedManagerDistSha256"}
or d.get("schemaVersion") != "nodedc.device-core.release.v1"
or d.get("repository") != "SILVER/NODEDC_DEVICE_CORE" or type(d.get("repositoryId")) is not int
or d["repositoryId"] != 38 or d.get("branch") != "main"
or not isinstance(d.get("sourceCommit"), str) or not re.fullmatch(r"[a-f0-9]{40}", d["sourceCommit"])
or any(type(d.get(k)) is not int or not 0 < d[k] < 2**53 for k in ("runId", "runNumber"))
or d.get("releaseId") != patch_id
or patch_id != "device-core-release-v1-r" + str(d["runId"]) + "-" + d["sourceCommit"]):
die("Device Core release identity mismatch")
actual = collect_exact_files(payload, DEVICE_RELEASE_ENTRIES[:-1], "Device Core release")
if not actual or d.get("filesSha256") != actual:
die("Device Core release file manifest mismatch")
q = d.get("qualification")
if (not isinstance(q, dict) or q.get("schema") != "nodedc.device-core.qualification.v1"
or q.get("status") != "qualified" or q.get("deployed") is not False
or q.get("sourceCommit") != d["sourceCommit"] or q.get("steps") != DEVICE_RELEASE_STEPS
or q.get("packageLockSha256") != actual["package-lock.json"]
or not isinstance(q.get("sources"), dict)):
die("Device Core release qualification mismatch")
# Dist is produced by CI; an incomplete or substituted UI must fail here.
dist = payload / "services/device-manager/dist"
digest = hashlib.sha256()
count = 0
for path in sorted(dist.rglob("*"), key=lambda p: p.relative_to(dist).as_posix()):
if path.is_file():
name = path.relative_to(dist).as_posix().encode()
data = path.read_bytes()
digest.update(len(name).to_bytes(8, "big") + name)
digest.update(len(data).to_bytes(8, "big") + data)
count += 1
if not count or d.get("packagedManagerDistSha256") != digest.hexdigest():
die("Device Core qualified UI digest mismatch")
return d
def device_release_applied_archive(row):
name = row.get("artifact")
if (not isinstance(name, str) or Path(name).name != name or not name.endswith(".tgz")
or row.get("status") != "ok" or not re.fullmatch(r"[a-f0-9]{64}", str(row.get("sha256")))):
die("Device Core predecessor receipt is malformed")
archive = APPLIED_DIR / name
if archive.is_symlink() or not archive.is_file() or sha256_file(archive) != row["sha256"]:
die("Device Core predecessor archive mismatch")
return archive
def device_release_predecessor(candidate):
applied = load_state(STATE_FILE)
for row in load_state(FAILED_STATE_FILE):
if row.get("component") == "device-core-release" and row.get("started_apply") and not str(row.get("rollback_status", "")).startswith("ok:"):
die("Device Core release requires reconciliation of a failed rollback")
normal = [row for row in applied if row.get("component") == "device-core-release"]
installed = DEVICE_PLANE_ROOT / DEVICE_RELEASE_ENTRY
expected = {}
predecessor = None
if normal:
row = normal[-1]
with tempfile.TemporaryDirectory(prefix="device-release-baseline-", dir=TMP_DIR) as tmp:
manifest, entries, payload = load_artifact(device_release_applied_archive(row), Path(tmp))
if manifest["component"] != "device-core-release" or manifest["id"] != row["id"]:
die("Device Core predecessor identity mismatch")
predecessor = validate_device_release_payload(payload, entries, row["id"])
expected = collect_exact_files(payload, entries, "Device Core predecessor")
if candidate["runNumber"] <= predecessor["runNumber"] or candidate["sourceCommit"] == predecessor["sourceCommit"]:
die("Device Core release is stale or already deployed")
else:
if installed.exists() or installed.is_symlink():
die("Device Core release descriptor has no canonical applied receipt")
# The first normal release is anchored in the three exact live releases,
# independently of the report or file hashes supplied by CI.
for identity, digest in DEVICE_RELEASE_BASELINES:
rows = [r for r in applied if r.get("id") == identity and r.get("sha256") == digest and r.get("component") == "device-plane"]
if len(rows) != 1:
die("Device Core initial predecessor journal mismatch: " + identity)
with tempfile.TemporaryDirectory(prefix="device-release-initial-", dir=TMP_DIR) as tmp:
safe_extract(device_release_applied_archive(rows[0]), Path(tmp))
payload = Path(tmp) / "payload"
# Historical descriptors/Compose stay outside the write set.
selected = parse_files_list(Path(tmp) / "files.txt")
files = collect_exact_files(payload, selected, "Device Core initial predecessor")
# Reconstruct the exact published sequence. A directory entry
# replaces that whole subtree, including files removed later.
expected = {rel: value for rel, value in expected.items() if not any(
rel == entry or rel.startswith(entry + "/") for entry in selected
)}
expected.update(files)
for rel, digest in expected.items():
path = DEVICE_PLANE_ROOT / rel
if path.is_symlink() or not path.is_file() or sha256_file(path) != digest:
die("Device Core initial predecessor source drift: " + rel)
expected = {rel: value for rel, value in expected.items() if any(
rel == entry or rel.startswith(entry + "/") for entry in DEVICE_RELEASE_ENTRIES[:-1]
)}
compare_entries = DEVICE_RELEASE_ENTRIES if normal else DEVICE_RELEASE_ENTRIES[:-1]
if collect_exact_files(DEVICE_PLANE_ROOT, compare_entries, "Device Core installed source") != expected:
die("Device Core installed application tree differs from its canonical predecessor")
return predecessor
def device_release_runtime_snapshot():
inventory = device_plane_runtime_inventory(DEVICE_RELEASE_INVENTORY)
if set(device_plane_inventory_service_names(inventory)) != set(DEVICE_RELEASE_INVENTORY):
die("Device Core release requires all existing services")
result = {}
for row in inventory["services"]:
if not row["running"] or row["health"] not in (None, "healthy"):
die("Device Core predecessor service is not healthy: " + row["service"])
info = inspect_device_plane_container(row["containerId"])
host = json.loads(json.dumps(info.get("HostConfig") or {}))
if isinstance(host.get("Ulimits"), list):
host["Ulimits"].sort(key=lambda x: json.dumps(x, sort_keys=True))
config = info.get("Config") or {}
fields = {"HostConfig": host,
"Config": {k: config.get(k) for k in ("Env", "User", "Cmd", "Entrypoint", "WorkingDir", "ExposedPorts")},
"Mounts": sorted(info.get("Mounts") or [], key=lambda x: json.dumps(x, sort_keys=True)),
"networks": sorted((info.get("NetworkSettings") or {}).get("Networks") or {})}
if isinstance(fields["Config"]["Env"], list):
fields["Config"]["Env"].sort()
row["runtimeConfigSha256"] = hashlib.sha256(json.dumps(fields, sort_keys=True).encode()).hexdigest()
result[row["service"]] = row
return result
def device_release_other_compose_services():
# Compose services have a persistent owner. Ephemeral Actions job containers
# have no Compose project and can legitimately finish during deployment.
proc = subprocess.run([str(DOCKER), "ps", "-aq", "--no-trunc", "--filter", "label=com.docker.compose.project"], capture_output=True, text=True, check=True)
result = {}
for identity in proc.stdout.split():
if not re.fullmatch(r"[a-f0-9]{64}", identity):
die("Device Core preserved container identity mismatch")
info = inspect_container(identity)
labels = (info.get("Config") or {}).get("Labels") or {}
if labels.get("com.docker.compose.project") == "nodedc-device-plane":
continue
if str(labels.get("com.docker.compose.oneoff", "False")).lower() == "true":
continue
result[identity] = {"fingerprint": gitea_actions_fingerprint_v2(info),
"running": (info.get("State") or {}).get("Running"),
"startedAt": (info.get("State") or {}).get("StartedAt")}
return result
def preflight_device_release(payload, entries, patch_id):
d = validate_device_release_payload(payload, entries, patch_id)
predecessor = device_release_predecessor(d)
# Normal app releases cannot introduce schema or Docker recipe transitions.
# Those use separately reviewed migration/topology domains.
immutable = (".dockerignore", "services/device-control-core/Dockerfile", "services/device-manager/Dockerfile", "services/device-control-core/migrations")
if collect_exact_files(payload, immutable, "Device Core candidate foundation") != collect_exact_files(DEVICE_PLANE_ROOT, immutable, "Device Core installed foundation"):
die("Device Core release changes the immutable database/build foundation")
validate_device_manager_control_plane_runtime(require_edge_channel=True, core_network_mode="private-egress", require_persistent_data=True)
before = device_release_runtime_snapshot()
compose = {str(p): sha256_file(p) for p in component_compose_files("device-plane")}
return {"descriptor": d, "predecessor": predecessor["releaseId"] if predecessor else "manager-v13/core-v4/edge-v4",
"runtime": before, "compose": compose, "otherComposeServices": device_release_other_compose_services(),
"installedFiles": collect_exact_files(DEVICE_PLANE_ROOT, DEVICE_RELEASE_ENTRIES if predecessor else DEVICE_RELEASE_ENTRIES[:-1], "Device Core rollback baseline")}
def accept_device_release(before, *, rollback=False):
current = device_release_runtime_snapshot()
for service, old in before["runtime"].items():
new = current[service]
if service not in DEVICE_RELEASE_SERVICES:
if new != old:
die("Device Core release changed a preserved service: " + service)
continue
if new["runtimeConfigSha256"] != old["runtimeConfigSha256"]:
die("Device Core release runtime configuration drift: " + service)
if rollback:
expected_image = old["imageId"]
else:
image = docker_json(["image", "inspect", "nodedc/" + service + ":local"], "Device Core release image")
if not isinstance(image, list) or len(image) != 1:
die("Device Core release image inspection mismatch")
expected_image = image[0].get("Id")
if new["containerId"] == old["containerId"]:
die("Device Core release did not recreate the selected service: " + service)
if new["imageId"] != expected_image:
die("Device Core release selected image mismatch: " + service)
if device_release_other_compose_services() != before["otherComposeServices"]:
die("Device Core release changed an unrelated Compose service")
if {str(p): sha256_file(p) for p in component_compose_files("device-plane")} != before["compose"]:
die("Device Core release changed Compose topology")
validate_device_manager_control_plane_runtime(require_edge_channel=True, core_network_mode="private-egress", require_persistent_data=True)
if rollback:
entries = DEVICE_RELEASE_ENTRIES if DEVICE_RELEASE_ENTRY in before["installedFiles"] else DEVICE_RELEASE_ENTRIES[:-1]
if collect_exact_files(DEVICE_PLANE_ROOT, entries, "Device Core rollback source") != before["installedFiles"]:
die("Device Core rollback source mismatch")
if DEVICE_RELEASE_ENTRY not in before["installedFiles"] and (DEVICE_PLANE_ROOT / DEVICE_RELEASE_ENTRY).exists():
die("Device Core rollback left an orphan release descriptor")
else:
d = before["descriptor"]
validate_device_release_payload(DEVICE_PLANE_ROOT, DEVICE_RELEASE_ENTRIES, d["releaseId"])
print("device_release_accept=" + ("rollback" if rollback else before["descriptor"]["sourceCommit"]) + ";database-volumes-and-topology=preserved")
def rollback_device_release(root, backup_dir, entries, current_stamp, before, runtime_started):
restore_platform_overlay(root, backup_dir, entries, current_stamp)
# Builds may have replaced a tag even if Compose never started. Restore both
# exact old image IDs; rollback never depends on a registry or a new build.
for service in DEVICE_RELEASE_SERVICES:
subprocess.run([str(DOCKER), "image", "tag", before["runtime"][service]["imageId"], "nodedc/" + service + ":local"], check=True)
if runtime_started:
run_compose("device-core-release", DEVICE_RELEASE_SERVICES, entries)
run_healthchecks("device-core-release", entries, DEVICE_RELEASE_SERVICES)
accept_device_release(before, rollback=True)
def plan_artifact(artifact):
validate_artifact_location(artifact)
ensure_layout()
@@ -32309,6 +32581,11 @@ def plan_artifact(artifact):
gitea_salvage_preflight = None
with tempfile.TemporaryDirectory(prefix="plan-", dir=TMP_DIR) as tmp:
manifest, entries, payload_dir = load_artifact(artifact, Path(tmp))
if manifest["component"] == "device-core-release":
release_before = preflight_device_release(payload_dir, entries, manifest["id"])
print("device_release_source=" + release_before["descriptor"]["sourceCommit"])
print("device_release_predecessor=" + release_before["predecessor"])
print("device_release_scope=core,manager;database-volumes-topology-secrets=preserved;rollback=exact-image-ids")
if is_gitea_fresh_install_slice(manifest["component"], entries):
validate_gitea_compose_schema(payload_dir / GITEA_COMPOSE_REL)
if is_gitea_incident_salvage_slice(manifest["component"], entries):
@@ -36488,6 +36765,8 @@ def run_compose(component, services, entries=None):
or touches_engine_credential_provisioner(component, entries)
or (component == "engine" and ENGINE_CREDENTIAL_BACKEND_ACTIVATION_FILE.exists())):
cmd.extend(["--pull", "never"])
if component == "device-core-release":
cmd.extend(["--pull", "never", "--no-build"])
if COMPONENTS[component].get("compose_build"):
cmd.append("--build")
if component_compose_no_deps(component, entries):
@@ -38464,6 +38743,14 @@ process.stdout.write('engine-l2-closed-loop:0.7.0:cas+safe-profile+external-plan
def run_healthchecks(component, entries=None, services=None):
if component == "device-core-release":
if tuple(services or ()) != DEVICE_RELEASE_SERVICES or tuple(entries or ()) != DEVICE_RELEASE_ENTRIES:
die("Device Core release health scope mismatch")
for service in DEVICE_RELEASE_INVENTORY:
healthcheck_compose_service_with_grace("device-plane", service)
for check in component_healthchecks("device-plane", entries, services):
healthcheck_url(check)
return
if component == "gitea-actions-config":
if tuple(services or ()) != ("gitea",) or tuple(entries or ()) not in ((GITEA_ACTIONS_ENTRY,), (GITEA_ACTIONS_V2_ENTRY,)):
die("Gitea Actions service/entry set mismatch")
@@ -39576,6 +39863,7 @@ def apply_artifact(artifact):
engine_backend_initial_mode = None
runtime_started = False
gitea_ci_before = None
device_release_before = None
gitea_actions_before = None
current_stamp = stamp()
@@ -39625,6 +39913,8 @@ def apply_artifact(artifact):
gitea_ci_before = preflight_gitea_ci(entries)
if component == "gitea-actions-config":
gitea_actions_before = preflight_gitea_actions(entries)
if component == "device-core-release":
device_release_before = preflight_device_release(payload_dir, entries, patch_id)
artifact_only = component_artifact_only(component)
defer_bootstrap_root = is_gitea_bootstrap_slice(
component,
@@ -40150,6 +40440,10 @@ def apply_artifact(artifact):
include_nginx_html = component == "engine" and component_publish_dist(component, entries)
create_backup(root, backup_dir, entries, include_nginx_html)
if component == "device-core-release":
proof = backup_dir / "device-release-before.json"
proof.write_text(json.dumps(device_release_before, sort_keys=True) + "\n", encoding="utf-8")
proof.chmod(0o600)
if component == "gitea-ci":
(backup_dir / "ci-runtime-before.json").write_text(
json.dumps(gitea_ci_before, sort_keys=True) + "\n",
@@ -40237,6 +40531,10 @@ def apply_artifact(artifact):
# can be safely reconciled by recreating on that runtime.
engine_backend_recreated = True
run_compose(component, services, entries)
elif component == "device-core-release":
run_build(component, entries)
runtime_started = True
run_compose(component, services, entries)
elif component == "gitea-actions-config":
runtime_started = True
apply_gitea_actions(gitea_actions_before, backup_dir)
@@ -40276,6 +40574,8 @@ def apply_artifact(artifact):
):
die("Engine L2 closed-loop app generation was not recreated")
run_healthchecks(component, entries, services)
if component == "device-core-release":
accept_device_release(device_release_before)
if component == "gitea-ci":
if gitea_ci_inventory() != gitea_ci_before:
die("Gitea CI altered the preserved container inventory")
@@ -40350,7 +40650,13 @@ def apply_artifact(artifact):
and backup_dir is not None
and root is not None
):
if component == "gitea-actions-config":
if component == "device-core-release":
try:
rollback_device_release(root, backup_dir, entries, current_stamp, device_release_before, runtime_started)
rollback_status = "ok:device-core-release"
except Exception as rollback_exc:
rollback_status = "failed:" + type(rollback_exc).__name__
elif component == "gitea-actions-config":
try:
rollback_gitea_actions(root, backup_dir, entries, current_stamp,
gitea_actions_before, runtime_started)
@@ -0,0 +1,251 @@
"""Recurring release boundary, source provenance and exact rollback tests."""
import copy
from contextlib import ExitStack, redirect_stdout, redirect_stderr
import hashlib
import importlib.machinery
import importlib.util
import io
import json
from pathlib import Path
import shutil
import tarfile
import tempfile
import unittest
from unittest import mock
loader = importlib.machinery.SourceFileLoader('device_release_runner', str(Path(__file__).with_name('nodedc-deploy')))
spec = importlib.util.spec_from_loader(loader.name, loader)
R = importlib.util.module_from_spec(spec)
loader.exec_module(R)
def put(root, rel, data):
target = root / rel
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(data)
def fixture(root, number=12, sha='a'*40):
files = {'.dockerignore': b'.env\nsecrets\n', 'package.json': b'{}', 'package-lock.json': b'{}',
'services/device-control-core/Dockerfile': b'FROM node:22-alpine\n',
'services/device-manager/Dockerfile': b'FROM node:22-alpine\n',
'services/device-control-core/src/server.mjs': b'fixture',
'services/device-control-core/migrations/001.sql': b'-- fixture',
'services/device-manager/server/app.mjs': b'fixture',
'services/device-manager/dist/index.html': b'<div>fixture</div>'}
for entry in R.DEVICE_RELEASE_ENTRIES[3:6]: files[entry+'/src/index.mjs'] = b'fixture'
digest = hashlib.sha256()
name = b'index.html'; data = files['services/device-manager/dist/index.html']
digest.update(len(name).to_bytes(8,'big')+name+len(data).to_bytes(8,'big')+data)
identity = 'device-core-release-v1-r'+str(number)+'-'+sha
d = {'schemaVersion':'nodedc.device-core.release.v1','repository':'SILVER/NODEDC_DEVICE_CORE',
'repositoryId':38,'branch':'main','sourceCommit':sha,'runId':number,'runNumber':number,
'releaseId':identity,'filesSha256':{k:hashlib.sha256(v).hexdigest() for k,v in files.items()},
'packagedManagerDistSha256':digest.hexdigest(),
'qualification':{'schema':'nodedc.device-core.qualification.v1','status':'qualified','deployed':False,
'sourceCommit':sha,'steps':R.DEVICE_RELEASE_STEPS,'packageLockSha256':hashlib.sha256(b'{}').hexdigest(),
'sources':{}}}
files[R.DEVICE_RELEASE_ENTRY] = json.dumps(d).encode()
for path, value in files.items(): put(root, path, value)
return d
def archive(root, destination, d):
with tarfile.open(destination,'w:gz') as a:
for name, data in [('manifest.env', ('id='+d['releaseId']+'\ncomponent=device-core-release\ntype=app-overlay\n').encode()),
('files.txt', ('\n'.join(R.DEVICE_RELEASE_ENTRIES)+'\n').encode())]:
info=tarfile.TarInfo(name);info.size=len(data);a.addfile(info,io.BytesIO(data))
a.add(root,arcname='payload')
def runtime():
return {s:{'service':s,'containerId':str(i)*64,'imageId':'sha256:'+str(i)*64,
'status':'running','running':True,'health':'healthy','restartCount':0,'runtimeConfigSha256':'f'*64}
for i,s in enumerate(R.DEVICE_RELEASE_INVENTORY,1)}
class ReleaseTests(unittest.TestCase):
def setUp(self):
self.tmp=tempfile.TemporaryDirectory();self.addCleanup(self.tmp.cleanup)
self.root=Path(self.tmp.name);self.payload=self.root/'payload';self.payload.mkdir()
self.d=fixture(self.payload);self.a=self.root/'release.tgz';archive(self.payload,self.a,self.d)
def test_real_archive_exact_scope_and_builds(self):
work=self.root/'work';work.mkdir()
manifest, entries, _=R.load_artifact(self.a,work)
self.assertEqual(manifest['id'],self.d['releaseId'])
self.assertEqual(R.component_services('device-core-release',entries),R.DEVICE_RELEASE_SERVICES)
self.assertEqual(len(R.component_builds('device-core-release',entries)),2)
self.assertTrue(R.component_compose_no_deps('device-core-release',entries))
with mock.patch.object(R,'component_compose_files', wraps=R.component_compose_files) as f, mock.patch.object(R,'DEVICE_PLANE_ROOT',self.root):
# New component delegates effective Compose to its existing owner.
R.component_compose_files('device-core-release')
self.assertIn(mock.call('device-plane'),f.call_args_list)
def test_no_partial_or_broad_service_selection(self):
for entries in [None,[],R.DEVICE_RELEASE_ENTRIES[:-1],list(R.DEVICE_RELEASE_ENTRIES)+['services/device-gateway']]:
with self.subTest(entries=entries),self.assertRaises(R.DeployError):R.component_services('device-core-release',entries)
def test_path_boundary_rejects_infrastructure_and_secrets(self):
for rel in ['docker-compose.device-plane.yml','services/device-gateway/src/app.mjs',
'services/device-manager/.env','services/device-manager/secrets/key',
'services/device-control-core/test/a.mjs','../escape','data/db','infra/watch.py',
'services/device-control-core/runtime/cache','services/device-manager/dist/a.pem']:
with self.subTest(rel=rel),self.assertRaises(R.DeployError):R.allowed_payload_path('device-core-release',rel)
def test_identity_and_qualification_cannot_select_another_target(self):
for key,value in [('repository','SILVER/other'),('repositoryId',True),('branch','develop'),
('runId',True),('runNumber',0),('sourceCommit','main'),('services',['device-postgres']),
('packagedManagerDistSha256','f'*64),('qualification',{})]:
d=copy.deepcopy(self.d);d[key]=value;put(self.payload,R.DEVICE_RELEASE_ENTRY,json.dumps(d).encode())
with self.subTest(key=key),self.assertRaises(R.DeployError):R.validate_device_release_payload(self.payload,R.DEVICE_RELEASE_ENTRIES,self.d['releaseId'])
def test_payload_tampering_missing_files_and_extra_files(self):
path=self.payload/'services/device-manager/dist/index.html'
old=path.read_bytes();path.write_bytes(old+b'changed')
with self.assertRaises(R.DeployError):R.validate_device_release_payload(self.payload,R.DEVICE_RELEASE_ENTRIES,self.d['releaseId'])
path.write_bytes(old);put(self.payload,'services/device-manager/server/extra.mjs',b'new')
with self.assertRaises(R.DeployError):R.validate_device_release_payload(self.payload,R.DEVICE_RELEASE_ENTRIES,self.d['releaseId'])
def test_packaged_digest_uses_lexical_paths_including_file_directory_prefixes(self):
files={'favicon.ico':b'icon','favicon/icon.png':b'image','index.html':b'<div>fixture</div>'}
digest=hashlib.sha256()
for name,value in sorted(files.items()):
put(self.payload,'services/device-manager/dist/'+name,value)
self.d['filesSha256']['services/device-manager/dist/'+name]=hashlib.sha256(value).hexdigest()
encoded=name.encode();digest.update(len(encoded).to_bytes(8,'big')+encoded+len(value).to_bytes(8,'big')+value)
self.d['packagedManagerDistSha256']=digest.hexdigest()
put(self.payload,R.DEVICE_RELEASE_ENTRY,json.dumps(self.d).encode())
R.validate_device_release_payload(self.payload,R.DEVICE_RELEASE_ENTRIES,self.d['releaseId'])
def test_new_schema_or_build_recipe_requires_a_separate_domain(self):
live=self.root/'live';shutil.copytree(self.payload,live)
for rel in ['services/device-control-core/migrations/001.sql','services/device-manager/Dockerfile']:
previous=(live/rel).read_bytes();(live/rel).write_bytes(b'drift')
with mock.patch.object(R,'DEVICE_PLANE_ROOT',live),mock.patch.object(R,'device_release_predecessor',return_value=None),mock.patch.object(R,'validate_device_manager_control_plane_runtime') as runtime_check,self.assertRaisesRegex(R.DeployError,'immutable database/build foundation'):
R.preflight_device_release(self.payload,R.DEVICE_RELEASE_ENTRIES,self.d['releaseId'])
runtime_check.assert_not_called();(live/rel).write_bytes(previous)
def test_predecessor_from_canonical_archive_rejects_stale_or_source_drift(self):
live=self.root/'live';shutil.copytree(self.payload,live)
row={'id':self.d['releaseId'],'artifact':self.a.name,'status':'ok','component':'device-core-release','sha256':R.sha256_file(self.a)}
with mock.patch.object(R,'load_state',side_effect=lambda p:[row] if p==R.STATE_FILE else []),mock.patch.object(R,'APPLIED_DIR',self.root),mock.patch.object(R,'DEVICE_PLANE_ROOT',live),mock.patch.object(R,'TMP_DIR',self.root):
newer={'runNumber':13,'sourceCommit':'b'*40}
self.assertEqual(R.device_release_predecessor(newer)['releaseId'],self.d['releaseId'])
for value in [{'runNumber':12,'sourceCommit':'b'*40},{'runNumber':13,'sourceCommit':'a'*40}]:
with self.assertRaises(R.DeployError):R.device_release_predecessor(value)
put(live,'services/device-manager/server/drift.mjs',b'changed')
with self.assertRaisesRegex(R.DeployError,'differs'):R.device_release_predecessor(newer)
def test_failed_rollback_blocks_later_release(self):
row={'component':'device-core-release','started_apply':True,'rollback_status':'failed:RuntimeError'}
with mock.patch.object(R,'load_state',side_effect=lambda p:[row] if p==R.FAILED_STATE_FILE else []),self.assertRaisesRegex(R.DeployError,'reconciliation'):
R.device_release_predecessor({'runNumber':13,'sourceCommit':'b'*40})
def test_orphan_descriptor_never_becomes_accepted_predecessor(self):
with mock.patch.object(R,'load_state',return_value=[]),mock.patch.object(R,'DEVICE_PLANE_ROOT',self.payload),self.assertRaisesRegex(R.DeployError,'no canonical'):
R.device_release_predecessor({'runNumber':13,'sourceCommit':'b'*40})
def test_initial_predecessor_is_required(self):
with mock.patch.object(R,'load_state',return_value=[]),mock.patch.object(R,'DEVICE_PLANE_ROOT',self.root/'missing'),self.assertRaisesRegex(R.DeployError,'journal mismatch'):
R.device_release_predecessor({'runNumber':13,'sourceCommit':'b'*40})
def test_rollback_uses_previous_images_without_build_or_registry(self):
before={'runtime':runtime()}; calls=[]
with mock.patch.object(R,'restore_platform_overlay',side_effect=lambda *a:calls.append('source')),mock.patch.object(R.subprocess,'run',side_effect=lambda *a,**k:calls.append(a[0])),mock.patch.object(R,'run_compose',side_effect=lambda *a:calls.append('compose')),mock.patch.object(R,'run_healthchecks',side_effect=lambda *a:calls.append('health')),mock.patch.object(R,'accept_device_release',side_effect=lambda *a,**k:calls.append('accept')),mock.patch.object(R,'run_build') as build:
R.rollback_device_release(self.root,self.root,R.DEVICE_RELEASE_ENTRIES,'stamp',before,True)
self.assertEqual(calls[0],'source');self.assertEqual(calls[-3:],['compose','health','accept']);build.assert_not_called()
self.assertEqual([x[1:3] for x in calls if isinstance(x,list)],[['image','tag'],['image','tag']])
self.assertEqual(calls[1][-2],before['runtime']['device-control-core']['imageId'])
def test_build_failure_restores_tags_but_does_not_restart_services(self):
with mock.patch.object(R,'restore_platform_overlay'),mock.patch.object(R.subprocess,'run') as command,mock.patch.object(R,'run_compose') as compose,mock.patch.object(R,'run_healthchecks') as health,mock.patch.object(R,'accept_device_release'):
R.rollback_device_release(self.root,self.root,R.DEVICE_RELEASE_ENTRIES,'stamp',{'runtime':runtime()},False)
self.assertEqual(command.call_count,2);compose.assert_not_called();health.assert_not_called()
def test_acceptance_rejects_preserved_service_recreation_or_new_config(self):
old=runtime();before={'runtime':old,'compose':{},'descriptor':self.d}
for service,key,value in [('device-postgres','containerId','z'*64),('device-manager','runtimeConfigSha256','e'*64),('device-control-core','containerId',old['device-control-core']['containerId'])]:
new=copy.deepcopy(old)
for selected in R.DEVICE_RELEASE_SERVICES:new[selected]['containerId']='c'*64
new[service][key]=value
with self.subTest(service=service,key=key),mock.patch.object(R,'device_release_runtime_snapshot',return_value=new),mock.patch.object(R,'docker_json',side_effect=lambda args,label:[{'Id':old[args[-1].split('/')[1].split(':')[0]]['imageId']}]),self.assertRaises(R.DeployError):R.accept_device_release(before)
def test_compose_never_rebuilds_pulls_or_starts_dependencies(self):
with mock.patch.object(R,'compose_base_cmd',return_value=['docker','compose']),mock.patch.object(R,'component_compose_root',return_value=self.root),mock.patch.object(R.subprocess,'run') as command:
R.run_compose('device-core-release',R.DEVICE_RELEASE_SERVICES,R.DEVICE_RELEASE_ENTRIES)
cmd=command.call_args_list[0].args[0]
for arg in ['--no-deps','--no-build','--force-recreate']:self.assertIn(arg,cmd)
self.assertEqual(cmd[cmd.index('--pull')+1],'never');self.assertEqual(cmd[-2:],list(R.DEVICE_RELEASE_SERVICES))
def execute_apply(self, *, fail_at=None):
live=self.root/'live';live.mkdir()
old=fixture(live,number=11,sha='b'*40)
before={'runtime':runtime(),'compose':{},'descriptor':self.d,'otherComposeServices':{},
'installedFiles':R.collect_exact_files(live,R.DEVICE_RELEASE_ENTRIES,'test')}
events=[]
config={**R.COMPONENTS['device-core-release'],'payload_root':live,'compose_root':live}
for directory in ['inbox','applied','failed','backups','state','tmp']:(self.root/directory).mkdir()
compose=live/'compose.yml';compose.write_text('fixture')
def operation(name):
def call(*args,**kwargs):
events.append(name)
if name==fail_at:raise R.DeployError('injected '+name)
return call
with ExitStack() as stack:
for name,value in [('INBOX',self.root/'inbox'),('APPLIED_DIR',self.root/'applied'),
('FAILED_DIR',self.root/'failed'),('BACKUPS_DIR',self.root/'backups'),
('STATE_DIR',self.root/'state'),('TMP_DIR',self.root/'tmp'),
('STATE_FILE',self.root/'state/applied.jsonl'),('FAILED_STATE_FILE',self.root/'state/failed.jsonl'),
('LOCK_DIR',self.root/'lock'),('DOCKER',Path('/usr/bin/true'))]:
stack.enter_context(mock.patch.object(R,name,value))
stack.enter_context(mock.patch.dict(R.COMPONENTS,{'device-core-release':config}))
for name in ['require_root','ensure_layout','validate_artifact_location']:
stack.enter_context(mock.patch.object(R,name))
stack.enter_context(mock.patch.object(R,'component_compose_files',return_value=(compose,)))
stack.enter_context(mock.patch.object(R,'preflight_device_release',return_value=before))
for name,label in [('run_build','build'),('run_compose','compose'),('run_healthchecks','health')]:
stack.enter_context(mock.patch.object(R,name,side_effect=operation(label)))
def acceptance(*args,**kwargs):
if kwargs.get('rollback'):
events.append('rollback-accept')
self.assertEqual(R.collect_exact_files(live,R.DEVICE_RELEASE_ENTRIES,'restored'),before['installedFiles'])
else:operation('accept')()
stack.enter_context(mock.patch.object(R,'accept_device_release',side_effect=acceptance))
stack.enter_context(mock.patch.object(R.subprocess,'run',side_effect=operation('tag')))
stack.enter_context(redirect_stdout(io.StringIO()));stack.enter_context(redirect_stderr(io.StringIO()))
if fail_at:
with self.assertRaises(R.DeployError):R.apply_artifact(self.a)
else:R.apply_artifact(self.a)
applied=R.load_state(R.STATE_FILE);failed=R.load_state(R.FAILED_STATE_FILE)
return events,applied,failed
def test_apply_journals_success_only_after_acceptance(self):
events,applied,failed=self.execute_apply()
self.assertEqual(events,['build','compose','health','accept'])
self.assertEqual(len(applied),1);self.assertFalse(failed)
self.assertEqual(applied[0]['sha256'],R.sha256_file(self.root/'applied/release.tgz'))
self.assertFalse(self.a.exists())
def test_failed_build_preserves_runtime_and_restores_source_and_tags(self):
events,applied,failed=self.execute_apply(fail_at='build')
self.assertFalse(applied);self.assertEqual(failed[0]['rollback_status'],'ok:device-core-release')
self.assertEqual(events,['build','tag','tag','rollback-accept'])
def test_failed_acceptance_rolls_back_before_failure_journal(self):
events,applied,failed=self.execute_apply(fail_at='accept')
self.assertFalse(applied);self.assertEqual(failed[0]['rollback_status'],'ok:device-core-release')
self.assertEqual(events,['build','compose','health','accept','tag','tag','compose','health','rollback-accept'])
def test_persistent_health_failure_is_reconciliation_required(self):
events,applied,failed=self.execute_apply(fail_at='health')
self.assertFalse(applied);self.assertEqual(failed[0]['rollback_status'],'failed:DeployError')
self.assertNotIn('rollback-accept',events)
def test_health_checks_selected_and_preserved_services(self):
with mock.patch.object(R,'healthcheck_compose_service_with_grace') as check,mock.patch.object(R,'healthcheck_url'),mock.patch.object(R,'component_healthchecks',return_value=[]):
R.run_healthchecks('device-core-release',R.DEVICE_RELEASE_ENTRIES,R.DEVICE_RELEASE_SERVICES)
self.assertEqual([x.args[1] for x in check.call_args_list],list(R.DEVICE_RELEASE_INVENTORY))
if __name__=='__main__':unittest.main()