Make Device Core primary network selection deterministic

This commit is contained in:
Codex
2026-09-30 11:03:58 +03:00
parent aba78dea98
commit 93b91a4b1e
7 changed files with 747 additions and 7 deletions
+225 -4
View File
@@ -2962,6 +2962,10 @@ GITEA_SALVAGE_UNSUPPORTED_SCHEMA_TABLES = tuple(
)
COMPONENTS = {
"device-core-network-priority": {
"payload_root": DEVICE_PLANE_ROOT,
"artifact_only": True, "services": (),
},
"device-core-autodeploy": {
"payload_root": Path("/volume1/docker/nodedc-device-autodeploy"),
"bootstrap_root": True, "artifact_only": True, "services": (),
@@ -4979,6 +4983,10 @@ def denied_payload_path(component, rel):
def allowed_payload_path(component, rel):
validate_posix_path(rel)
if component == "device-core-network-priority":
if rel in ("deployment", *DEVICE_PRIORITY_ENTRIES):
return True
die("Device Core network priority accepts only its fixed two files")
if component == "device-core-autodeploy":
if rel in ("deployment", DEVICE_AUTODEPLOY_ENTRY):
return True
@@ -11607,6 +11615,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-network-priority":
validate_device_priority_payload(payload_dir, entries, manifest["id"])
if manifest["component"] == "device-core-autodeploy":
validate_device_autodeploy_payload(payload_dir, entries, manifest["id"])
if manifest["component"] == "device-core-release-drift-audit":
@@ -22463,6 +22473,10 @@ def is_platform_provider_catalog_only(entries):
def component_services(component, entries=None):
if component == "device-core-network-priority":
if tuple(entries or ()) != DEVICE_PRIORITY_ENTRIES:
die("Device Core network priority requires exact entries")
return ()
if component == "device-core-autodeploy":
if tuple(entries or ()) != (DEVICE_AUTODEPLOY_ENTRY,):
die("Device Core autodeploy requires the exact descriptor entry")
@@ -22804,7 +22818,7 @@ def component_compose_files(
expected_node_intelligence_gateway_sha256=None,
):
if component == "device-core-release":
return component_compose_files("device-plane")
return device_priority_compose_files(component_compose_files("device-plane"))
if component == "engine":
root = component_root(component)
files = [root / "docker-compose.yml"]
@@ -32332,6 +32346,185 @@ def rollback_gitea_ci(root, backup_dir, entries, current_stamp, runtime_started)
# Recurring application releases: a separate domain from immutable historical
# Device Plane transitions. No Compose, database, secret or controller payload.
DEVICE_PRIORITY_ID = "device-core-network-priority-v1-20260930-001"
DEVICE_PRIORITY_ENTRY = "deployment/device-core-network-priority-v1.json"
DEVICE_PRIORITY_COMPOSE = "docker-compose.device-release-network-priority.yml"
DEVICE_PRIORITY_ENTRIES = (DEVICE_PRIORITY_COMPOSE, DEVICE_PRIORITY_ENTRY)
DEVICE_PRIORITY_BASELINE = "device-core-release-v1-r12-b2660df9e26afe977bfa62efd35a8397eac4898b"
DEVICE_PRIORITY_BASELINE_SHA = "44c62036967c3ed26bd6c82f94e6f4103ccad06f45c383498210b43ad80c9d7c"
DEVICE_PRIORITY_NETWORKS = {
"device-control-core": ("device-plane-private", "device-plane-egress"),
"device-manager": ("device-plane-private", "platform-edge"),
}
DEVICE_PRIORITY_YAML = """services:
device-control-core:
networks:
device-plane-private:
priority: 100
device-plane-egress:
priority: 0
device-manager:
networks:
device-plane-private:
priority: 100
platform-edge:
priority: 0
"""
def device_priority_descriptor():
return {"schemaVersion": "nodedc.device-core.network-priority.v1", "releaseId": DEVICE_PRIORITY_ID,
"baselineReleaseId": DEVICE_PRIORITY_BASELINE, "baselineSha256": DEVICE_PRIORITY_BASELINE_SHA,
"mode": "metadata-only-existing-primary-network", "primaryPriority": 100, "secondaryPriority": 0}
def validate_device_priority_payload(root, entries, identity):
if tuple(entries) != DEVICE_PRIORITY_ENTRIES or identity != DEVICE_PRIORITY_ID:
die("Device Core network priority identity/entries mismatch")
if read_strict_json(root / DEVICE_PRIORITY_ENTRY, "Device Core network priority") != device_priority_descriptor():
die("Device Core network priority descriptor mismatch")
path = root / DEVICE_PRIORITY_COMPOSE
if path.is_symlink() or not path.is_file() or path.read_bytes() != DEVICE_PRIORITY_YAML.encode():
die("Device Core network priority Compose mismatch")
def device_priority_no_failed_rollback():
for row in load_state(FAILED_STATE_FILE):
if (row.get("component") == "device-core-network-priority" and row.get("started_apply")
and row.get("rollback_status") != "ok:device-core-network-priority-metadata-only"):
die("Device Core network priority requires reconciliation of failed rollback")
def device_priority_compose_files(files):
device_priority_no_failed_rollback()
present = [(DEVICE_PLANE_ROOT / entry).exists() or (DEVICE_PLANE_ROOT / entry).is_symlink()
for entry in DEVICE_PRIORITY_ENTRIES]
if not any(present):
return files
if not all(present):
die("Device Core network priority activation is incomplete")
validate_device_priority_payload(DEVICE_PLANE_ROOT, DEVICE_PRIORITY_ENTRIES, DEVICE_PRIORITY_ID)
rows = [r for r in load_state(STATE_FILE) if r.get("id") == DEVICE_PRIORITY_ID]
if len(rows) != 1 or rows[0].get("component") != "device-core-network-priority":
die("Device Core network priority has no unique canonical receipt")
# A marker alone does not authorize the extra effective Compose file.
with tempfile.TemporaryDirectory(prefix="device-priority-proof-", dir=TMP_DIR) as tmp:
manifest, entries, payload = load_artifact(device_release_applied_archive(rows[0]), Path(tmp))
if manifest["id"] != DEVICE_PRIORITY_ID or manifest["component"] != "device-core-network-priority":
die("Device Core network priority receipt identity mismatch")
validate_device_priority_payload(payload, entries, manifest["id"])
return (*files, DEVICE_PLANE_ROOT / DEVICE_PRIORITY_COMPOSE)
def device_priority_baseline():
device_priority_no_failed_rollback()
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:")
and not device_release_r5_reconciled(row)):
die("Device Core network priority requires application reconciliation")
rows = [r for r in load_state(STATE_FILE) if r.get("component") == "device-core-release"]
if not rows or rows[-1].get("id") != DEVICE_PRIORITY_BASELINE or rows[-1].get("sha256") != DEVICE_PRIORITY_BASELINE_SHA:
die("Device Core network priority requires the exact accepted r12 baseline")
with tempfile.TemporaryDirectory(prefix="device-priority-baseline-", dir=TMP_DIR) as tmp:
manifest, entries, payload = load_artifact(device_release_applied_archive(rows[-1]), Path(tmp))
if manifest["component"] != "device-core-release" or manifest["id"] != DEVICE_PRIORITY_BASELINE:
die("Device Core network priority baseline identity mismatch")
validate_device_release_payload(payload, entries, manifest["id"])
expected = collect_exact_files(payload, entries, "Device Core network priority baseline")
if collect_exact_files(DEVICE_PLANE_ROOT, DEVICE_RELEASE_ENTRIES, "Device Core network priority live source") != expected:
die("Device Core network priority installed source drift")
return expected
def device_priority_config(override=None):
command = compose_base_cmd("device-plane")
if override is not None:
command = [*command, "-f", str(override)]
result = subprocess.run([*command, "config", "--format", "json"], cwd=str(DEVICE_PLANE_ROOT),
capture_output=True, text=True, timeout=45, check=False)
if result.returncode or len(result.stdout) > 8 * 1024 * 1024:
die("Device Core network priority effective config failed")
try:
value = json.loads(result.stdout)
except (ValueError, TypeError):
die("Device Core network priority effective config is invalid")
if not isinstance(value, dict) or not isinstance(value.get("services"), dict):
die("Device Core network priority effective config is incomplete")
return value # Private in-memory comparison only; never log config/Env.
def device_priority_config_proof(base, candidate):
expected = json.loads(json.dumps(base))
actual = json.loads(json.dumps(candidate))
for service, networks in DEVICE_PRIORITY_NETWORKS.items():
for config in (expected, actual):
edges = config.get("services", {}).get(service, {}).get("networks")
if not isinstance(edges, dict) or set(edges) != set(networks):
die("Device Core network priority changes attached networks")
for name in networks:
edge = edges[name]
if not isinstance(edge, dict) or type(edge.get("priority", 0)) is not int:
die("Device Core network priority endpoint is invalid")
# Compose 2.20 omits the zero default in config JSON.
if edge.get("priority") == 0:
edge.pop("priority")
edges = expected["services"][service]["networks"]
if any(edge.get("priority", 0) != 0 for edge in edges.values()):
die("Device Core network priority predecessor already specifies priorities")
edges[networks[0]]["priority"] = 100
if expected != actual:
die("Device Core network priority changes more than the two primary priorities")
return {"baseConfigSha256": device_release_drift_digest(base),
"candidateConfigSha256": device_release_drift_digest(candidate)}
def preflight_device_priority(payload, entries, identity):
validate_device_priority_payload(payload, entries, identity)
if any((DEVICE_PLANE_ROOT / rel).exists() or (DEVICE_PLANE_ROOT / rel).is_symlink() for rel in entries):
die("Device Core network priority is an initial-only transition")
installed = device_priority_baseline()
run_healthchecks("device-core-release", DEVICE_RELEASE_ENTRIES, DEVICE_RELEASE_SERVICES)
validate_device_manager_control_plane_runtime(require_edge_channel=True, core_network_mode="private-egress", require_persistent_data=True, read_only=True)
runtime = device_release_runtime_snapshot_v2()
digests = device_release_capture_field_digests(runtime)
primary = device_release_drift_digest("nodedc-device-plane-private")
if any(digests[s].get("HostConfig.NetworkMode") != primary for s in DEVICE_RELEASE_SERVICES):
die("Device Core network priority must preserve the existing private primary network")
networks = {"device-control-core": ["nodedc-device-plane-egress", "nodedc-device-plane-private"],
"device-manager": ["nodedc-device-plane-private", "nodedc-platform_edge"]}
if any(digests[s].get("networks") != device_release_drift_digest(names) for s, names in networks.items()):
die("Device Core network priority runtime network set mismatch")
proof = device_priority_config_proof(device_priority_config(), device_priority_config(payload / DEVICE_PRIORITY_COMPOSE))
version = subprocess.run([str(DOCKER), "compose", "version", "--short"], capture_output=True,
text=True, timeout=15, check=True).stdout.strip()
if not re.fullmatch(r"v?[0-9]+\.[0-9]+\.[0-9]+(?:[-+][A-Za-z0-9.-]+)?", version):
die("Device Core network priority Compose version is invalid")
return {**proof, "composeVersion": version, "runtime": runtime, "installedFiles": installed,
"compose": {str(p): sha256_file(p) for p in component_compose_files("device-plane")},
"otherComposeServices": device_release_other_compose_services()}
def accept_device_priority(before, rollback=False):
if rollback:
if any((DEVICE_PLANE_ROOT / rel).exists() or (DEVICE_PLANE_ROOT / rel).is_symlink() for rel in DEVICE_PRIORITY_ENTRIES):
die("Device Core network priority rollback left activation files")
else:
validate_device_priority_payload(DEVICE_PLANE_ROOT, DEVICE_PRIORITY_ENTRIES, DEVICE_PRIORITY_ID)
proof = device_priority_config_proof(device_priority_config(), device_priority_config(DEVICE_PLANE_ROOT / DEVICE_PRIORITY_COMPOSE))
if any(proof[k] != before[k] for k in proof):
die("Device Core network priority effective config changed after plan")
if device_release_drift_digest(device_priority_config()) != before["baseConfigSha256"]:
die("Device Core network priority changed base effective config")
if (device_release_runtime_snapshot_v2() != before["runtime"]
or device_release_other_compose_services() != before["otherComposeServices"]
or {str(p): sha256_file(p) for p in component_compose_files("device-plane")} != before["compose"]
or device_priority_baseline() != before["installedFiles"]):
die("Device Core network priority changed preserved source/runtime")
run_healthchecks("device-core-release", DEVICE_RELEASE_ENTRIES, DEVICE_RELEASE_SERVICES)
print("device_network_priority_accept=" + ("rollback" if rollback else "metadata-only") + ";services=none;runtime=preserved")
DEVICE_RELEASE_ENTRY = "deployment/device-core-release-v1.json"
DEVICE_RELEASE_ENTRIES = (
".dockerignore", "package.json", "package-lock.json",
@@ -32992,7 +33185,7 @@ def preflight_device_release(payload, entries, patch_id):
run_healthchecks("device-core-release", entries, DEVICE_RELEASE_SERVICES)
before = device_release_runtime_snapshot_v2()
field_digests = device_release_capture_field_digests(before)
compose = {str(p): sha256_file(p) for p in component_compose_files("device-plane")}
compose = {str(p): sha256_file(p) for p in component_compose_files("device-core-release")}
return {"runtimeFingerprintVersion": 2, "descriptor": d, "predecessor": predecessor["releaseId"] if predecessor else "manager-v13/core-v4/edge-v4",
"runtime": before, "runtimeFieldDigests": field_digests,
"compose": compose, "otherComposeServices": device_release_other_compose_services(),
@@ -33025,7 +33218,7 @@ def accept_device_release(before, *, rollback=False):
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"]:
if {str(p): sha256_file(p) for p in component_compose_files("device-core-release")} != 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, read_only=True)
if rollback:
@@ -33104,6 +33297,12 @@ 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-network-priority":
priority_before = preflight_device_priority(payload_dir, entries, manifest["id"])
print("device_network_priority_compose=" + priority_before["composeVersion"])
print("device_network_priority_delta=core-private:100,manager-private:100;secondary:0")
print("device_network_priority_source=accepted-r12;services=none;build=none;runtime-mutation=none")
print("device_network_priority_preserved=all-runtime,databases,volumes,ports,secrets;rollback=two-new-files-only")
if manifest["component"] == "device-core-autodeploy":
auto_before = preflight_device_autodeploy(payload_dir, entries, manifest["id"])
print("device_autodeploy_scheduler=native-systemd;binary=" + auto_before["systemctl"])
@@ -39289,6 +39488,10 @@ 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-network-priority":
if tuple(entries or ()) != DEVICE_PRIORITY_ENTRIES or tuple(services or ()) != ():
die("Device Core network priority health scope mismatch")
return # Exact before/after acceptance belongs to accept_device_priority.
if component == "device-core-release-reconciliation":
if tuple(services or ()) != ():
die("Device Core reconciliation must not select services")
@@ -40418,6 +40621,7 @@ def apply_artifact(artifact):
device_release_before = None
gitea_actions_before = None
device_autodeploy_before = None
device_priority_before = None
current_stamp = stamp()
with DeployLock():
@@ -40462,6 +40666,8 @@ def apply_artifact(artifact):
compose_root = component_compose_root(component)
bootstrap_root = bool(COMPONENTS[component].get("bootstrap_root"))
services = component_services(component, entries)
if component == "device-core-network-priority":
device_priority_before = preflight_device_priority(payload_dir, entries, patch_id)
if component == "mission-core-map-access":
preflight_map_access(payload_dir, entries)
if component == "gitea-ci":
@@ -40999,6 +41205,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-network-priority":
proof = backup_dir / "device-network-priority-before.json"
proof.write_text(json.dumps(device_priority_before, sort_keys=True) + "\n", encoding="utf-8")
proof.chmod(0o600)
if component == "device-core-autodeploy":
proof = backup_dir / "autodeploy-before.json"
proof.write_text(json.dumps(device_autodeploy_before, sort_keys=True) + "\n", encoding="utf-8")
@@ -41101,6 +41311,8 @@ def apply_artifact(artifact):
elif component == "device-core-autodeploy":
runtime_started = True
apply_device_autodeploy(device_autodeploy_before)
elif component == "device-core-network-priority":
pass # Metadata only: never build, pull, restart or recreate.
elif component == "gitea-actions-config":
runtime_started = True
apply_gitea_actions(gitea_actions_before, backup_dir)
@@ -41140,6 +41352,8 @@ def apply_artifact(artifact):
):
die("Engine L2 closed-loop app generation was not recreated")
run_healthchecks(component, entries, services)
if component == "device-core-network-priority":
accept_device_priority(device_priority_before)
if component == "device-core-autodeploy":
accept_device_autodeploy(device_autodeploy_before)
if component == "device-core-release":
@@ -41218,7 +41432,14 @@ def apply_artifact(artifact):
and backup_dir is not None
and root is not None
):
if component == "device-core-autodeploy":
if component == "device-core-network-priority":
try:
restore_platform_overlay(root, backup_dir, entries, current_stamp)
accept_device_priority(device_priority_before, rollback=True)
rollback_status = "ok:device-core-network-priority-metadata-only"
except Exception as rollback_exc:
rollback_status = "failed:" + type(rollback_exc).__name__
elif component == "device-core-autodeploy":
try:
rollback_device_autodeploy(root, backup_dir, entries, current_stamp, device_autodeploy_before)
rollback_status = "ok:device-core-autodeploy-bootstrap"