From 755a124bd8c245bf9b999cc2e27c3ac097b6c272 Mon Sep 17 00:00:00 2001 From: DCCONSTRUCTIONS Date: Thu, 29 Oct 2026 09:10:02 +0300 Subject: [PATCH] build(node): ship qualified installers with CAN maintenance and rollback Publish qualified Node and device bundles through versioned installers. Coordinate CAN maintenance, dependency closure, retained rollback and packaging provenance. --- .../50-mission-core-device-prepare.rules | 2 +- apps/node-agent/packaging/build.py | 1 + apps/node-agent/packaging/build_deb.py | 14 +- .../packaging/build_linux_source.py | 53 +++- .../packaging/build_owner_release.py | 14 +- apps/node-agent/packaging/can_maintenance.py | 270 ++++++++++++++++++ .../packaging/fetch_monitor_dependencies.py | 6 +- .../packaging/insta360-profile.json | 8 +- .../packaging/install_owner_release.py | 40 ++- .../node-agent/packaging/linux_build_entry.py | 80 ++++-- apps/node-agent/packaging/linux_build_job.py | 61 +++- .../mission-core-node-wifi-trial.service | 13 + .../mission-core-node-wireguard.service | 27 ++ .../packaging/mission-core-node.service | 2 +- apps/node-agent/packaging/postinst | 3 + apps/node-agent/packaging/preinst | 7 + apps/node-agent/packaging/prerm | 25 ++ .../packaging/repack_codec_recovery.py | 133 +++++++++ .../packaging/repack_preview_cost.py | 130 +++++++++ .../packaging/repack_wireguard_helper.py | 75 +++++ .../packaging/resume_node72_packaging.py | 153 ++++++++++ .../packaging/test_build_source_reuse.py | 52 ++++ .../packaging/test_can_maintenance.py | 227 +++++++++++++++ .../packaging/test_install_owner_release.py | 27 ++ .../packaging/test_owner_dependencies.py | 54 ++++ .../packaging/test_resume_node72_packaging.py | 53 ++++ .../packaging/test_vesc_hall_recovery.py | 126 ++++++++ .../packaging/test_wifi_latency_trial.py | 187 ++++++++++++ .../packaging/vesc_hall_recovery.py | 152 ++++++++++ .../packaging/wifi_latency_trial.py | 253 ++++++++++++++++ apps/node-agent/ui/src/CoreConnectionView.tsx | 7 + apps/node-agent/ui/src/NodeSensors.tsx | 6 +- apps/node-agent/ui/src/api.ts | 4 +- docs/node/37_CAN_INSTALLER_MAINTENANCE.md | 106 +++++++ scripts/publish_fleet_installer.py | 7 +- src/k1link/web/installer_api.py | 3 +- 36 files changed, 2322 insertions(+), 59 deletions(-) create mode 100644 apps/node-agent/packaging/can_maintenance.py create mode 100644 apps/node-agent/packaging/mission-core-node-wifi-trial.service create mode 100644 apps/node-agent/packaging/mission-core-node-wireguard.service create mode 100644 apps/node-agent/packaging/repack_codec_recovery.py create mode 100644 apps/node-agent/packaging/repack_preview_cost.py create mode 100644 apps/node-agent/packaging/repack_wireguard_helper.py create mode 100644 apps/node-agent/packaging/resume_node72_packaging.py create mode 100644 apps/node-agent/packaging/test_build_source_reuse.py create mode 100644 apps/node-agent/packaging/test_can_maintenance.py create mode 100644 apps/node-agent/packaging/test_install_owner_release.py create mode 100644 apps/node-agent/packaging/test_owner_dependencies.py create mode 100644 apps/node-agent/packaging/test_resume_node72_packaging.py create mode 100644 apps/node-agent/packaging/test_vesc_hall_recovery.py create mode 100644 apps/node-agent/packaging/test_wifi_latency_trial.py create mode 100644 apps/node-agent/packaging/vesc_hall_recovery.py create mode 100644 apps/node-agent/packaging/wifi_latency_trial.py create mode 100644 docs/node/37_CAN_INSTALLER_MAINTENANCE.md diff --git a/apps/node-agent/packaging/50-mission-core-device-prepare.rules b/apps/node-agent/packaging/50-mission-core-device-prepare.rules index 367c73e2..13b02a51 100644 --- a/apps/node-agent/packaging/50-mission-core-device-prepare.rules +++ b/apps/node-agent/packaging/50-mission-core-device-prepare.rules @@ -1,7 +1,7 @@ // An authenticated Node action may start only this fixed model job. polkit.addRule(function(action, subject) { var unit = action.lookup("unit"); - if (subject.user === "mission-core-node" && action.id === "org.freedesktop.systemd1.manage-units" && (unit === "mission-core-node-vesc-prepare.service" || unit === "mission-core-node-realsense-prepare.service" || unit === "mission-core-node-insta360-x4-profile.service") && action.lookup("verb") === "start") { + if (subject.user === "mission-core-node" && action.id === "org.freedesktop.systemd1.manage-units" && (unit === "mission-core-node-usb-can-prepare.service" || unit === "mission-core-node-vesc-prepare.service" || unit === "mission-core-node-realsense-prepare.service" || unit === "mission-core-node-insta360-x4-profile.service") && action.lookup("verb") === "start") { return polkit.Result.YES; } }); diff --git a/apps/node-agent/packaging/build.py b/apps/node-agent/packaging/build.py index 8dc97c4a..5c082cda 100644 --- a/apps/node-agent/packaging/build.py +++ b/apps/node-agent/packaging/build.py @@ -34,6 +34,7 @@ def provenance(): "base_commit": subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=ROOT, text=True).strip(), "design_guideline_commit": DG_COMMIT, "design_guideline_files": guideline_sources(), + "wireguard_client_sha256": hashlib.sha256((ROOT.parent / "wireguard-client/helper.py").read_bytes()).hexdigest(), "shared_sensor_ui_files": {str(p.relative_to(ROOT.parents[1])): hashlib.sha256(p.read_bytes()).hexdigest() for p in sorted((ROOT.parents[1] / "packages/sensor-ui/src").rglob("*")) if p.is_file()}, "shared_spatial_ui_files": {str(p.relative_to(ROOT.parents[1])): hashlib.sha256(p.read_bytes()).hexdigest() for p in sorted((ROOT.parents[1] / "packages/spatial-ui/src").rglob("*")) if p.is_file()}, "vesc_plugin_files": {str(p.relative_to(ROOT.parents[1])): hashlib.sha256(p.read_bytes()).hexdigest() for p in sorted((ROOT.parents[1] / "plugins/vesc").rglob("*")) if p.is_file() and not any(x in p.relative_to(ROOT.parents[1]).parts for x in ("__pycache__", "build"))}, diff --git a/apps/node-agent/packaging/build_deb.py b/apps/node-agent/packaging/build_deb.py index a160ada4..baaaecb7 100644 --- a/apps/node-agent/packaging/build_deb.py +++ b/apps/node-agent/packaging/build_deb.py @@ -11,8 +11,8 @@ import sys ROOT = Path(__file__).resolve().parents[1] -BINARY_VERSION = "0.8.46" -VERSION = "0.8.46-1" +BINARY_VERSION = "0.8.49" +VERSION = "0.8.49-94" sys.path.insert(0, str(ROOT.parents[1] / "scripts/packaging")) from debian import package @@ -44,13 +44,15 @@ Architecture: amd64 Maintainer: NODE.DC local build Section: admin Priority: optional -Depends: adduser, systemd (>= 255), python3 (>= 3.12), python3 (<< 3.13), python3-gi, gir1.2-gtk-3.0, gir1.2-webkit2-4.1, pkexec, polkitd, ca-certificates, hicolor-icon-theme, network-manager, iproute2, python3-psycopg2, postgresql-16 (>= 16.15), timescaledb-2-oss-postgresql-16 (= 2.29.2~ubuntu24.04-1615), udev, usbutils, libc6 (>= 2.39), libstdc++6 (>= 12), libgcc-s1, zlib1g +Depends: adduser, systemd (>= 255), python3 (>= 3.12), python3 (<< 3.13), python3-gi, gir1.2-gtk-3.0, gir1.2-webkit2-4.1, pkexec, polkitd, ca-certificates, hicolor-icon-theme, network-manager, iproute2, wireguard-tools, python3-psycopg2, postgresql-16 (>= 16.15), timescaledb-2-oss-postgresql-16 (= 2.29.2~ubuntu24.04-1615), udev, usbutils, libc6 (>= 2.39), libstdc++6 (>= 12), libgcc-s1, zlib1g Description: Mission Core onboard computer configuration Local graphical setup, host inventory, SSH access and persistent node identity. """.encode() controls = [("control", control, 0o644)] controls += [(name, (p / name).read_bytes(), 0o755) for name in ["preinst", "postinst", "prerm", "postrm"]] files = [("usr/lib/mission-core-node/node-agent", payload, 0o755)] + files.append(("usr/lib/mission-core-node/wireguard_helper.py", (ROOT.parent / "wireguard-client/helper.py").read_bytes(), 0o644)) + files.append(("usr/lib/systemd/system/mission-core-node-wireguard.service", (p / "mission-core-node-wireguard.service").read_bytes(), 0o644)) brand = (ROOT.parents[2] / "NODEDC_DESIGN_GUIDELINE/apps/catalog/public/nodedc-mark.svg").read_bytes() files.append(("usr/share/icons/hicolor/scalable/apps/org.nodedc.MissionCoreNode.svg", desktop_icon(brand), 0o644)) for source, path, mode in [ @@ -61,10 +63,14 @@ Description: Mission Core onboard computer configuration ("org.nodedc.mission-core-node.policy", "usr/share/polkit-1/actions/org.nodedc.mission-core-node.policy", 0o644), ("60-mission-core-node.conf", "usr/share/mission-core-node/60-mission-core-node.conf", 0o644), ("network_helper.py", "usr/lib/mission-core-node/network_helper.py", 0o644), + ("wifi_latency_trial.py", "usr/lib/mission-core-node/wifi_latency_trial.py", 0o644), + ("mission-core-node-wifi-trial.service", "usr/lib/systemd/system/mission-core-node-wifi-trial.service", 0o644), ("install-tailscale", "usr/lib/mission-core-node/install-tailscale", 0o755), ("connect-tailscale", "usr/lib/mission-core-node/connect-tailscale", 0o755), ("tailscale-release.json", "usr/share/mission-core-node/tailscale-release.json", 0o644), ("configure-system", "usr/lib/mission-core-node/configure-system", 0o755), + ("vesc_hall_recovery.py", "usr/lib/mission-core-node/vesc_hall_recovery.py", 0o644), + ("can_maintenance.py", "usr/lib/mission-core-node/can_maintenance.py", 0o644), ("environment_helper.py", "usr/lib/mission-core-node/environment_helper.py", 0o644), ("desktop_startup.py", "usr/lib/mission-core-node/desktop_startup.py", 0o644), ("mission-core-node-autostart.desktop", "usr/share/mission-core-node/mission-core-node-autostart.desktop", 0o644), @@ -81,6 +87,7 @@ Description: Mission Core onboard computer configuration if path.suffix in {'.py', '.sql'}: files.append(('usr/lib/mission-core-node/monitor/' + path.name, path.read_bytes(), 0o644)) files.append(("usr/share/mission-core-node/environment-profile.json", (ROOT / "internal/node/environment-profile.json").read_bytes(), 0o644)) + files.append(("usr/share/mission-core-node/router-observation-profile.json", (ROOT / "internal/routers/profile.json").read_bytes(), 0o644)) for name in ("realsense_prepare.py", "realsense_iio_access.py"): files.append(("usr/lib/mission-core-node/" + name, (p / name).read_bytes(), 0o644)) for name in ("mission-core-realsense.service", "mission-core-node-realsense-prepare.service"): @@ -118,6 +125,7 @@ Description: Mission Core onboard computer configuration files.append(("usr/share/doc/mission-core-node/provenance.json", (ROOT / "build/provenance.json").read_bytes(), 0o644)) import runpy files.extend(runpy.run_path(str(ROOT.parents[1] / "plugins/vesc/packaging/payload.py"))["payload"]()) + files.extend(runpy.run_path(str(ROOT.parents[1] / "plugins/usb-can/packaging/payload.py"))["payload"]()) archive = package(controls, files) destination.parent.mkdir(parents=True, exist_ok=True) destination.write_bytes(archive) diff --git a/apps/node-agent/packaging/build_linux_source.py b/apps/node-agent/packaging/build_linux_source.py index bf1c718a..99bb4ef3 100644 --- a/apps/node-agent/packaging/build_linux_source.py +++ b/apps/node-agent/packaging/build_linux_source.py @@ -5,13 +5,18 @@ import hashlib import json import stat import subprocess +import sys import zipfile from pathlib import Path NODE = Path(__file__).resolve().parents[1] REPO = NODE.parents[1] +sys.path.insert(0, str(REPO / "scripts/packaging")) +from build_retention import input_hold, publish_input # noqa: E402 + DG = REPO.parent / "NODEDC_DESIGN_GUIDELINE" DG_COMMIT = "a6e6c8f2d9c3de8d98b60c30da6a70d9538c1ef2" +USB_CAN_SDK_SHA256 = "3f4681c64b086ecd4bf538908e09ed5203a05286632c0d99485b88f9b069285c" def files(root): @@ -31,7 +36,7 @@ def files(root): yield path -def build(qualified, node_only=False): +def build(qualified, node_only=False, base=None): commit = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=DG, text=True).strip() if commit != DG_COMMIT: raise ValueError("Design Guideline revision differs from the admitted source") @@ -80,6 +85,22 @@ def build(qualified, node_only=False): if len(native_bytes) != native["bytes"] or hashlib.sha256(native_bytes).hexdigest() != native["sha256"]: raise ValueError("Qualified VESC Tool runtime changed") entries[REPO.name + "/plugins/vesc/build/native-runtime/" + native["file"]] = native_path + catalog = json.loads((native_root / "packaging/firmware-catalog.json").read_text()) + for item in catalog["items"]: + path = native_root / "build/firmware-catalog" / (item["sha256"] + ".bin") + data = path.read_bytes() + if len(data) != item["bytes"] or hashlib.sha256(data).hexdigest() != item["sha256"]: + raise ValueError("Pinned firmware image changed") + entries[str(path.relative_to(REPO.parent))] = path + package_pin=json.loads((native_root / "packaging/package-catalog.json").read_text()) + package_path=native_root / "build/package-catalog/vesc_pkg_all.rcc" + package_bytes=package_path.read_bytes() + if len(package_bytes)!=package_pin["bytes"] or hashlib.sha256(package_bytes).hexdigest()!=package_pin["sha256"]:raise ValueError("Pinned extension catalogue changed") + entries[str(package_path.relative_to(REPO.parent))]=package_path + usbcan_library = REPO / "plugins/usb-can/build/sdk/libcontrolcanfd.so" + if hashlib.sha256(usbcan_library.read_bytes()).hexdigest() != USB_CAN_SDK_SHA256: + raise ValueError("USB-CAN library pin changed") + entries[str(usbcan_library.relative_to(REPO.parent))] = usbcan_library metadata = {} for name, path in entries.items(): data = path.read_bytes() @@ -103,13 +124,37 @@ def build(qualified, node_only=False): "entrypoint_sha256": hashlib.sha256(entrypoint).hexdigest(), "files": metadata, } + payload_names = set(entries) + if base is not None: + import re + if not re.fullmatch(r"mission-core-node-linux-build-[a-f0-9]{24}\.pyz", base.name): + raise ValueError("Invalid baseline artifact name") + with zipfile.ZipFile(base) as previous: + baseline = json.loads(previous.read("source.json")) + if baseline.get("base") or baseline["schema"] != manifest["schema"]: + raise ValueError("Baseline must be a complete source artifact") + payload_names = {name for name, item in metadata.items() + if baseline["files"].get(name) != item} + with base.open("rb") as stream: + manifest["base"] = {"name": base.name, "sha256": hashlib.file_digest(stream, "sha256").hexdigest()} + manifest["payload_files"] = sorted(payload_names) raw = json.dumps(manifest, sort_keys=True, indent=2).encode() + b"\n" identifier = hashlib.sha256(raw).hexdigest()[:24] output = NODE / "build" / ("mission-core-node-linux-build-" + identifier + ".pyz") - with output.open("xb") as stream, zipfile.ZipFile(stream, "w") as archive: + required = ( + sum(metadata[name]["bytes"] for name in payload_names) + + len(raw) + len(entrypoint) + 2 * 1024**2 + ) + with ( + publish_input(output, required_bytes=required) as staged, + staged.open("xb") as stream, + zipfile.ZipFile(stream, "w") as archive, + ): for name, data in (("__main__.py", entrypoint), ("source.json", raw)): archive.writestr(name, data) for name, path in entries.items(): + if name not in payload_names: + continue archive.write( path, "source/" + name, @@ -120,6 +165,7 @@ def build(qualified, node_only=False): output.chmod(0o600) return { "artifact": str(output), + "retention": input_hold(output), "source_id": identifier, "files": len(entries), "bytes": output.stat().st_size, @@ -131,5 +177,6 @@ if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--model-package", type=Path, required=True) parser.add_argument("--node-only", action="store_true") + parser.add_argument("--base", type=Path, help="Complete verified archive already staged in the build root") args = parser.parse_args() - print(json.dumps(build(args.model_package.resolve(), args.node_only))) + print(json.dumps(build(args.model_package.resolve(), args.node_only, args.base))) diff --git a/apps/node-agent/packaging/build_owner_release.py b/apps/node-agent/packaging/build_owner_release.py index 53b85f64..19c9c34e 100644 --- a/apps/node-agent/packaging/build_owner_release.py +++ b/apps/node-agent/packaging/build_owner_release.py @@ -7,6 +7,8 @@ import re import zipfile from pathlib import Path +NODE_DEPENDENCIES = ('timescaledb-2-loader-postgresql-16_2.29.2~ubuntu24.04-1615_amd64.deb', 'timescaledb-2-oss-postgresql-16_2.29.2~ubuntu24.04-1615_amd64.deb') + ROOT = Path(__file__).resolve().parents[1] REPO = ROOT.parents[1] @@ -34,8 +36,16 @@ def build(qualified): files = { package: payload, "install": (ROOT / "packaging/install-owner-release").read_bytes(), - "install_release.py": (ROOT / "packaging/install_owner_release.py").read_bytes(), + "install_release.py": (ROOT / "packaging/vesc_hall_recovery.py").read_bytes() + b"\n" + (ROOT / "packaging/can_maintenance.py").read_bytes() + b"\n" + (ROOT / "packaging/install_owner_release.py").read_bytes(), } + # Carry non-Ubuntu dependencies in the actual owner artifact. They were + # verified against the signed vendor index by the qualified Linux job. + for name in NODE_DEPENDENCIES: + data = (qualified / name).read_bytes() + info = evidence["artifacts"][name] + if len(data) != info["bytes"] or hashlib.sha256(data).hexdigest() != info["sha256"]: + raise ValueError("Qualified dependency changed") + files[name] = data entry = (REPO / "plugins/insta360-x4/packaging/owner_release_entry.py").read_bytes() manifest = { "schema": "missioncore.node.owner-release/v1", @@ -45,6 +55,8 @@ def build(qualified): (qualified / "qualification.json").read_bytes() ).hexdigest(), "clean_image_qualified": False, + "dependencies": list(NODE_DEPENDENCIES), + "system_dependencies": "Ubuntu 24.04 amd64 repositories; online APT resolution required", "entrypoint_sha256": hashlib.sha256(entry).hexdigest(), "files": { name: {"bytes": len(data), "sha256": hashlib.sha256(data).hexdigest()} diff --git a/apps/node-agent/packaging/can_maintenance.py b/apps/node-agent/packaging/can_maintenance.py new file mode 100644 index 00000000..14ad6f1b --- /dev/null +++ b/apps/node-agent/packaging/can_maintenance.py @@ -0,0 +1,270 @@ +"""Versioned installer transaction: quiesce VESC before CAN, restore observation. + +The only legacy migration is the reviewed pre-maintenance socket protocol. It +fences new connections, drains admitted Node operations, then proves idle. It +never sends a controller command, stops an active operation, or edits config. +""" + +if "recover_hall" not in globals(): + from vesc_hall_recovery import HALL_ROOT, hall_recovery_supported, recover_hall + +import fcntl +import hashlib +import json +import os +import pwd +import stat +import subprocess +import time +from pathlib import Path + +MAINTENANCE_ROOT = Path("/run/mission-core-node-maintenance") +MARKER = MAINTENANCE_ROOT / "active" +SOCKETS = {name: Path("/run/mission-core-" + name + "/driver.sock") for name in ("vesc", "usb-can")} +LEGACY = { + "vesc": "415da47c880c629e2aec595fd37a8d802bdb7c75bcfc8eec61bbd849fd84565d", + "usb-can": "5644897c588a83227babc6856ab3d9b1e7c9696700ec35832a6c61b492a626de", +} +# SO_PEERCRED is established by connect(), so the legacy probe runs with the +# old server's admitted Node UID. GID 0 grants traversal of our private fence. +PROBE = """import http.client,json,socket,sys +payload=sys.stdin.buffer.read(65537) +assert len(payload)<=65536 +c=http.client.HTTPConnection('local',timeout=15 if payload else 7) +c.sock=socket.socket(socket.AF_UNIX);c.sock.settimeout(15 if payload else 7);c.sock.connect(sys.argv[1]) +c.request(sys.argv[2],sys.argv[3],body=payload or None,headers={'X-Node-Id':'installer','Content-Type':'application/json'}) +r=c.getresponse();b=r.read(1048577) +assert r.status==200 and len(b)<=1048576 +print(json.dumps(json.loads(b))) +c.close() +""" + + +def probe(path, route, method="GET", legacy=False, payload=None): + user = pwd.getpwnam("mission-core-node") if legacy else None + result = subprocess.run( + ["/usr/bin/python3", "-I", "-c", PROBE, str(path), method, route], + capture_output=True, + input=json.dumps(payload).encode() if payload is not None else b"", + timeout=18 if payload is not None else 10, + **({"user": user.pw_uid, "group": 0, "extra_groups": [user.pw_gid]} if user else {}), + ) + if result.returncode: + raise RuntimeError("Служба не подтвердила состояние обслуживания: " + route) + return json.loads(result.stdout) + + +def legacy_idle( + snapshot, + inventory, + root=Path("/var/lib/mission-core-vesc"), + journals=Path("/var/lib/mission-core-node/sensors"), + now=None, + recovering_hall=False, +): + if ( + snapshot.get("state") not in ("observing", "stopped", "fault") + or snapshot.get("release_confirmed") is False + ): + raise RuntimeError("Завершите управление VESC перед обновлением.") + for item in inventory["items"]: + state = item["vesc_status"] + if state["test_active"] or any( + state.get(k) + for k in ( + "configuration_pending", + "bms_configuration_pending", + "package_pending", + "code_pending", + "code_execution_pending", + ) + ): + raise RuntimeError("Операция VESC ещё выполняется или требует проверки результата.") + if state["firmware_update"]["state"] not in ("idle", "complete"): + raise RuntimeError("Результат прошивания VESC не подтверждён.") + if any( + any(p.name != "hall-pending.json" or not recovering_hall for p in root.glob(pattern)) + for pattern in ("limits_*.json", "*pending*.json", "code-execution-*.json") + ): + raise RuntimeError("Не завершено изменение настроек или восстановление ограничений VESC.") + now = time.time() if now is None else now + for path in journals.glob("op_*.json"): + record = json.loads(path.read_text()) + action = record["command"]["action_id"] + if action.startswith(("vesc.", "can.")) and record["state"] == "running": + raise RuntimeError("Дождитесь завершения операции устройства перед обновлением.") + if action.startswith("vesc.samples.") and now - record["updated_at"] < 135: + raise RuntimeError("Дождитесь завершения недавнего захвата Sample Data.") + + +class CanMaintenance: + def __init__(self, report): + self.report = report + self.entered = [] + self.fences = {} + self.stopped = [] + self.lock = None + self.owned = False + self.report.update(state="not-started", motor_commands=False, steps=[]) + + def systemctl(self, action, name): + result = subprocess.run( + ["/usr/bin/systemctl", action, "mission-core-" + name + ".service"], + capture_output=True, + timeout=30, + ) + if result.returncode: + raise RuntimeError("Не выполнено обслуживание службы " + name + ": " + action) + + def legacy(self, name): + source = Path("/usr/lib/mission-core-" + name + "/runtime/server.py") + return source.exists() and hashlib.sha256(source.read_bytes()).hexdigest() == LEGACY[name] + + def fence(self, name): + source = SOCKETS[name] + target = MAINTENANCE_ROOT / "private" / (name + ".sock") + if target.exists() or not stat.S_ISSOCK(source.lstat().st_mode): + raise RuntimeError("Не подтверждён сокет службы " + name) + source.rename(target) + self.fences[name] = (source, target, target.stat().st_ino) + return target + + def begin(self): + MAINTENANCE_ROOT.mkdir(mode=0o711, exist_ok=True) + info = MAINTENANCE_ROOT.lstat() + if not stat.S_ISDIR(info.st_mode) or info.st_uid != 0 or info.st_mode & 0o022: + raise RuntimeError("Недопустимый каталог обслуживания.") + MAINTENANCE_ROOT.chmod(0o711) + private = MAINTENANCE_ROOT / "private" + private.mkdir(mode=0o710, exist_ok=True) + info = private.lstat() + if not stat.S_ISDIR(info.st_mode) or info.st_uid != 0 or info.st_mode & 0o027: + raise RuntimeError("Недопустимый каталог изоляции сокетов.") + private.chmod(0o710) + self.lock = (MAINTENANCE_ROOT / "lock").open("a") + fcntl.flock(self.lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + if MARKER.exists() or any(private.glob("*.sock")): + raise RuntimeError( + "Предыдущее обслуживание не завершено; требуется восстановление установщиком." + ) + self.owned = True + recovering_hall = (HALL_ROOT / "hall-pending.json").exists() + if recovering_hall: + if not hall_recovery_supported() or not SOCKETS["vesc"].exists(): + raise RuntimeError("Восстановление измерения не поддерживает установленную службу.") + # Check before fencing so a live control session is never cut off. + legacy_idle(probe(SOCKETS["vesc"], "/observe", legacy=True), + probe(SOCKETS["vesc"], "/inventory", legacy=True), recovering_hall=True) + # Refuse active legacy control BEFORE fencing its relay. + if SOCKETS["vesc"].exists() and self.legacy("vesc"): + legacy_idle( + probe(SOCKETS["vesc"], "/observe", legacy=True), + probe(SOCKETS["vesc"], "/inventory", legacy=True), + ) + self.report["state"] = "entering" + for name in ("vesc", "usb-can"): + if not SOCKETS[name].exists(): + state = subprocess.run( + ["/usr/bin/systemctl", "is-active", "mission-core-" + name + ".service"], + capture_output=True, + ) + if state.returncode == 0: + raise RuntimeError("Активная служба не предоставила сокет: " + name) + continue # Clean Ubuntu or intentionally inactive optional driver. + self.entered.append(name) + if name == "vesc" and recovering_hall: + path = self.fence(name) + time.sleep(11) + inventory = probe(path, "/inventory", legacy=True) + legacy_idle(probe(path, "/observe", legacy=True), inventory, recovering_hall=True) + evidence = recover_hall(lambda command: probe(path, "/operation", "POST", legacy=True, payload=command), inventory) + self.report["hall_recovery"] = evidence + # The ordinary service guard remains authoritative after recovery. + result = probe(path, "/maintenance/enter", "POST") + if result.get("safe") is not True: + raise RuntimeError("Обслуживание после восстановления отклонено: " + str(result.get("reason"))) + self.report["steps"].append({"service": name, "protocol": "hall-recovery-v1", **result}) + elif self.legacy(name): + path = self.fence(name) + if name == "vesc": + # Old handler's bounded socket read is 10 s, read admission + # at most .5 s. Existing operations are journalled BEFORE + # dispatch. Never stop a worker while its journal is running. + time.sleep(11) + legacy_idle( + probe(path, "/observe", legacy=True), probe(path, "/inventory", legacy=True) + ) + else: + deadline = time.monotonic() + 5 + while probe(path, "/prepare-safe").get("safe") is not True: + if time.monotonic() >= deadline: + raise RuntimeError( + "CAN занят: завершите ручной канал или передачу кадров." + ) + time.sleep(0.2) + self.report["steps"].append( + {"service": name, "protocol": "pinned-legacy-drain", "safe": True} + ) + else: + result = probe(SOCKETS[name], "/maintenance/enter", "POST") + if result.get("safe") is not True: + raise RuntimeError( + "Обслуживание отклонено: " + str(result.get("reason", "unknown")) + ) + self.report["steps"].append( + {"service": name, "protocol": "admission-barrier-v1", **result} + ) + MARKER.write_text( + json.dumps({"schema": "missioncore.can-maintenance/v1", "pid": os.getpid()}) + ) + MARKER.chmod(0o644) + self.systemctl("stop", name) + self.stopped.append(name) + if not MARKER.exists(): + MARKER.write_text( + json.dumps({"schema": "missioncore.can-maintenance/v1", "pid": os.getpid()}) + ) + MARKER.chmod(0o644) + self.report["state"] = "quiescent" + + def finish(self): + if not self.owned: + if self.lock: + self.lock.close() + return + errors = [] + # Never overwrite a newly created service generation with an old socket. + for name, (source, target, inode) in self.fences.items(): + try: + if target.exists() and target.stat().st_ino == inode: + if name in self.stopped or source.exists(): + target.unlink() + else: + target.rename(source) + except OSError as error: + errors.append(str(error)) + MARKER.unlink(missing_ok=True) + # Postinst may already have started these. start is idempotent; NEVER + # restart a service that has regained observation, nor replay a command. + for name in ("usb-can", "vesc"): + try: + if name in self.stopped: + self.systemctl("start", name) + deadline = time.monotonic() + 10 + while not SOCKETS[name].exists(): + if time.monotonic() >= deadline: + raise RuntimeError("Служба не восстановила сокет: " + name) + time.sleep(0.1) + if SOCKETS[name].exists() and not self.legacy(name): + result = probe(SOCKETS[name], "/maintenance/leave", "POST") + if result.get("resumed") is not True: + raise RuntimeError("Служба не вышла из обслуживания: " + name) + except (OSError, RuntimeError) as error: + errors.append(str(error)) + self.report.update( + state="recovery-required" if errors else "observation-restored", errors=errors + ) + if self.lock: + self.lock.close() + if errors: + raise RuntimeError("; ".join(errors)) diff --git a/apps/node-agent/packaging/fetch_monitor_dependencies.py b/apps/node-agent/packaging/fetch_monitor_dependencies.py index 710a4e47..fca2ea77 100644 --- a/apps/node-agent/packaging/fetch_monitor_dependencies.py +++ b/apps/node-agent/packaging/fetch_monitor_dependencies.py @@ -27,15 +27,17 @@ def main(): args = parser.parse_args() root = args.destination root.mkdir(parents=True, exist_ok=True) + key_home = root / "gpg-home" + key_home.mkdir(mode=0o700, exist_ok=True) key = root / "timescale.asc" key.write_bytes(fetch("https://packagecloud.io/timescale/timescaledb/gpgkey", 65536)) keyring = root / "timescale.gpg" subprocess.run( - ["gpg", "--batch", "--yes", "--dearmor", "--output", str(keyring), str(key)], check=True + ["gpg", "--homedir", str(key_home.resolve()), "--batch", "--yes", "--dearmor", "--output", str(keyring), str(key)], check=True ) release = root / "InRelease" release.write_bytes(fetch(BASE + "dists/noble/InRelease", 1048576)) - subprocess.run(["gpgv", "--keyring", str(keyring.resolve()), str(release)], check=True) + subprocess.run(["gpgv", "--homedir", str(key_home.resolve()), "--keyring", str(keyring.resolve()), str(release)], check=True) lines = release.read_text().splitlines() hashes = {} inside = False diff --git a/apps/node-agent/packaging/insta360-profile.json b/apps/node-agent/packaging/insta360-profile.json index d93ba048..653c5b95 100644 --- a/apps/node-agent/packaging/insta360-profile.json +++ b/apps/node-agent/packaging/insta360-profile.json @@ -1,8 +1,8 @@ { "schema": "missioncore.node.bundled-model/v1", "model_id": "insta360.x4", - "version": "0.1.3-9", - "revision": "0b1085386d53e65760a9610f", - "bytes": 58211732, - "sha256": "eb6331680fbe8cac56eb745c31d7c37618a9dff67bc2a190681a384813cdc709" + "version": "0.1.3-30", + "revision": "6b548a3432798e8f8a06e208", + "bytes": 58235788, + "sha256": "a3312eab74d193498b8524674f4a60c77b0c04fcc4f45caa09bb4b44fbae4403" } diff --git a/apps/node-agent/packaging/install_owner_release.py b/apps/node-agent/packaging/install_owner_release.py index 7cf86b7e..cd39be8b 100644 --- a/apps/node-agent/packaging/install_owner_release.py +++ b/apps/node-agent/packaging/install_owner_release.py @@ -15,9 +15,16 @@ import uuid from datetime import UTC, datetime from pathlib import Path +if "CanMaintenance" not in globals(): + from can_maintenance import CanMaintenance + +NODE_DEPENDENCIES = ('timescaledb-2-loader-postgresql-16_2.29.2~ubuntu24.04-1615_amd64.deb', 'timescaledb-2-oss-postgresql-16_2.29.2~ubuntu24.04-1615_amd64.deb') + ROOT = Path("/var/tmp/mission-core-node-installs") SERVICES = ( "mission-core-node.service", + "mission-core-vesc.service", + "mission-core-usb-can.service", "mission-core-k1.service", "mission-core-realsense.service", ) @@ -150,6 +157,16 @@ def update_installed_x4(run): ) if installed == profile["version"]: return {"state": "current", "version": installed} + comparison = subprocess.run( + ["/usr/bin/dpkg", "--compare-versions", installed, "gt", profile["version"]], + capture_output=True, timeout=10, + ) + if comparison.returncode == 0: + # A Node-only feature update must preserve a separately qualified newer + # camera release. The model preparation workflow still rejects downgrades. + return {"state": "newer-installed-preserved", "version": installed} + if comparison.returncode != 1: + raise RuntimeError("Не удалось сравнить версии драйвера X4.") # The shipped profile verifies root-owned bytes, lifecycle quiescence and # dependency closure. It never requires a connected camera for package upgrade. run( @@ -205,7 +222,10 @@ def main(): ): raise ValueError("Unknown Node release") package = "mission-core-node_" + version + "_amd64.deb" - if set(manifest["files"]) != {package, "install", "install_release.py"}: + dependencies = manifest.get("dependencies", []) + if dependencies != list(NODE_DEPENDENCIES): + raise ValueError("Required Node dependencies are missing") + if set(manifest["files"]) != {package, "install", "install_release.py", *dependencies}: raise ValueError("Unexpected installer contents") contents = {} for name, expected in manifest["files"].items(): @@ -216,7 +236,9 @@ def main(): private(ROOT) folder = ROOT / uuid.uuid4().hex private(folder) - (folder / package).write_bytes(contents[package]) + for name in [*dependencies, package]: + (folder / name).write_bytes(contents[name]) + package_paths = [str(folder / name) for name in [*dependencies, package]] report = { "schema": "missioncore.node.install-run/v1", "session_id": folder.name, @@ -255,6 +277,7 @@ def main(): raise RuntimeError("Не завершён этап установки: " + name) return result.stdout.decode().strip() + maintenance = CanMaintenance(report.setdefault("can_maintenance", {})) publish() try: report["legacy_pager_recovery"] = finish_legacy_monitor_pager() @@ -277,8 +300,10 @@ def main(): # Its transaction is never killed by an observer timeout. run( "apt-plan", - ["/usr/bin/apt-get", "--simulate", "--no-remove", "install", str(folder / package)], + ["/usr/bin/apt-get", "--simulate", "--no-remove", "install", *package_paths], ) + maintenance.begin() + publish() run( "package", [ @@ -290,7 +315,7 @@ def main(): "install", "-y", "--no-remove", - str(folder / package), + *package_paths, ], timeout=None, ) @@ -306,6 +331,9 @@ def main(): "node-service", ["/usr/bin/systemctl", "is-active", "--quiet", "mission-core-node.service"], ) + run("wireguard-service", ["/usr/bin/systemctl", "is-active", "--quiet", "mission-core-node-wireguard.service"]) + run("wireguard-socket", ["/usr/bin/python3", "-I", "-c", + 'import socket,json; s=socket.socket(socket.AF_UNIX); s.settimeout(5); s.connect("/run/mission-core-wireguard/control.sock"); s.sendall(b\'{"action":"health"}\\n\'); r=json.loads(s.makefile("rb").readline(16385)); assert r.get("ok") is True and r["result"]["schema"]=="missioncore.wireguard-helper/v1"; print("WireGuard helper ready")']) deadline = time.monotonic() + 30 while True: client = http.client.HTTPConnection("127.0.0.1", 8780, timeout=2) @@ -341,6 +369,10 @@ def main(): except Exception as error: report.update(state="error", error=str(error)[:500]) finally: + try: + maintenance.finish() + except Exception as error: + report.update(state="error", error=str(error)[:500]) report.update( finished_at=datetime.now(UTC).isoformat(), duration_seconds=time.monotonic() - report["monotonic_started"], diff --git a/apps/node-agent/packaging/linux_build_entry.py b/apps/node-agent/packaging/linux_build_entry.py index 1b467426..daad91ab 100644 --- a/apps/node-agent/packaging/linux_build_entry.py +++ b/apps/node-agent/packaging/linux_build_entry.py @@ -5,12 +5,14 @@ import hashlib import json import os import platform +import re import shutil import subprocess import sys import time import zipfile from datetime import UTC, datetime +from contextlib import contextmanager from pathlib import Path, PurePosixPath ROOT = Path("/var/tmp/mission-core-node-builds") @@ -20,6 +22,39 @@ def digest(data): return hashlib.sha256(data).hexdigest() +@contextmanager +def source_archives(archive, manifest, root): + """Reuse immutable hash-verified input bytes, never a previous loose checkout.""" + names = set(manifest["files"]) + payload = manifest.get("payload_files", sorted(names)) + if not isinstance(payload, list) or len(payload) != len(set(payload)) or not set(payload) <= names: + raise ValueError("Invalid build payload list") + admitted = {"source.json", "__main__.py"} | {"source/" + name for name in payload} + if set(archive.namelist()) != admitted or len(archive.namelist()) != len(admitted): + raise ValueError("Unexpected source contents") + base = None + try: + if set(payload) != names: + spec = manifest.get("base", {}) + if set(spec) != {"name", "sha256"} or not re.fullmatch(r"mission-core-node-linux-build-[a-f0-9]{24}\.pyz", str(spec.get("name"))) or not re.fullmatch(r"[a-f0-9]{64}", str(spec.get("sha256"))): + raise ValueError("Invalid build baseline") + path = root / spec["name"] + if path.is_symlink() or not path.is_file() or path.stat().st_uid != os.geteuid() or path.stat().st_mode & 0o022: + raise ValueError("Untrusted build baseline") + with path.open("rb") as stream: + if hashlib.file_digest(stream, "sha256").hexdigest() != spec["sha256"]: + raise ValueError("Build baseline hash changed") + stream.seek(0) + base = zipfile.ZipFile(stream) + origins = {name: archive if name in payload else base for name in names} + yield origins + else: + yield {name: archive for name in names} + finally: + if base is not None: + base.close() + + def private(path): path.mkdir(mode=0o700, exist_ok=True) info = path.lstat() @@ -72,30 +107,27 @@ def main(): raise RuntimeError("Preserve prior failure evidence and use --clean before retry") if shutil.disk_usage(folder).free < 6 * 1024**3: raise RuntimeError("Build requires 6 GiB free temporary disk space") - admitted = {"source.json", "__main__.py"} | { - "source/" + name for name in manifest["files"] - } - if set(archive.namelist()) != admitted or len(archive.namelist()) != len(admitted): - raise ValueError("Unexpected source contents") - for name, expected in manifest["files"].items(): - path = PurePosixPath(name) - if ( - path.is_absolute() - or ".." in path.parts - or path.as_posix() != name - or "\\" in name - ): - raise ValueError("Unsafe source path") - entry = archive.getinfo("source/" + name) - if entry.file_size != expected["bytes"] or entry.file_size > 100 * 1024**2: - raise ValueError("Invalid source size") - data = archive.read(entry) - if digest(data) != expected["sha256"] or expected["mode"] not in (0o644, 0o755): - raise ValueError("Invalid source bytes or mode") - target = folder / "source" / name - target.parent.mkdir(mode=0o700, parents=True, exist_ok=True) - target.write_bytes(data) - target.chmod(expected["mode"]) + with source_archives(archive, manifest, ROOT) as origins: + for name, expected in manifest["files"].items(): + path = PurePosixPath(name) + if ( + path.is_absolute() + or ".." in path.parts + or path.as_posix() != name + or "\\" in name + ): + raise ValueError("Unsafe source path") + origin = origins[name] + entry = origin.getinfo("source/" + name) + if entry.file_size != expected["bytes"] or entry.file_size > 100 * 1024**2: + raise ValueError("Invalid source size") + data = origin.read(entry) + if digest(data) != expected["sha256"] or expected["mode"] not in (0o644, 0o755): + raise ValueError("Invalid source bytes or mode") + target = folder / "source" / name + target.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(expected["mode"]) (folder / "source.json").write_bytes(raw) report = { "schema": "missioncore.node.linux-build-run/v1", diff --git a/apps/node-agent/packaging/linux_build_job.py b/apps/node-agent/packaging/linux_build_job.py index b59c1074..9b43fb3a 100644 --- a/apps/node-agent/packaging/linux_build_job.py +++ b/apps/node-agent/packaging/linux_build_job.py @@ -140,10 +140,18 @@ def main(): def app_dependencies(app, name): lock = json.loads((app / "package-lock.json").read_text()) - for value in lock["packages"].values(): + # Existing Omniverse integration uses NVIDIA's official registry. + # Admit only its already locked artifact, never a whole extra registry. + vendor_pin = ( + "node_modules/@nvidia/ov-web-rtc", + "https://edge.urm.nvidia.com/artifactory/api/npm/omniverse-client-npm/@nvidia/ov-web-rtc/-/@nvidia/ov-web-rtc-6.7.0.tgz", + "sha512-Knt393yvuI1tFmQgJM7VuMlVKDh5GyuKq8fAIarNLyY7Ucxw+lSY/72ceWR+3HyCnNtL39J0DZ27dn9riqpGWw==", + ) + for package_name, value in lock["packages"].items(): resolved = value.get("resolved", "") if "://" in resolved and not resolved.startswith("https://registry.npmjs.org/"): - raise ValueError("An npm dependency is outside the locked public registry") + if (package_name, resolved, value.get("integrity")) != vendor_pin: + raise ValueError("An npm dependency is outside the locked registry pins") command = [ str(nodejs), str(npm), @@ -161,7 +169,10 @@ def main(): for attempt in range(1, 4): step = name + "-dependencies-" + str(attempt) try: - run(step, command, cwd=app, timeout=45) + # Large locked Cesium archives can still be making progress after + # 45 s on a slow uplink. Keep retries and the outer cgroup + # deadline bounded without killing each valid download early. + run(step, command, cwd=app, timeout=180) break except subprocess.TimeoutExpired: # npm can stall after a TLS download without surfacing its @@ -199,6 +210,8 @@ def main(): [str(nodejs), str(npm), "run", "test:activity-indicator"], cwd=dg, ) + run("design-guideline-dock-tests", [str(nodejs), str(npm), "run", "test:dock-layout"], cwd=dg) + run("design-guideline-settings-tests", [str(nodejs), str(npm), "run", "test:settings-surfaces"], cwd=dg) run( "design-guideline-catalog", [str(nodejs), str(npm), "run", "build", "--workspace", "@nodedc/ui-catalog"], @@ -230,6 +243,11 @@ def main(): str(go.parent / "gofmt"), "-d", *[str(path) for path in sorted((node / "internal/node").glob("pairing*.go"))], + *[str(node / "internal/node" / name) for name in ( + "link_budget.go", "link_budget_test.go", "rover_channel.go", + "rover_local_delivery.go", "rover_local_delivery_test.go", "rover_diagnostics.go", + "rover_diagnostics_lane.go", "rover_link.go", "rover_stream_state.go", "server.go")], + str(node / "cmd/node-agent/main.go"), ], cwd=node, ) @@ -243,10 +261,18 @@ def main(): sys.path.insert(0, str(node / "packaging")) from build_deb import BINARY_VERSION, VERSION, build - run("node-environment-tests", ["/usr/bin/python3", "-m", "unittest", "test_environment_helper", "test_usb_startup_recovery", "test_desktop_startup", "-v"], cwd=node / "packaging") + run("node-environment-tests", ["/usr/bin/python3", "-m", "unittest", "test_environment_helper", "test_wifi_latency_trial", "test_usb_startup_recovery", "test_desktop_startup", "test_install_owner_release", "test_can_maintenance", "test_vesc_hall_recovery", "test_owner_dependencies", "test_build_source_reuse", "-v"], cwd=node / "packaging") run("owner-release-staging-tests", ["/usr/bin/python3", "plugins/insta360-x4/packaging/test_owner_release_entry.py"], cwd=repo) - run("node-usb-unit-validation", ["/usr/bin/systemd-analyze", "verify", str(node / "packaging/mission-core-node-usb-startup.service")], cwd=node) + run("node-usb-unit-validation", ["/usr/bin/systemd-analyze", "verify", str(node / "packaging/mission-core-node-usb-startup.service"), str(node / "packaging/mission-core-node-wifi-trial.service")], cwd=node) run("vesc-reader-tests", ["/usr/bin/python3", "-m", "unittest", "discover", "-s", "plugins/vesc/tests", "-v"], cwd=repo) + run("usb-can-native-abi", ["/usr/bin/python3", "-B", "-c", + "from runtime.sdk import library; library('build/sdk/libcontrolcanfd.so'); print('Pinned SDK loaded; no USB open')"], + cwd=repo / "plugins/usb-can") + run("usb-can-unit-validation", ["/usr/bin/systemd-analyze", "verify", + str(repo / "plugins/usb-can/packaging/mission-core-usb-can.service"), + str(repo / "plugins/usb-can/packaging/mission-core-node-usb-can-prepare.service")], cwd=repo) + run("usb-can-sdk-custom-baud-inspection", ["/usr/bin/objdump", "-d", "--disassemble=ZCAN_SetBaudRateCustom", + str(repo / "plugins/usb-can/build/sdk/libcontrolcanfd.so")], cwd=repo) binary = node / "build/node-agent-linux-amd64" run( "node-binary", @@ -264,6 +290,15 @@ def main(): cwd=node, overrides={"CGO_ENABLED": "0", "GOOS": "linux", "GOARCH": "amd64"}, ) + dependency_root = temporary / "monitor-dependencies" + run("node-monitor-dependencies", ["/usr/bin/python3", str(node / "packaging/fetch_monitor_dependencies.py"), str(dependency_root)], timeout=180) + dependency_manifest = json.loads((dependency_root / "manifest.json").read_text()) + dependency_paths = [] + for dependency in dependency_manifest["artifacts"]: + target = output / dependency["file"] + shutil.copyfile(dependency_root / dependency["file"], target) + dependency_paths.append(target) + shutil.copyfile(dependency_root / "manifest.json", output / "monitor-dependencies.json") provenance = { "schema": "missioncore.node.source-provenance/v1", "version": VERSION, @@ -287,15 +322,21 @@ def main(): memory_peak_bytes=int((control / "memory.peak").read_text()), ) report["artifacts"] = { - package.name: { - "bytes": package.stat().st_size, - "sha256": hashlib.sha256(package.read_bytes()).hexdigest(), - } + path.name: {"bytes": path.stat().st_size, + "sha256": hashlib.sha256(path.read_bytes()).hexdigest()} + for path in [package, *dependency_paths, output / "monitor-dependencies.json"] } publish() return core = repo / "apps/control-station" app_dependencies(core, "core") + # npm lifecycle scripts stay disabled for dependencies. Apply the + # repository-owned, hash-checked native viewer before ABI tests. + run( + "core-native-navigation", + [str(nodejs), "scripts/install-rerun-navigation.mjs"], + cwd=core, + ) run( "core-architecture", [str(nodejs), "--test", "test/applicationArchitecture.test.mjs"], @@ -346,7 +387,7 @@ def main(): "bytes": path.stat().st_size, "sha256": hashlib.sha256(path.read_bytes()).hexdigest(), } - for path in (package, output / "core-dist.tar.gz") + for path in (package, output / "core-dist.tar.gz", *dependency_paths, output / "monitor-dependencies.json") } publish() except Exception: diff --git a/apps/node-agent/packaging/mission-core-node-wifi-trial.service b/apps/node-agent/packaging/mission-core-node-wifi-trial.service new file mode 100644 index 00000000..a6874f8c --- /dev/null +++ b/apps/node-agent/packaging/mission-core-node-wifi-trial.service @@ -0,0 +1,13 @@ +[Unit] +Description=Mission Core bounded Wi-Fi power-save qualification with restoration +After=NetworkManager.service mission-core-vesc.service + +[Service] +Type=oneshot +ExecStart=/usr/bin/python3 -I -B /usr/lib/mission-core-node/wifi_latency_trial.py --trial +ExecStopPost=/usr/bin/python3 -I -B /usr/lib/mission-core-node/wifi_latency_trial.py --restore +Environment=PATH=/usr/sbin:/usr/bin:/sbin:/bin +Environment=LANG=C.UTF-8 +UMask=0077 +TimeoutStartSec=210 +TimeoutStopSec=30 diff --git a/apps/node-agent/packaging/mission-core-node-wireguard.service b/apps/node-agent/packaging/mission-core-node-wireguard.service new file mode 100644 index 00000000..6251a121 --- /dev/null +++ b/apps/node-agent/packaging/mission-core-node-wireguard.service @@ -0,0 +1,27 @@ +[Unit] +Description=Mission Core board WireGuard configuration +After=network-online.target +Wants=network-online.target +Before=mission-core-node.service + +[Service] +Type=simple +ExecStart=/usr/bin/python3 -I /usr/lib/mission-core-node/wireguard_helper.py +Restart=on-failure +RestartSec=3 +StateDirectory=mission-core-wireguard +StateDirectoryMode=0700 +RuntimeDirectory=mission-core-wireguard +RuntimeDirectoryMode=0755 +UMask=0077 +NoNewPrivileges=yes +ProtectSystem=strict +ProtectHome=yes +PrivateTmp=yes +RestrictAddressFamilies=AF_UNIX AF_INET AF_NETLINK +CapabilityBoundingSet=CAP_NET_ADMIN CAP_CHOWN CAP_DAC_OVERRIDE +MemoryMax=64M +TasksMax=16 + +[Install] +WantedBy=multi-user.target diff --git a/apps/node-agent/packaging/mission-core-node.service b/apps/node-agent/packaging/mission-core-node.service index 0180123b..fa4ddfcc 100644 --- a/apps/node-agent/packaging/mission-core-node.service +++ b/apps/node-agent/packaging/mission-core-node.service @@ -10,7 +10,7 @@ ExecStart=/usr/lib/mission-core-node/node-agent StateDirectory=mission-core-node StateDirectoryMode=0700 RuntimeDirectory=mission-core-node -RuntimeDirectoryMode=0700 +RuntimeDirectoryMode=0750 UMask=0077 Restart=on-failure RestartSec=3 diff --git a/apps/node-agent/packaging/postinst b/apps/node-agent/packaging/postinst index c0975e97..45e1546a 100644 --- a/apps/node-agent/packaging/postinst +++ b/apps/node-agent/packaging/postinst @@ -13,8 +13,11 @@ case "$1" in # versioned job started by «Настройка окружения → Сконфигурировать». if [ -d /run/systemd/system ]; then systemctl daemon-reload + systemctl enable mission-core-node-wireguard.service + systemctl restart mission-core-node-wireguard.service systemctl enable mission-core-node.service systemctl restart mission-core-node.service + systemctl start mission-core-node-usb-can-prepare.service systemctl try-restart mission-core-realsense.service if [ -f /var/lib/mission-core-node-profiles/vesc/preparation.json ]; then systemctl start mission-core-node-vesc-prepare.service diff --git a/apps/node-agent/packaging/preinst b/apps/node-agent/packaging/preinst index 541aad91..39e5c2b6 100644 --- a/apps/node-agent/packaging/preinst +++ b/apps/node-agent/packaging/preinst @@ -2,6 +2,13 @@ set -eu if [ "$1" = install ] || [ "$1" = upgrade ]; then if [ -d /run/systemd/system ]; then + if [ -S /run/mission-core-usb-can/driver.sock ]; then + if ! /usr/bin/python3 -I -c 'import http.client,json,socket; c=http.client.HTTPConnection("usb-can",timeout=5); c.sock=socket.socket(socket.AF_UNIX); c.sock.settimeout(5); c.sock.connect("/run/mission-core-usb-can/driver.sock"); c.request("GET","/prepare-safe"); r=c.getresponse(); assert r.status==200 and json.load(r).get("safe") is True'; then + echo "Mission Core Node: остановите CAN-каналы перед обновлением или удалением." >&2 + exit 1 + fi + systemctl stop mission-core-usb-can.service + fi if [ -S /run/mission-core-sensors/driver.sock ]; then if ! /usr/bin/python3 -I -c 'import http.client,json,socket; c=http.client.HTTPConnection("driver",timeout=5); c.sock=socket.socket(socket.AF_UNIX); c.sock.settimeout(5); c.sock.connect("/run/mission-core-sensors/driver.sock"); c.request("GET","/prepare-safe"); r=c.getresponse(); assert r.status==200 and json.load(r).get("safe") is True'; then echo "Mission Core Node: остановите захват или просмотр записи перед обновлением или удалением." >&2 diff --git a/apps/node-agent/packaging/prerm b/apps/node-agent/packaging/prerm index 754ea7dc..977648d4 100644 --- a/apps/node-agent/packaging/prerm +++ b/apps/node-agent/packaging/prerm @@ -1,6 +1,13 @@ #!/bin/sh set -eu if [ -d /run/systemd/system ]; then + if [ -S /run/mission-core-usb-can/driver.sock ]; then + if ! /usr/bin/python3 -I -c 'import http.client,json,socket; c=http.client.HTTPConnection("usb-can",timeout=5); c.sock=socket.socket(socket.AF_UNIX); c.sock.settimeout(5); c.sock.connect("/run/mission-core-usb-can/driver.sock"); c.request("GET","/prepare-safe"); r=c.getresponse(); assert r.status==200 and json.load(r).get("safe") is True'; then + echo "Mission Core Node: остановите CAN-каналы перед обновлением или удалением." >&2 + exit 1 + fi + systemctl stop mission-core-usb-can.service + fi if [ -S /run/mission-core-sensors/driver.sock ]; then if ! /usr/bin/python3 -I -c 'import http.client,json,socket; c=http.client.HTTPConnection("driver",timeout=5); c.sock=socket.socket(socket.AF_UNIX); c.sock.settimeout(5); c.sock.connect("/run/mission-core-sensors/driver.sock"); c.request("GET","/prepare-safe"); r=c.getresponse(); assert r.status==200 and json.load(r).get("safe") is True'; then echo "Mission Core Node: остановите захват или просмотр записи перед обновлением или удалением." >&2 @@ -106,3 +113,21 @@ case "$1" in fi ;; esac + +# Retire only this profile on removal or rollback to a release without it. +if [ "$1" = remove ] || { [ "$1" = upgrade ] && [ -n "${2:-}" ] && dpkg --compare-versions "$2" lt 0.8.49-33; }; then + if [ -d /run/systemd/system ]; then + systemctl disable --now mission-core-usb-can.service || true + fi + mc_can_rule=/etc/udev/rules.d/70-mission-core-usb-can.rules + if [ ! -L "$mc_can_rule" ] && cmp -s /usr/share/mission-core-node/profiles/usb-can/70-mission-core-usb-can.rules "$mc_can_rule"; then + rm "$mc_can_rule" + fi +fi + +# This version owns only its WireGuard helper. Keep private identity for reinstall. +if [ "$1" = remove ] || { [ "$1" = upgrade ] && [ -n "${2:-}" ] && dpkg --compare-versions "$2" lt 0.8.49-91; }; then + if [ -d /run/systemd/system ]; then + systemctl disable --now mission-core-node-wireguard.service || true + fi +fi diff --git a/apps/node-agent/packaging/repack_codec_recovery.py b/apps/node-agent/packaging/repack_codec_recovery.py new file mode 100644 index 00000000..0261d53f --- /dev/null +++ b/apps/node-agent/packaging/repack_codec_recovery.py @@ -0,0 +1,133 @@ +"""Node93: package the qualified codec-recovery fix and X4-29, preserving binaries. + +Exact qualified Node92 base; no compilation or system installation. The X4 package +must independently pass its Ubuntu cold-import, codec and transport checks. +""" +import argparse +import hashlib +import io +import json +import shutil +import sys +import tarfile +from pathlib import Path + +BASE = 'c84d7019be956e2420cdd21d690069d7e16db9486d8834f2e056993f97c12e9c' +VERSION = '0.8.49-93' +MODEL_ROOT = 'usr/share/mission-core-node/profiles/insta360-x4/' +SDK_PATH = 'usr/lib/mission-core-node/sdk/missioncore_plugin_sdk/codec_recovery.py' +PROOF = 'usr/share/doc/mission-core-node/codec-recovery-packaging-revision.json' +REPO = Path(__file__).resolve().parents[3] + + +def digest(data): + return hashlib.sha256(data).hexdigest() + + +def members(raw): + if raw[:8] != b'!\n': + raise ValueError('Invalid Debian archive') + entries, cursor = {}, 8 + while cursor < len(raw): + h = raw[cursor:cursor + 60] + name, size = h[:16].decode().strip().rstrip('/'), int(h[48:58]) + if h[58:] != b'`\n' or name in entries: + raise ValueError('Invalid ar member') + entries[name] = raw[cursor + 60:cursor + 60 + size] + cursor += 60 + size + size % 2 + if set(entries) != {'debian-binary', 'control.tar.gz', 'data.tar.gz'}: + raise ValueError('Unexpected Debian contents') + result = {} + for name in ('control.tar.gz', 'data.tar.gz'): + result[name] = [] + with tarfile.open(fileobj=io.BytesIO(entries[name]), mode='r:gz') as archive: + for m in archive: + if m.isdir(): + continue + if not m.isfile() or m.uid or m.gid: + raise ValueError('Unexpected package member') + result[name].append((m.name, archive.extractfile(m).read(), m.mode)) + return result['control.tar.gz'], result['data.tar.gz'] + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--qualified', required=True, type=Path) + parser.add_argument('--model', required=True, type=Path) + parser.add_argument('--output', required=True, type=Path) + args = parser.parse_args() + evidence = json.loads((args.qualified / 'qualification.json').read_text()) + if evidence['state'] != 'complete' or any(j['state'] != 'complete' for j in evidence['jobs']): + raise ValueError('Completed base qualification required') + raw = (args.qualified / 'mission-core-node_0.8.49-92_amd64.deb').read_bytes() + if digest(raw) != BASE: + raise ValueError('Qualified base changed') + controls, data = members(raw) + old = {name: value for name, value, _ in data} + fixed = (REPO / 'packages/plugin-sdk/python/missioncore_plugin_sdk/codec_recovery.py').read_bytes() + # The SDK delta is exactly completion of one sustained recovery window. + old_tail = b' return floor if now - started >= 2 else applied\n' + new_tail = b''' if now - started >= 2: + # This sustained floor completes one upgrade. A later, higher + # request must earn its own window instead of inheriting this floor + # forever after the encoder applies it. + self.pending = None + return floor + return applied +''' + if old[SDK_PATH].count(old_tail) != 1 or fixed != old[SDK_PATH].replace(old_tail, new_tail): + raise ValueError('Codec repair differs from the reviewed delta') + model = json.loads((args.model / 'package-result.json').read_text()) + checks = json.loads((args.model / 'build-report.json').read_text()) + if model['version'] != '0.1.3-29' or checks['state'] != 'complete': + raise ValueError('Qualified X4-29 required') + model_name = 'mission-core-insta360-x4_0.1.3-29_amd64.deb' + model_bytes = (args.model / model_name).read_bytes() + if digest(model_bytes) != model['sha256'] or len(model_bytes) != model['bytes']: + raise ValueError('Qualified model package changed') + old_model = MODEL_ROOT + 'mission-core-insta360-x4_0.1.3-28_amd64.deb' + prior = json.loads(old[MODEL_ROOT + 'profile.json']) + if prior['version'] != '0.1.3-28' or digest(old[old_model]) != prior['sha256']: + raise ValueError('Unexpected previous camera bundle') + profile = {**prior, **{k: model[k] for k in ('version', 'revision', 'bytes', 'sha256')}} + changes = {SDK_PATH: fixed, MODEL_ROOT + 'profile.json': (json.dumps(profile, indent=2) + '\n').encode()} + control = next(v for n, v, _ in controls if n == 'control') + if control.count(b'Version: 0.8.49-92\n') != 1 or PROOF in old: + raise ValueError('Unexpected base version/proof') + controls = [(n, v.replace(b'Version: 0.8.49-92\n', b'Version: 0.8.49-93\n') if n == 'control' else v, m) for n, v, m in controls] + proof = {'schema': 'missioncore.node.packaging-revision/v1', 'version': VERSION, + 'qualified_base_sha256': BASE, 'compiled_node_ui_and_network_configuration_unchanged': True, + 'changed_files': list(changes) + [old_model, MODEL_ROOT + model_name, PROOF], + 'codec_sha256': digest(fixed), 'model': profile, + 'model_qualification_sha256': digest((args.model / 'build-report.json').read_bytes()), + 'base_qualification_sha256': digest((args.qualified / 'qualification.json').read_bytes()), + 'repack_source_sha256': digest(Path(__file__).read_bytes())} + data = [(n, changes.get(n, v), m) for n, v, m in data if n != old_model] + data.extend([(MODEL_ROOT + model_name, model_bytes, 0o644), + (PROOF, (json.dumps(proof, sort_keys=True) + '\n').encode(), 0o644)]) + sys.path.insert(0, str(REPO / 'scripts/packaging')) + from debian import package + args.output.mkdir(mode=0o700) + target = args.output / ('mission-core-node_' + VERSION + '_amd64.deb') + result = package(controls, data) + new_controls, new_data = members(result) + if new_controls != controls or new_data != sorted(data): + raise ValueError('Packaged contents differ from the admitted delta') + target.write_bytes(result) + artifacts = {target.name: {'bytes': len(result), 'sha256': digest(result)}} + for name, info in evidence['artifacts'].items(): + if name.startswith('mission-core-node_'): + continue + content = (args.qualified / name).read_bytes() + if digest(content) != info['sha256'] or len(content) != info['bytes']: + raise ValueError('Dependency changed') + shutil.copyfile(args.qualified / name, args.output / name) + artifacts[name] = info + evidence.update(artifacts=artifacts, packaging_revision=proof) + evidence['jobs'].append({'id': 'codec-recovery-and-qualified-x4-bundle', 'state': 'complete', 'exit_code': 0}) + (args.output / 'qualification.json').write_text(json.dumps(evidence, indent=2) + '\n') + print(json.dumps({'directory': str(args.output), 'artifacts': artifacts})) + + +if __name__ == '__main__': + main() diff --git a/apps/node-agent/packaging/repack_preview_cost.py b/apps/node-agent/packaging/repack_preview_cost.py new file mode 100644 index 00000000..0ba51b90 --- /dev/null +++ b/apps/node-agent/packaging/repack_preview_cost.py @@ -0,0 +1,130 @@ +"""Node94: package the qualified low-cost preview encoder and X4-30, preserving binaries. + +Exact qualified Node93 base; no compilation or system installation. The X4 package +must independently pass its Ubuntu cold-import, codec and transport checks. +""" +import argparse +import hashlib +import io +import json +import shutil +import sys +import tarfile +from pathlib import Path + +BASE = 'c6b8654515b1c8dd4b7700f96fce2e8afec105ab8f6415fd4adf2a7b760c8314' +VERSION = '0.8.49-94' +MODEL_ROOT = 'usr/share/mission-core-node/profiles/insta360-x4/' +SDK_PATH = 'usr/lib/mission-core-node/sdk/missioncore_plugin_sdk/preview_h264.py' +PROOF = 'usr/share/doc/mission-core-node/preview-cost-packaging-revision.json' +REPO = Path(__file__).resolve().parents[3] + + +def digest(data): + return hashlib.sha256(data).hexdigest() + + +def members(raw): + if raw[:8] != b'!\n': + raise ValueError('Invalid Debian archive') + entries, cursor = {}, 8 + while cursor < len(raw): + h = raw[cursor:cursor + 60] + name, size = h[:16].decode().strip().rstrip('/'), int(h[48:58]) + if h[58:] != b'`\n' or name in entries: + raise ValueError('Invalid ar member') + entries[name] = raw[cursor + 60:cursor + 60 + size] + cursor += 60 + size + size % 2 + if set(entries) != {'debian-binary', 'control.tar.gz', 'data.tar.gz'}: + raise ValueError('Unexpected Debian contents') + result = {} + for name in ('control.tar.gz', 'data.tar.gz'): + result[name] = [] + with tarfile.open(fileobj=io.BytesIO(entries[name]), mode='r:gz') as archive: + for m in archive: + if m.isdir(): + continue + if not m.isfile() or m.uid or m.gid: + raise ValueError('Unexpected package member') + result[name].append((m.name, archive.extractfile(m).read(), m.mode)) + return result['control.tar.gz'], result['data.tar.gz'] + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--qualified', required=True, type=Path) + parser.add_argument('--model', required=True, type=Path) + parser.add_argument('--output', required=True, type=Path) + args = parser.parse_args() + evidence = json.loads((args.qualified / 'qualification.json').read_text()) + if evidence['state'] != 'complete' or any(j['state'] != 'complete' for j in evidence['jobs']): + raise ValueError('Completed base qualification required') + raw = (args.qualified / 'mission-core-node_0.8.49-93_amd64.deb').read_bytes() + if digest(raw) != BASE: + raise ValueError('Qualified base changed') + controls, data = members(raw) + old = {name: value for name, value, _ in data} + fixed = (REPO / 'packages/plugin-sdk/python/missioncore_plugin_sdk/preview_h264.py').read_bytes() + # Admit only the measured preset/thread delta; preserve pacing/VBV/recovery. + old_threads = b' codec.bit_rate, codec.pix_fmt = rate, "yuv420p"\n' + new_threads = old_threads + b' # Bounded sliced encoding leaves CPU for capture, control and other sensors.\n codec.thread_count = 2\n' + old_options = b'"level": "31", "tune": "zerolatency",' + new_options = b'"level": "31", "tune": "zerolatency", "preset": "veryfast",' + if old[SDK_PATH].count(old_threads) != 1 or old[SDK_PATH].count(old_options) != 1: + raise ValueError('Unexpected preview encoder base') + if fixed != old[SDK_PATH].replace(old_threads, new_threads).replace(old_options, new_options): + raise ValueError('Preview cost repair differs from the reviewed delta') + model = json.loads((args.model / 'package-result.json').read_text()) + checks = json.loads((args.model / 'build-report.json').read_text()) + if model['version'] != '0.1.3-30' or checks['state'] != 'complete': + raise ValueError('Qualified X4-30 required') + model_name = 'mission-core-insta360-x4_0.1.3-30_amd64.deb' + model_bytes = (args.model / model_name).read_bytes() + if digest(model_bytes) != model['sha256'] or len(model_bytes) != model['bytes']: + raise ValueError('Qualified model package changed') + old_model = MODEL_ROOT + 'mission-core-insta360-x4_0.1.3-29_amd64.deb' + prior = json.loads(old[MODEL_ROOT + 'profile.json']) + if prior['version'] != '0.1.3-29' or digest(old[old_model]) != prior['sha256']: + raise ValueError('Unexpected previous camera bundle') + profile = {**prior, **{k: model[k] for k in ('version', 'revision', 'bytes', 'sha256')}} + changes = {SDK_PATH: fixed, MODEL_ROOT + 'profile.json': (json.dumps(profile, indent=2) + '\n').encode()} + control = next(v for n, v, _ in controls if n == 'control') + if control.count(b'Version: 0.8.49-93\n') != 1 or PROOF in old: + raise ValueError('Unexpected base version/proof') + controls = [(n, v.replace(b'Version: 0.8.49-93\n', b'Version: 0.8.49-94\n') if n == 'control' else v, m) for n, v, m in controls] + proof = {'schema': 'missioncore.node.packaging-revision/v1', 'version': VERSION, + 'qualified_base_sha256': BASE, 'compiled_node_ui_and_network_configuration_unchanged': True, + 'changed_files': list(changes) + [old_model, MODEL_ROOT + model_name, PROOF], + 'codec_sha256': digest(fixed), 'model': profile, + 'model_qualification_sha256': digest((args.model / 'build-report.json').read_bytes()), + 'base_qualification_sha256': digest((args.qualified / 'qualification.json').read_bytes()), + 'repack_source_sha256': digest(Path(__file__).read_bytes())} + data = [(n, changes.get(n, v), m) for n, v, m in data if n != old_model] + data.extend([(MODEL_ROOT + model_name, model_bytes, 0o644), + (PROOF, (json.dumps(proof, sort_keys=True) + '\n').encode(), 0o644)]) + sys.path.insert(0, str(REPO / 'scripts/packaging')) + from debian import package + args.output.mkdir(mode=0o700) + target = args.output / ('mission-core-node_' + VERSION + '_amd64.deb') + result = package(controls, data) + new_controls, new_data = members(result) + if new_controls != controls or new_data != sorted(data): + raise ValueError('Packaged contents differ from the admitted delta') + target.write_bytes(result) + artifacts = {target.name: {'bytes': len(result), 'sha256': digest(result)}} + for name, info in evidence['artifacts'].items(): + if name.startswith('mission-core-node_'): + continue + content = (args.qualified / name).read_bytes() + if digest(content) != info['sha256'] or len(content) != info['bytes']: + raise ValueError('Dependency changed') + shutil.copyfile(args.qualified / name, args.output / name) + artifacts[name] = info + evidence.update(artifacts=artifacts, packaging_revision=proof) + evidence['jobs'].append({'id': 'preview-cost-and-qualified-x4-bundle', 'state': 'complete', 'exit_code': 0}) + (args.output / 'qualification.json').write_text(json.dumps(evidence, indent=2) + '\n') + print(json.dumps({'directory': str(args.output), 'artifacts': artifacts})) + + +if __name__ == '__main__': + main() diff --git a/apps/node-agent/packaging/repack_wireguard_helper.py b/apps/node-agent/packaging/repack_wireguard_helper.py new file mode 100644 index 00000000..f3c4331b --- /dev/null +++ b/apps/node-agent/packaging/repack_wireguard_helper.py @@ -0,0 +1,75 @@ +"""Node92 packaging-only repair of the qualified Node91 helper socket ownership. + +Exact base digest; compiled Node/UI/model bytes retained. No system installation. +""" +import argparse +import hashlib +import io +import json +import shutil +import subprocess +import sys +import tarfile +import time +from pathlib import Path + +BASE='f5f5d2f06d4ae0fed6853d0f5d25db3b7e4910ce6c1c80d2c42b6103d4e0e111' +TARGET='usr/lib/mission-core-node/wireguard_helper.py' +PROOF='usr/share/doc/mission-core-node/wireguard-packaging-revision.json' +VERSION='0.8.49-92' + +def digest(data):return hashlib.sha256(data).hexdigest() +def main(): + parser=argparse.ArgumentParser();parser.add_argument('--qualified',type=Path,required=True);parser.add_argument('--output',type=Path,required=True);parser.add_argument('--payload',type=Path,required=True) + args=parser.parse_args();base=args.qualified;out=args.output + evidence=json.loads((base/'qualification.json').read_text()) + if evidence.get('state')!='complete' or any(j['state']!='complete' for j in evidence['jobs']):raise ValueError('Qualified base required') + raw=(base/'mission-core-node_0.8.49-91_amd64.deb').read_bytes() + if digest(raw)!=BASE or raw[:8]!=b'!\n':raise ValueError('Qualified base changed') + entries={};cursor=8 + while cursor