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.
This commit is contained in:
@@ -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;
|
||||
}
|
||||
});
|
||||
|
||||
@@ -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"))},
|
||||
|
||||
@@ -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 <noreply@example.invalid>
|
||||
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)
|
||||
|
||||
@@ -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)))
|
||||
|
||||
@@ -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()}
|
||||
|
||||
@@ -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))
|
||||
@@ -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
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
|
||||
@@ -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"],
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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'!<arch>\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()
|
||||
@@ -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'!<arch>\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()
|
||||
@@ -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'!<arch>\n':raise ValueError('Qualified base changed')
|
||||
entries={};cursor=8
|
||||
while cursor<len(raw):
|
||||
h=raw[cursor:cursor+60];name=h[:16].decode().strip().rstrip('/');size=int(h[48:58])
|
||||
if h[58:]!=b'`\n' or name in entries:raise ValueError('Invalid ar')
|
||||
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('Invalid Debian contents')
|
||||
def files(name):
|
||||
result=[]
|
||||
with tarfile.open(fileobj=io.BytesIO(entries[name]),mode='r:gz') as ar:
|
||||
for m in ar.getmembers():
|
||||
if m.isdir():continue
|
||||
if not m.isfile() or m.uid or m.gid:raise ValueError('Unexpected member')
|
||||
result.append((m.name,ar.extractfile(m).read(),m.mode))
|
||||
return result
|
||||
controls,data=files('control.tar.gz'),files('data.tar.gz')
|
||||
old=next(v for n,v,m in data if n==TARGET)
|
||||
new=(args.payload/'helper.py').read_bytes()
|
||||
# This release admits exactly the ownership-order repair, no hidden code changes.
|
||||
expected=old.replace(b' os.chown(SOCKET, owner["uid"], owner["gid"])\n os.chmod(SOCKET, 0o600)',b' secure_socket(SOCKET, owner["uid"], owner["gid"])')
|
||||
expected=expected.replace(b'\ndef main():',b'\ndef secure_socket(path, uid, gid):\n # With CAP_CHOWN but no CAP_FOWNER, chmod must precede ownership transfer.\n os.chmod(path, 0o600)\n os.chown(path, uid, gid)\n\n\ndef main():')
|
||||
if new!=expected or old==new:raise ValueError('Repair differs from reviewed delta')
|
||||
started=time.monotonic()
|
||||
subprocess.run([sys.executable,'-B',str(args.payload/'test_helper.py')],check=True,timeout=20)
|
||||
control=next(v for n,v,m in controls if n=='control')
|
||||
if control.count(b'Version: 0.8.49-91\n')!=1:raise ValueError('Wrong base version')
|
||||
controls=[(n,v.replace(b'Version: 0.8.49-91\n',b'Version: 0.8.49-92\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,'changed_files':[TARGET],
|
||||
'binary_ui_and_model_packages_unchanged':True,'helper_sha256':digest(new),'repair_source_sha256':digest(Path(__file__).read_bytes()),
|
||||
'qualification_base_sha256':digest((base/'qualification.json').read_bytes())}
|
||||
data=[(n,new if n==TARGET else v,m) for n,v,m in data]
|
||||
if any(n==PROOF for n,v,m in data):raise ValueError('Proof already present')
|
||||
data.append((PROOF,(json.dumps(proof,sort_keys=True)+'\n').encode(),0o644))
|
||||
sys.path.insert(0,str(args.payload))
|
||||
from debian import package
|
||||
out.mkdir(mode=0o700)
|
||||
target=out/('mission-core-node_'+VERSION+'_amd64.deb');target.write_bytes(package(controls,data))
|
||||
artifacts={target.name:{'bytes':target.stat().st_size,'sha256':digest(target.read_bytes())}}
|
||||
for n,info in evidence['artifacts'].items():
|
||||
if n.startswith('mission-core-node_'):continue
|
||||
content=(base/n).read_bytes()
|
||||
if digest(content)!=info['sha256'] or len(content)!=info['bytes']:raise ValueError('Dependency changed')
|
||||
shutil.copyfile(base/n,out/n);artifacts[n]=info
|
||||
evidence.update(artifacts=artifacts,packaging_revision=proof)
|
||||
evidence['jobs'].append({'id':'wireguard-socket-ownership-repair','state':'complete','exit_code':0,'duration_seconds':time.monotonic()-started})
|
||||
(out/'qualification.json').write_text(json.dumps(evidence,indent=2)+'\n')
|
||||
print(json.dumps({'directory':str(out),'artifacts':artifacts}))
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,153 @@
|
||||
"""Finish one pinned Node72 build after its bounded dependency-fetch timeout.
|
||||
|
||||
Reuses only the verified source checkpoint and race-tested ELF. No system
|
||||
installation, Go/UI rebuild, source edit, camera access or motor command.
|
||||
"""
|
||||
import fcntl
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import platform
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
|
||||
IDENTIFIER = '40184248400d5f481872b230'
|
||||
SOURCE_HASH = '40184248400d5f481872b230ef7fb6ed2278b632e70230e94d775162a7dec78f'
|
||||
REPORT_HASH = '75d12d135258dbe20cd13e3d95c0720e5b82c2e3cd96ac914925e2050f1ced3e'
|
||||
BUILD_HASH = 'df3aa65920f993e3941a810263bb219e78dc6cb93e546667babbcfc956e4098d'
|
||||
BINARY_HASH = 'ef19319165eff8a3fec130427725b4c0310352acca8f3f26fed3c5a6fc6081e5'
|
||||
FOLDER = Path('/var/tmp/mission-core-node-builds') / IDENTIFIER
|
||||
REQUIRED = {'go-version', 'node-version', 'design-guideline-build',
|
||||
'design-guideline-typecheck', 'design-guideline-registry',
|
||||
'design-guideline-loading-tests', 'design-guideline-dock-tests',
|
||||
'design-guideline-settings-tests', 'design-guideline-catalog',
|
||||
'node-ui-tests', 'node-ui-build', 'node-go-format-diff', 'node-go-tests',
|
||||
'node-environment-tests', 'owner-release-staging-tests',
|
||||
'node-usb-unit-validation', 'vesc-reader-tests', 'usb-can-native-abi',
|
||||
'usb-can-unit-validation', 'usb-can-sdk-custom-baud-inspection', 'node-binary'}
|
||||
|
||||
|
||||
def digest(path):
|
||||
with path.open('rb') as stream:
|
||||
return hashlib.file_digest(stream, 'sha256').hexdigest()
|
||||
|
||||
|
||||
def validate_checkpoint(folder):
|
||||
for name, expected in [('source.json', SOURCE_HASH),
|
||||
('output/qualification.json', REPORT_HASH),
|
||||
('report.json', BUILD_HASH)]:
|
||||
if digest(folder/name) != expected:
|
||||
raise ValueError('Pinned checkpoint changed: '+name)
|
||||
manifest = json.loads((folder/'source.json').read_text())
|
||||
report = json.loads((folder/'output/qualification.json').read_text())
|
||||
completed = {j['id'] for j in report['jobs'] if j.get('state') == 'complete' and j.get('exit_code') == 0}
|
||||
if not REQUIRED <= completed or report['jobs'][-1]['id'] != 'node-monitor-dependencies':
|
||||
raise ValueError('Missing previously qualified stage')
|
||||
for prefix in ('design-guideline-dependencies-', 'node-ui-dependencies-'):
|
||||
if not any(name.startswith(prefix) for name in completed):
|
||||
raise ValueError('UI dependencies were not qualified')
|
||||
source = folder/'source'
|
||||
for name, expected in manifest['files'].items():
|
||||
path = source/name
|
||||
if path.is_symlink() or not path.resolve().is_relative_to(source.resolve()) or digest(path) != expected['sha256']:
|
||||
raise ValueError('Qualified source changed: '+name)
|
||||
node = source/manifest['repository']/'apps/node-agent'
|
||||
if digest(node/'build/node-agent-linux-amd64') != BINARY_HASH:
|
||||
raise ValueError('Race-tested binary changed')
|
||||
if (folder/'output/node-go-format-diff.stdout').read_bytes():
|
||||
raise ValueError('Unresolved Go formatting difference')
|
||||
return manifest, report, node
|
||||
|
||||
|
||||
def main():
|
||||
if os.geteuid() == 0 or (platform.system(), platform.machine()) != ('Linux', 'x86_64'):
|
||||
raise ValueError('Use the unprivileged Ubuntu build account')
|
||||
if sys.argv[1:] not in ([], ['--job']):
|
||||
raise ValueError('Only the fixed Node72 packaging continuation is admitted')
|
||||
os.umask(0o077)
|
||||
for path in (FOLDER.parent, FOLDER):
|
||||
info = path.lstat()
|
||||
if path.is_symlink() or info.st_uid != os.geteuid() or info.st_mode & 0o077:
|
||||
raise ValueError('Build staging is not private and owned')
|
||||
if not sys.argv[1:]:
|
||||
with (FOLDER/'build.lock').open('a') as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
validate_checkpoint(FOLDER)
|
||||
subprocess.run(['/usr/bin/systemd-run', '--user', '--quiet', '--collect', '--wait', '--pipe',
|
||||
'--unit=mission-core-node-packaging-resume-'+IDENTIFIER,
|
||||
'--property=MemoryMax=3G', '--property=CPUQuota=150%', '--property=TasksMax=256',
|
||||
'--property=RuntimeMaxSec=300', '--property=TimeoutStopSec=10',
|
||||
'--property=KillMode=control-group', '--property=Nice=10',
|
||||
'/usr/bin/python3', '-I', str(Path(__file__).resolve()), '--job'], check=True)
|
||||
print(json.dumps({'state':'complete','output':str(FOLDER/'output'),
|
||||
'qualification_sha256':digest(FOLDER/'output/qualification.json')}))
|
||||
return
|
||||
group = next(line.split(':',2)[2] for line in Path('/proc/self/cgroup').read_text().splitlines() if line.startswith('0::'))
|
||||
control = Path('/sys/fs/cgroup')/group.lstrip('/')
|
||||
cpu, period = map(int,(control/'cpu.max').read_text().split())
|
||||
if int((control/'memory.max').read_text()) != 3*1024**3 or cpu/period > 1.5 or int((control/'pids.max').read_text()) > 256:
|
||||
raise ValueError('Continuation resource bounds are not enforced')
|
||||
manifest, report, node = validate_checkpoint(FOLDER)
|
||||
output = FOLDER/'output'
|
||||
previous = output/'qualification-before-packaging-resume.json'
|
||||
if previous.exists():
|
||||
if digest(previous) != REPORT_HASH: raise ValueError('Prior evidence changed')
|
||||
else: shutil.copyfile(output/'qualification.json', previous)
|
||||
started = time.monotonic()
|
||||
stamp = str(time.time_ns())
|
||||
dependency_root = FOLDER/'temporary'/('monitor-dependencies-resume-'+stamp)
|
||||
env = {'PATH':'/usr/bin:/bin','LANG':'C.UTF-8','PYTHONDONTWRITEBYTECODE':'1','TMPDIR':str(FOLDER/'temporary')}
|
||||
with (output/('node-monitor-dependencies-resume-'+stamp+'.stdout')).open('wb') as out, (output/('node-monitor-dependencies-resume-'+stamp+'.stderr')).open('wb') as err:
|
||||
subprocess.run(['/usr/bin/python3',str(node/'packaging/fetch_monitor_dependencies.py'),str(dependency_root)],
|
||||
env=env,stdout=out,stderr=err,timeout=180,check=True)
|
||||
dependencies = json.loads((dependency_root/'manifest.json').read_text())
|
||||
expected_names = {'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'}
|
||||
if {x['file'] for x in dependencies['artifacts']} != expected_names:
|
||||
raise ValueError('Unexpected dependency set')
|
||||
for item in dependencies['artifacts']:
|
||||
path = dependency_root/item['file']
|
||||
if path.stat().st_size != item['bytes'] or digest(path) != item['sha256']:
|
||||
raise ValueError('Verified dependency changed')
|
||||
shutil.copyfile(path,output/path.name)
|
||||
shutil.copyfile(dependency_root/'manifest.json',output/'monitor-dependencies.json')
|
||||
report['jobs'].append({'id':'node-monitor-dependencies-resume','state':'complete','exit_code':0,
|
||||
'duration_seconds':time.monotonic()-started})
|
||||
sys.path.insert(0,str(node/'packaging'))
|
||||
from build_deb import VERSION, build
|
||||
if VERSION != '0.8.49-72': raise ValueError('Unexpected package version')
|
||||
helper_hash = digest(Path(__file__))
|
||||
provenance = {'schema':'missioncore.node.source-provenance/v1','version':VERSION,
|
||||
'base_commit':manifest['base_commit'],'design_guideline_commit':manifest['design_guideline_commit'],
|
||||
'source_manifest_sha256':SOURCE_HASH,'toolchains':manifest['toolchains'],'files':manifest['files'],
|
||||
'packaging_resume_sha256':helper_hash,'qualified_binary_sha256':BINARY_HASH}
|
||||
(node/'build/provenance.json').write_text(json.dumps(provenance,indent=2)+'\n')
|
||||
package = output/('mission-core-node_'+VERSION+'_amd64.deb')
|
||||
build(node/'build/node-agent-linux-amd64',package)
|
||||
recovery = {'schema':'missioncore.node.packaging-resume/v1','state':'complete',
|
||||
'started_monotonic':started,'finished_at':datetime.now(UTC).isoformat(),
|
||||
'duration_seconds':time.monotonic()-started,'helper_sha256':helper_hash,
|
||||
'source_manifest_sha256':SOURCE_HASH,'checkpoint_sha256':REPORT_HASH,
|
||||
'binary_sha256':BINARY_HASH,'memory_peak_bytes':int((control/'memory.peak').read_text()),
|
||||
'resource_limits':{'memory_bytes':3*1024**3,'cpu_percent':150,'tasks':256,'seconds':300},
|
||||
'motor_commands':False}
|
||||
(output/'packaging-resume-report.json').write_text(json.dumps(recovery,indent=2)+'\n')
|
||||
report['jobs'].append({'id':'node-package-resume','state':'complete','exit_code':0,
|
||||
'duration_seconds':recovery['duration_seconds']})
|
||||
# Preserve the interrupted attempt explicitly; only its replacement is complete.
|
||||
for job in report['jobs']:
|
||||
if job['id']=='node-monitor-dependencies' and job['state']=='running':
|
||||
job.update(state='error',reason='original build cgroup RuntimeMaxSec=1200')
|
||||
report.update(state='complete',profile='node-only',finished_at=recovery['finished_at'],
|
||||
duration_seconds=time.monotonic()-report['monotonic_started'],recovered_from=REPORT_HASH,
|
||||
memory_peak_bytes=recovery['memory_peak_bytes'],memory_peak_scope='packaging-resume-only',
|
||||
recovery=recovery)
|
||||
report['artifacts']={p.name:{'bytes':p.stat().st_size,'sha256':digest(p)}
|
||||
for p in [package,output/'monitor-dependencies.json',*[output/n for n in sorted(expected_names)]]}
|
||||
(output/'qualification.json').write_text(json.dumps(report,indent=2)+'\n')
|
||||
|
||||
if __name__=='__main__': main()
|
||||
@@ -0,0 +1,52 @@
|
||||
"""Incremental transport still consumes complete hash-pinned source inputs."""
|
||||
import hashlib
|
||||
import tempfile
|
||||
import unittest
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
from linux_build_entry import source_archives
|
||||
|
||||
|
||||
class SourceReuse(unittest.TestCase):
|
||||
def test_verified_base_and_changed_source_are_selected_without_loose_files(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
base = root / ("mission-core-node-linux-build-" + "a" * 24 + ".pyz")
|
||||
with zipfile.ZipFile(base, "w") as z:
|
||||
z.writestr("source/old", b"original")
|
||||
z.writestr("source/changed", b"previous")
|
||||
base.chmod(0o600)
|
||||
delta = root / "delta.zip"
|
||||
with zipfile.ZipFile(delta, "w") as z:
|
||||
z.writestr("__main__.py", "")
|
||||
z.writestr("source.json", "")
|
||||
z.writestr("source/changed", b"current")
|
||||
manifest = {"files": {"old": {}, "changed": {}}, "payload_files": ["changed"], "base": {"name": base.name, "sha256": hashlib.sha256(base.read_bytes()).hexdigest()}}
|
||||
with zipfile.ZipFile(delta) as z, source_archives(z, manifest, root) as sources:
|
||||
self.assertEqual(sources["old"].read("source/old"), b"original")
|
||||
self.assertEqual(sources["changed"].read("source/changed"), b"current")
|
||||
base.write_bytes(b"changed baseline")
|
||||
with zipfile.ZipFile(delta) as z:
|
||||
with self.assertRaises(ValueError), source_archives(z, manifest, root):
|
||||
pass
|
||||
|
||||
def test_absolute_baseline_and_undeclared_payload_are_rejected(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
delta = root / "delta.zip"
|
||||
with zipfile.ZipFile(delta, "w") as z:
|
||||
z.writestr("__main__.py", "")
|
||||
z.writestr("source.json", "")
|
||||
manifest = {"files": {"old": {}}, "payload_files": [], "base": {"name": "/unrelated", "sha256": "a" * 64}}
|
||||
with zipfile.ZipFile(delta) as z:
|
||||
with self.assertRaises(ValueError), source_archives(z, manifest, root):
|
||||
pass
|
||||
manifest["payload_files"] = ["undeclared"]
|
||||
with zipfile.ZipFile(delta) as z:
|
||||
with self.assertRaises(ValueError), source_archives(z, manifest, root):
|
||||
pass
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,227 @@
|
||||
"""Admission/race/failure tests with fake services; no SDK or real CAN."""
|
||||
|
||||
import importlib.util
|
||||
import json
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
import can_maintenance as owner
|
||||
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"maintenance_gate",
|
||||
Path(__file__).resolve().parents[3]
|
||||
/ "packages/plugin-sdk/python/missioncore_plugin_sdk/maintenance.py",
|
||||
)
|
||||
gates = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(gates)
|
||||
|
||||
|
||||
class StandaloneRuntime(unittest.TestCase):
|
||||
def test_source_runtime_needs_only_standard_library(self):
|
||||
import subprocess
|
||||
import sys
|
||||
repo = Path(__file__).resolve().parents[3]
|
||||
code = "import sys; sys.path[:0] = " + repr([str(repo / "src"), str(repo / "plugins/vesc")]) + "; from runtime.server import Maintenance; assert Maintenance is not None"
|
||||
result = subprocess.run([sys.executable, "-I", "-S", "-c", code], capture_output=True, text=True)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
|
||||
|
||||
class Admission(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.marker = Path(self.tmp.name) / "active"
|
||||
self.gate = gates.Maintenance(self.marker)
|
||||
self.close = Mock()
|
||||
|
||||
def test_active_control_refusal_keeps_relay_and_outputs_untouched(self):
|
||||
self.assertEqual(self.gate.enter(lambda: "control-active", self.close)["safe"], False)
|
||||
with self.gate.work() as admitted:
|
||||
self.assertTrue(admitted)
|
||||
self.close.assert_not_called()
|
||||
|
||||
def test_inflight_operation_is_not_interrupted(self):
|
||||
with self.gate.work():
|
||||
self.assertFalse(self.gate.enter(lambda: None, self.close)["safe"])
|
||||
self.close.assert_not_called()
|
||||
self.assertFalse(self.gate.closed)
|
||||
|
||||
def test_background_read_drains_before_close_and_new_request_is_refused(self):
|
||||
started, release = threading.Event(), threading.Event()
|
||||
|
||||
def read():
|
||||
with self.gate.work(background=True):
|
||||
started.set()
|
||||
release.wait(2)
|
||||
|
||||
thread = threading.Thread(target=read)
|
||||
thread.start()
|
||||
started.wait(1)
|
||||
result = []
|
||||
entrant = threading.Thread(
|
||||
target=lambda: result.append(self.gate.enter(lambda: None, self.close))
|
||||
)
|
||||
entrant.start()
|
||||
for _ in range(100):
|
||||
if self.gate.closed:
|
||||
break
|
||||
time.sleep(0.001)
|
||||
with self.gate.work() as admitted:
|
||||
self.assertFalse(admitted)
|
||||
self.close.assert_not_called()
|
||||
release.set()
|
||||
thread.join()
|
||||
entrant.join()
|
||||
self.assertEqual(result, [{"safe": True}])
|
||||
self.close.assert_called_once()
|
||||
|
||||
def test_timeout_does_not_close_transport_and_explicit_leave_recovers(self):
|
||||
with self.gate.work(background=True):
|
||||
self.assertFalse(self.gate.enter(lambda: None, self.close, timeout=0.001)["safe"])
|
||||
self.close.assert_not_called()
|
||||
self.gate.leave()
|
||||
with self.gate.work() as admitted:
|
||||
self.assertTrue(admitted)
|
||||
|
||||
def test_restarted_services_do_not_resume_during_package_install(self):
|
||||
self.marker.touch()
|
||||
gate = gates.Maintenance(self.marker)
|
||||
with gate.work() as admitted:
|
||||
self.assertFalse(admitted)
|
||||
with self.assertRaises(ValueError):
|
||||
gate.leave()
|
||||
self.marker.unlink()
|
||||
gate.leave()
|
||||
with gate.work() as admitted:
|
||||
self.assertTrue(admitted)
|
||||
|
||||
def test_exception_releases_admission(self):
|
||||
with self.assertRaises(RuntimeError), self.gate.work():
|
||||
raise RuntimeError("fake")
|
||||
self.assertEqual(self.gate.clients, 0)
|
||||
|
||||
|
||||
class Legacy(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.root = Path(self.tmp.name)
|
||||
self.snapshot = {"state": "observing", "release_confirmed": None}
|
||||
self.inventory = {
|
||||
"items": [{"vesc_status": {"test_active": False, "firmware_update": {"state": "idle"}}}]
|
||||
}
|
||||
|
||||
def check(self):
|
||||
owner.legacy_idle(self.snapshot, self.inventory, self.root, self.root, now=1000)
|
||||
|
||||
def test_idle_telemetry_is_admitted(self):
|
||||
self.check()
|
||||
|
||||
def test_active_or_unreleased_control_is_refused(self):
|
||||
for state in ("preparing", "driving"):
|
||||
self.snapshot["state"] = state
|
||||
with self.assertRaises(RuntimeError):
|
||||
self.check()
|
||||
self.snapshot.update(state="stopped", release_confirmed=False)
|
||||
with self.assertRaises(RuntimeError):
|
||||
self.check()
|
||||
|
||||
def test_motor_and_firmware_operations_are_refused(self):
|
||||
state = self.inventory["items"][0]["vesc_status"]
|
||||
state["test_active"] = True
|
||||
with self.assertRaises(RuntimeError):
|
||||
self.check()
|
||||
state["test_active"] = False
|
||||
state["firmware_update"]["state"] = "uploading"
|
||||
with self.assertRaises(RuntimeError):
|
||||
self.check()
|
||||
|
||||
def test_pending_limits_and_unknown_changes_are_not_cleared(self):
|
||||
for name in ("limits_vesc_test.json", "hall-pending.json", "code-execution-test.json"):
|
||||
path = self.root / name
|
||||
path.write_text("{}")
|
||||
with self.assertRaises(RuntimeError):
|
||||
self.check()
|
||||
self.assertTrue(path.exists())
|
||||
path.unlink()
|
||||
|
||||
def test_hall_recovery_exempts_only_hall_marker_and_never_active_control(self):
|
||||
(self.root / "hall-pending.json").write_text("{}")
|
||||
owner.legacy_idle(self.snapshot, self.inventory, self.root, self.root, recovering_hall=True)
|
||||
for name in ("calibration-pending.json", "limits_test.json", "code-execution-test.json"):
|
||||
path = self.root / name; path.write_text("{}")
|
||||
with self.assertRaises(RuntimeError):
|
||||
owner.legacy_idle(self.snapshot, self.inventory, self.root, self.root, recovering_hall=True)
|
||||
path.unlink()
|
||||
self.snapshot["state"] = "driving"
|
||||
with self.assertRaises(RuntimeError):
|
||||
owner.legacy_idle(self.snapshot, self.inventory, self.root, self.root, recovering_hall=True)
|
||||
|
||||
def test_pre_fence_operation_and_recent_capture_refuse_stop(self):
|
||||
path = self.root / "op_test.json"
|
||||
for action, state in [
|
||||
("vesc.foc.calibrate", "running"),
|
||||
("can.transmit.start", "running"),
|
||||
("vesc.samples.start", "complete"),
|
||||
]:
|
||||
path.write_text(
|
||||
json.dumps({"command": {"action_id": action}, "state": state, "updated_at": 999})
|
||||
)
|
||||
with self.assertRaises(RuntimeError):
|
||||
self.check()
|
||||
|
||||
def test_completed_old_capture_does_not_block(self):
|
||||
(self.root / "op_test.json").write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"command": {"action_id": "vesc.samples.start"},
|
||||
"state": "complete",
|
||||
"updated_at": 1,
|
||||
}
|
||||
)
|
||||
)
|
||||
self.check()
|
||||
|
||||
|
||||
class Recovery(unittest.TestCase):
|
||||
def test_failure_after_vesc_stop_restores_can_before_vesc_without_restart(self):
|
||||
m = owner.CanMaintenance({})
|
||||
m.owned = True
|
||||
m.stopped = ["vesc", "usb-can"]
|
||||
m.entered = list(m.stopped)
|
||||
calls = []
|
||||
with (
|
||||
patch.object(owner.MARKER.__class__, "unlink"),
|
||||
patch.object(owner.Path, "exists", return_value=True),
|
||||
patch.object(
|
||||
m, "systemctl", side_effect=lambda action, name: calls.append((action, name))
|
||||
),
|
||||
patch.object(m, "legacy", return_value=False),
|
||||
patch.object(owner, "probe", return_value={"resumed": True}),
|
||||
):
|
||||
m.finish()
|
||||
self.assertEqual(calls, [("start", "usb-can"), ("start", "vesc")])
|
||||
self.assertEqual(m.report["state"], "observation-restored")
|
||||
|
||||
def test_clean_install_resumes_new_services_without_starting_optional_ones(self):
|
||||
m = owner.CanMaintenance({})
|
||||
m.owned = True
|
||||
with patch.object(owner.Path, "unlink"), patch.object(owner.Path, "exists", return_value=True), patch.object(m, "legacy", return_value=False), patch.object(owner, "probe", return_value={"resumed": True}) as probe, patch.object(m, "systemctl") as ctl:
|
||||
m.finish()
|
||||
self.assertEqual(probe.call_count, 2)
|
||||
ctl.assert_not_called()
|
||||
|
||||
def test_no_owner_never_resumes_other_installers(self):
|
||||
m = owner.CanMaintenance({})
|
||||
with patch.object(owner, "probe") as probe, patch.object(owner.Path, "unlink") as unlink:
|
||||
m.finish()
|
||||
probe.assert_not_called()
|
||||
unlink.assert_not_called()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,27 @@
|
||||
"""A Node update must not replace a newer, independently installed camera build."""
|
||||
import json
|
||||
from types import SimpleNamespace
|
||||
import unittest
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
import install_owner_release as installer
|
||||
|
||||
|
||||
class ModelPreservation(unittest.TestCase):
|
||||
def test_newer_camera_is_preserved_without_starting_preparation(self):
|
||||
run = Mock(return_value="0.1.3-15")
|
||||
with patch.object(installer.Path, "read_text", return_value=json.dumps({"version": "0.1.3-9"})), patch.object(installer.subprocess, "run", side_effect=[SimpleNamespace(returncode=0, stdout="install ok installed"), SimpleNamespace(returncode=0)]):
|
||||
result = installer.update_installed_x4(run)
|
||||
self.assertEqual(result, {"state": "newer-installed-preserved", "version": "0.1.3-15"})
|
||||
self.assertEqual(run.call_count, 1)
|
||||
|
||||
def test_invalid_version_comparison_fails_without_model_write(self):
|
||||
run = Mock(return_value="unexpected")
|
||||
with patch.object(installer.Path, "read_text", return_value=json.dumps({"version": "0.1.3-9"})), patch.object(installer.subprocess, "run", side_effect=[SimpleNamespace(returncode=0, stdout="install ok installed"), SimpleNamespace(returncode=2)]):
|
||||
with self.assertRaises(RuntimeError):
|
||||
installer.update_installed_x4(run)
|
||||
self.assertEqual(run.call_count, 1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,54 @@
|
||||
"""Qualified owner releases carry the pinned non-Ubuntu dependencies."""
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
import zipfile
|
||||
import build_owner_release as builder
|
||||
import install_owner_release as installer
|
||||
|
||||
|
||||
class OwnerDependencyTests(unittest.TestCase):
|
||||
def fixture(self, root):
|
||||
node=root/'apps/node-agent';packaging=node/'packaging';packaging.mkdir(parents=True)
|
||||
(node/'build').mkdir()
|
||||
(packaging/'vesc_hall_recovery.py').write_bytes(b'# hall recovery\n')
|
||||
(packaging/'can_maintenance.py').write_bytes(b'# maintenance\n')
|
||||
(packaging/'install-owner-release').write_bytes(b'installer')
|
||||
(packaging/'install_owner_release.py').write_bytes(b'python installer')
|
||||
entry=root/'plugins/insta360-x4/packaging';entry.mkdir(parents=True)
|
||||
(entry/'owner_release_entry.py').write_bytes(b'entry')
|
||||
qualified=root/'qualified';qualified.mkdir()
|
||||
files={'mission-core-node_0.8.49-8_amd64.deb':b'node', **{name:name.encode() for name in builder.NODE_DEPENDENCIES}}
|
||||
for name,data in files.items():(qualified/name).write_bytes(data)
|
||||
evidence={'state':'complete','artifacts':{name:{'bytes':len(data),'sha256':hashlib.sha256(data).hexdigest()} for name,data in files.items()}}
|
||||
(qualified/'qualification.json').write_text(json.dumps(evidence))
|
||||
return node,qualified
|
||||
|
||||
def test_pinned_dependency_set_and_hashes_are_in_actual_owner_release(self):
|
||||
self.assertEqual(builder.NODE_DEPENDENCIES,installer.NODE_DEPENDENCIES)
|
||||
entry_path=Path(__file__).resolve().parents[3]/'plugins/insta360-x4/packaging/owner_release_entry.py'
|
||||
spec=importlib.util.spec_from_file_location('owner_entry',entry_path);entry=importlib.util.module_from_spec(spec);spec.loader.exec_module(entry)
|
||||
self.assertEqual(builder.NODE_DEPENDENCIES,entry.NODE_DEPENDENCIES)
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root=Path(directory);node,qualified=self.fixture(root)
|
||||
with patch.object(builder,'ROOT',node),patch.object(builder,'REPO',root):result=builder.build(qualified)
|
||||
with zipfile.ZipFile(result['artifact']) as archive:
|
||||
manifest=json.loads(archive.read('release.json'))
|
||||
self.assertEqual(manifest['dependencies'],list(builder.NODE_DEPENDENCIES))
|
||||
self.assertFalse(manifest['clean_image_qualified'])
|
||||
for name in builder.NODE_DEPENDENCIES:
|
||||
self.assertEqual(hashlib.sha256(archive.read(name)).hexdigest(),manifest['files'][name]['sha256'])
|
||||
|
||||
def test_tampered_dependency_prevents_publication(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root=Path(directory);node,qualified=self.fixture(root)
|
||||
(qualified/builder.NODE_DEPENDENCIES[0]).write_bytes(b'changed')
|
||||
with patch.object(builder,'ROOT',node),patch.object(builder,'REPO',root):
|
||||
with self.assertRaisesRegex(ValueError,'dependency changed'):builder.build(qualified)
|
||||
self.assertEqual(list((node/'build').iterdir()),[])
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
@@ -0,0 +1,53 @@
|
||||
"""Refuse changed checkpoints and unqualified source/binary in fixed recovery."""
|
||||
import json
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
import resume_node72_packaging as recovery
|
||||
|
||||
class CheckpointTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp=tempfile.TemporaryDirectory()
|
||||
self.root=Path(self.temp.name)
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
(self.root/'output').mkdir()
|
||||
self.binary=self.root/'source/NODEDC_MISSION_CORE/apps/node-agent/build/node-agent-linux-amd64'
|
||||
self.binary.parent.mkdir(parents=True)
|
||||
self.binary.write_bytes(b'qualified-elf')
|
||||
self.source=self.root/'source/NODEDC_MISSION_CORE/config.txt'
|
||||
self.source.write_bytes(b'qualified-source')
|
||||
manifest={'repository':'NODEDC_MISSION_CORE','files':{'NODEDC_MISSION_CORE/config.txt':{'sha256':recovery.digest(self.source)}}}
|
||||
(self.root/'source.json').write_text(json.dumps(manifest))
|
||||
jobs=[{'id':name,'state':'complete','exit_code':0} for name in sorted(recovery.REQUIRED)]
|
||||
jobs += [{'id':name+'1','state':'complete','exit_code':0} for name in ('design-guideline-dependencies-','node-ui-dependencies-')]
|
||||
jobs.append({'id':'node-monitor-dependencies','state':'running'})
|
||||
self.report=self.root/'output/qualification.json'
|
||||
self.report.write_text(json.dumps({'jobs':jobs}))
|
||||
(self.root/'report.json').write_text('{"state":"error"}')
|
||||
(self.root/'output/node-go-format-diff.stdout').write_bytes(b'')
|
||||
values={'SOURCE_HASH':recovery.digest(self.root/'source.json'),'REPORT_HASH':recovery.digest(self.report),
|
||||
'BUILD_HASH':recovery.digest(self.root/'report.json'),'BINARY_HASH':recovery.digest(self.binary)}
|
||||
self.patches=patch.multiple(recovery,**values);self.patches.start();self.addCleanup(self.patches.stop)
|
||||
def test_exact_checkpoint_is_accepted(self):
|
||||
self.assertEqual(recovery.validate_checkpoint(self.root)[2],self.binary.parent.parent)
|
||||
def test_changed_source_is_rejected(self):
|
||||
self.source.write_bytes(b'changed')
|
||||
with self.assertRaisesRegex(ValueError,'source changed'):recovery.validate_checkpoint(self.root)
|
||||
def test_changed_binary_is_rejected(self):
|
||||
self.binary.write_bytes(b'changed')
|
||||
with self.assertRaisesRegex(ValueError,'binary changed'):recovery.validate_checkpoint(self.root)
|
||||
def test_changed_checkpoint_is_rejected(self):
|
||||
self.report.write_text('{}')
|
||||
with self.assertRaisesRegex(ValueError,'checkpoint changed'):recovery.validate_checkpoint(self.root)
|
||||
def test_unfinished_go_stage_is_rejected_even_in_a_pinned_report(self):
|
||||
data=json.loads(self.report.read_text())
|
||||
next(j for j in data['jobs'] if j['id']=='node-go-tests')['state']='running'
|
||||
self.report.write_text(json.dumps(data))
|
||||
with patch.object(recovery,'REPORT_HASH',recovery.digest(self.report)):
|
||||
with self.assertRaisesRegex(ValueError,'qualified stage'):recovery.validate_checkpoint(self.root)
|
||||
def test_source_symlink_is_rejected(self):
|
||||
target=self.root/'other';target.write_bytes(self.source.read_bytes());self.source.unlink();self.source.symlink_to(target)
|
||||
with self.assertRaisesRegex(ValueError,'source changed'):recovery.validate_checkpoint(self.root)
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
@@ -0,0 +1,126 @@
|
||||
"""Recovery failure boundaries; all controller responses are synthetic."""
|
||||
import base64
|
||||
import copy
|
||||
import hashlib
|
||||
import json
|
||||
import tempfile
|
||||
import unittest
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
import vesc_hall_recovery as recovery
|
||||
|
||||
|
||||
class HallRecovery(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory(); self.addCleanup(self.tmp.cleanup)
|
||||
self.root = Path(self.tmp.name)
|
||||
self.operation = 'op_' + 'a' * 32
|
||||
self.ids = ['vesc_' + x * 32 for x in ('b', 'c')]
|
||||
self.backups = ['op_' + x * 32 for x in ('d', 'e')]
|
||||
self.identities = {key: {'version': '5.02', 'hardware': '75_300_R2', 'test_firmware': 0,
|
||||
'hardware_type': 0, 'uuid': str(i)} for i, key in enumerate(self.ids)}
|
||||
self.hash = hashlib.sha256(b'configuration').hexdigest()
|
||||
configs = {kind: {'payload': base64.b64encode(b'configuration').decode(), 'sha256': self.hash, 'bytes': 13}
|
||||
for kind in ('motor', 'application')}
|
||||
for key, op in zip(self.ids, self.backups):
|
||||
self.write('backup_' + op + '.json', {'device_id': key, 'operation_id': op,
|
||||
'parent_operation_id': self.operation, 'identity': self.identities[key], 'configs': configs})
|
||||
self.pending = {'device_id': self.ids[0], 'identity': self.identities[self.ids[0]],
|
||||
'started_at': '2026-01-01T00:00:00+00:00', 'backups': self.backups}
|
||||
self.write('hall-pending.json', self.pending)
|
||||
self.receipt = {'receipt': {'state': 'complete', 'result': {'procedure': 'native_foc_hall',
|
||||
'completed': False, 'configuration_written': False, 'device_id': self.ids[0], 'backups': self.backups}}}
|
||||
self.write(self.operation + '.json', self.receipt)
|
||||
self.inventory = {'items': [{'id': key, 'vesc_status': {'connected': True, 'identity': self.identities[key]},
|
||||
'snapshot': {'context': {'session_id': 'session_' + key}}} for key in self.ids]}
|
||||
self.calls = []
|
||||
self.change = lambda action, result: None
|
||||
|
||||
def write(self, name, data):
|
||||
(self.root / name).write_text(json.dumps(data))
|
||||
|
||||
def read(self, command):
|
||||
self.calls.append(command)
|
||||
key, action = command['session']['device_id'], command['action_id']
|
||||
self.assertEqual(command['parameters'], {})
|
||||
result = {'identity': copy.deepcopy(self.identities[key])}
|
||||
if action == 'vesc.configuration.read':
|
||||
result['configuration'] = {kind: {'packet_sha256': self.hash} for kind in ('motor', 'application')}
|
||||
elif action == 'vesc.telemetry.read':
|
||||
result['values'] = {'motor_current_a': 0, 'input_current_a': 0, 'erpm': 0, 'duty': 0, 'fault_code': 0}
|
||||
elif action == 'vesc.input.read':
|
||||
result['input'] = {'level': 0, 'pulse_ms': 0}
|
||||
else:
|
||||
self.fail('Recovery emitted a non-read action: ' + action)
|
||||
self.change(action, result)
|
||||
return {'state': 'complete', 'result': result}
|
||||
|
||||
def run_recovery(self, **kwargs):
|
||||
return recovery.recover_hall(self.read, self.inventory, self.root, sleep=lambda _: None,
|
||||
now=datetime(2026, 1, 1, 0, 2, tzinfo=timezone.utc), **kwargs)
|
||||
|
||||
def test_recovery_archives_unknown_result_and_preserves_original_receipt(self):
|
||||
original = (self.root / (self.operation + '.json')).read_bytes()
|
||||
result = self.run_recovery()
|
||||
self.assertFalse((self.root / 'hall-pending.json').exists())
|
||||
self.assertEqual(result['outcome'], 'measurement-result-unknown')
|
||||
self.assertFalse(result['measurement_replayed'])
|
||||
self.assertFalse(result['motor_commands'])
|
||||
self.assertEqual(len(result['samples']), 6)
|
||||
self.assertEqual((self.root / (self.operation + '.json')).read_bytes(), original)
|
||||
self.assertTrue((self.root / ('hall_recovered_' + self.operation + '.json')).is_file())
|
||||
self.assertEqual(len({c['operation_id'] for c in self.calls}), len(self.calls))
|
||||
|
||||
def test_active_native_cycle_and_future_clock_are_refused_before_reads(self):
|
||||
for started in ('2026-01-01T00:01:45+00:00', '2027-01-01T00:00:00+00:00'):
|
||||
self.pending['started_at'] = started; self.write('hall-pending.json', self.pending)
|
||||
with self.assertRaises(RuntimeError): self.run_recovery()
|
||||
self.assertEqual(self.calls, [])
|
||||
|
||||
def test_incomplete_foreign_or_config_writing_receipt_is_not_recovered(self):
|
||||
for field, value in [('procedure', 'native_foc_calibration'), ('completed', True), ('configuration_written', True)]:
|
||||
modified = copy.deepcopy(self.receipt); modified['receipt']['result'][field] = value
|
||||
self.write(self.operation + '.json', modified)
|
||||
with self.assertRaises(RuntimeError): self.run_recovery()
|
||||
self.assertTrue((self.root / 'hall-pending.json').exists())
|
||||
self.assertEqual(self.calls, [])
|
||||
|
||||
def test_config_identity_motion_fault_or_receiver_change_keeps_interlock(self):
|
||||
changes = [
|
||||
lambda a, r: r['identity'].update(uuid='replacement'),
|
||||
lambda a, r: r['configuration']['motor'].update(packet_sha256='0'*64) if a.endswith('configuration.read') else None,
|
||||
*[lambda a, r, k=k, v=v: r['values'].update({k: v}) if a.endswith('telemetry.read') else None
|
||||
for k, v in [('motor_current_a', 2), ('input_current_a', 2), ('erpm', 1), ('duty', .01), ('fault_code', 1), ('motor_current_a', float('nan'))]],
|
||||
lambda a, r: r['input'].update(pulse_ms=1.5) if a.endswith('input.read') else None,
|
||||
]
|
||||
for change in changes:
|
||||
self.change = change
|
||||
with self.assertRaises(RuntimeError): self.run_recovery()
|
||||
self.assertTrue((self.root / 'hall-pending.json').exists())
|
||||
self.assertEqual(list(self.root.glob('hall_recovered*')), [])
|
||||
|
||||
def test_replaced_missing_or_duplicate_controller_is_refused(self):
|
||||
original = copy.deepcopy(self.inventory)
|
||||
for items in ([], original['items'][:1], original['items'] + original['items'][:1]):
|
||||
self.inventory = {'items': items}
|
||||
with self.assertRaises(RuntimeError): self.run_recovery()
|
||||
self.assertEqual(self.calls, [])
|
||||
|
||||
def test_transport_error_does_not_replay_or_clear(self):
|
||||
with patch.object(self, 'read', side_effect=TimeoutError) as read:
|
||||
with self.assertRaises(TimeoutError): self.run_recovery()
|
||||
self.assertEqual(read.call_count, 1)
|
||||
self.assertTrue((self.root / 'hall-pending.json').exists())
|
||||
|
||||
def test_evidence_write_failure_keeps_interlock(self):
|
||||
with patch.object(recovery.os, 'fsync', side_effect=OSError('disk failure')):
|
||||
with self.assertRaises(OSError): self.run_recovery()
|
||||
self.assertTrue((self.root / 'hall-pending.json').exists())
|
||||
|
||||
def test_unknown_runtime_is_not_migrated(self):
|
||||
self.assertFalse(recovery.hall_recovery_supported(self.root))
|
||||
|
||||
|
||||
if __name__ == '__main__': unittest.main()
|
||||
@@ -0,0 +1,187 @@
|
||||
"""No radio/OS changes: validate trial rollback and qualification boundaries."""
|
||||
|
||||
import json
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
import wifi_latency_trial as w
|
||||
|
||||
|
||||
class TrialTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.root = Path(self.temp.name)
|
||||
self.identity = {
|
||||
"ifindex": 4,
|
||||
"device": "/sys/devices/pci/adapter",
|
||||
"connection": "12345678-1234-1234-1234-123456789abc",
|
||||
}
|
||||
self.state = (0, 0, 0, 0)
|
||||
self.writes = []
|
||||
self.patches = [
|
||||
patch.object(w, "ROOT", self.root),
|
||||
patch.object(w, "STATE", self.root / "state.json"),
|
||||
patch.object(w, "idle"),
|
||||
patch.object(w, "fingerprint", return_value=self.identity),
|
||||
patch.object(w, "power", side_effect=self.power),
|
||||
patch.object(w, "DURATION", 0),
|
||||
patch.object(Path, "read_text", autospec=True, side_effect=self.read),
|
||||
]
|
||||
self.original_read = Path.read_text
|
||||
for p in self.patches:
|
||||
p.start()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
for p in self.patches:
|
||||
self.addCleanup(p.stop)
|
||||
|
||||
def read(self, path, *args, **kwargs):
|
||||
if str(path) == "/proc/sys/kernel/random/boot_id":
|
||||
return "boot-1"
|
||||
if str(path) == "/etc/os-release":
|
||||
return "ID=ubuntu\nVERSION_ID=24.04\n"
|
||||
return self.original_read(path, *args, **kwargs)
|
||||
|
||||
def power(self, name, setting=None):
|
||||
if setting is not None:
|
||||
saved = json.loads((self.root / "state.json").read_text())
|
||||
self.assertEqual(saved["adapters"][0]["original"], [0, 0, 0, 0])
|
||||
self.writes.append(setting)
|
||||
self.state = setting
|
||||
return self.state
|
||||
|
||||
def adapters(self):
|
||||
return [{"interface": "wlan0", "identity": self.identity, "original": list(self.state)}]
|
||||
|
||||
def test_original_journal_precedes_set_and_success_restores(self):
|
||||
result = w.trial(self.adapters())
|
||||
self.assertEqual(self.writes, [w.OFF, (0, 0, 0, 0)])
|
||||
self.assertEqual(result["state"], "restored")
|
||||
self.assertFalse(result["motor_commands"])
|
||||
|
||||
def test_active_control_prevents_all_writes(self):
|
||||
w.idle.side_effect = RuntimeError("active")
|
||||
with self.assertRaisesRegex(RuntimeError, "active"):
|
||||
w.trial(self.adapters())
|
||||
self.assertEqual(self.writes, [])
|
||||
self.assertFalse((self.root / "state.json").exists())
|
||||
|
||||
def test_failure_after_apply_always_restores(self):
|
||||
with (
|
||||
patch.object(w, "DURATION", 5),
|
||||
patch.object(w.time, "sleep", side_effect=RuntimeError("interrupted")),
|
||||
self.assertRaisesRegex(RuntimeError, "interrupted"),
|
||||
):
|
||||
w.trial(self.adapters())
|
||||
self.assertEqual(self.writes, [w.OFF, (0, 0, 0, 0)])
|
||||
self.assertEqual(json.loads((self.root / "state.json").read_text())["state"], "restored")
|
||||
|
||||
def test_already_disabled_adapter_not_modified(self):
|
||||
self.state = w.OFF
|
||||
result = w.trial(self.adapters())
|
||||
self.assertEqual(self.writes, [])
|
||||
self.assertEqual(result["state"], "restored")
|
||||
|
||||
def test_connection_replacement_never_overwrites_new_owner(self):
|
||||
with patch.object(w, "DURATION", 5):
|
||||
w.fingerprint.return_value = {**self.identity, "connection": "new"}
|
||||
with self.assertRaisesRegex(RuntimeError, "connection changed"):
|
||||
w.trial(self.adapters())
|
||||
self.assertEqual(self.writes, [w.OFF])
|
||||
self.assertEqual(json.loads((self.root / "state.json").read_text())["state"], "running")
|
||||
|
||||
def test_restoration_preserves_another_runtime_power_setting(self):
|
||||
# Inspect's read-only command contract is also checked in source below;
|
||||
# restoration refuses a replaced state rather than forcing it back.
|
||||
value = {
|
||||
"schema": "missioncore.wifi-latency-trial/v1",
|
||||
"state": "running",
|
||||
"boot_id": "boot-1",
|
||||
"adapters": [
|
||||
{"interface": "wlan0", "identity": self.identity, "original": [3, 0, 0, 0]}
|
||||
],
|
||||
}
|
||||
with self.assertRaisesRegex(RuntimeError, "Another power setting"):
|
||||
w.restore(value)
|
||||
self.assertEqual(self.writes, [])
|
||||
|
||||
def test_different_boot_never_replays_saved_power(self):
|
||||
value = {"state": "running", "boot_id": "older", "adapters": self.adapters()}
|
||||
with self.assertRaisesRegex(RuntimeError, "Different boot"):
|
||||
w.restore(value)
|
||||
self.assertEqual(self.writes, [])
|
||||
|
||||
def test_restore_is_idempotent(self):
|
||||
result = w.trial(self.adapters())
|
||||
count = len(self.writes)
|
||||
self.assertEqual(w.restore(result)["state"], "restored")
|
||||
self.assertEqual(len(self.writes), count)
|
||||
|
||||
def hardware(self):
|
||||
net = self.root / "net"
|
||||
device = net / "wlan0" / "device"
|
||||
device.mkdir(parents=True)
|
||||
(device / "vendor").write_text("0x14e4")
|
||||
(device / "device").write_text("0x4331")
|
||||
driver = self.root / "wl"
|
||||
driver.mkdir()
|
||||
(device / "driver").symlink_to(driver)
|
||||
return net
|
||||
|
||||
def test_inspection_rejects_explicit_profile_before_any_power_ioctl(self):
|
||||
net = self.hardware()
|
||||
with (
|
||||
patch.object(w, "SYS", net),
|
||||
patch.object(w.os, "uname", return_value=type("U", (), {"machine": "x86_64"})()),
|
||||
patch.object(w, "command", return_value="enable"),
|
||||
self.assertRaisesRegex(RuntimeError, "foreign power policy"),
|
||||
):
|
||||
w.inspect()
|
||||
w.power.assert_not_called()
|
||||
|
||||
def test_inspection_qualifies_only_supported_connected_adapter(self):
|
||||
net = self.hardware()
|
||||
with (
|
||||
patch.object(w, "SYS", net),
|
||||
patch.object(w.os, "uname", return_value=type("U", (), {"machine": "x86_64"})()),
|
||||
patch.object(w, "command", return_value="default"),
|
||||
):
|
||||
found = w.inspect()
|
||||
self.assertEqual(found, self.adapters())
|
||||
(net / "wlan0" / "device" / "device").write_text("0x9999")
|
||||
with self.assertRaisesRegex(RuntimeError, "one supported adapter"):
|
||||
w.inspect()
|
||||
self.assertEqual(self.writes, [])
|
||||
|
||||
def test_unit_is_not_enabled_or_started_by_package_install(self):
|
||||
root = Path(__file__).parent
|
||||
unit = (root / "mission-core-node-wifi-trial.service").read_text()
|
||||
self.assertIn("ExecStopPost=", unit)
|
||||
self.assertIn("TimeoutStartSec=210", unit)
|
||||
self.assertNotIn("[Install]", unit)
|
||||
self.assertNotIn("wifi-trial", (root / "postinst").read_text())
|
||||
self.assertIn("wifi_latency_trial.py", (root / "build_deb.py").read_text())
|
||||
|
||||
|
||||
class WireFormatTests(unittest.TestCase):
|
||||
def test_invalid_interface_never_opens_a_socket(self):
|
||||
with patch.object(w.socket, "socket") as sock:
|
||||
with self.assertRaises(ValueError):
|
||||
w.power("../bad")
|
||||
sock.assert_not_called()
|
||||
|
||||
def test_query_is_get_only_and_has_exact_amd64_iwreq_layout(self):
|
||||
with (
|
||||
patch.object(w.socket, "socket"),
|
||||
patch.object(w.fcntl, "ioctl", side_effect=lambda fd, op, arg: arg) as ioctl,
|
||||
):
|
||||
self.assertEqual(w.power("wlan0"), (0, 0, 0, 0))
|
||||
args = ioctl.call_args.args
|
||||
self.assertEqual(args[1], 0x8B2D)
|
||||
self.assertEqual(len(args[2]), 32)
|
||||
self.assertEqual(args[2][:16], b"wlan0" + b"\0" * 11)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,152 @@
|
||||
"""Installer recovery of a lost FW 5.02 Hall reply, using read-only operations.
|
||||
|
||||
Call only behind the installer socket fence and after all admitted work drains.
|
||||
This proves restored idle/configuration, NOT successful Hall measurement. It
|
||||
never retries a procedure, changes configuration, or emits a motor command.
|
||||
"""
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
import uuid
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
HALL_ROOT = Path('/var/lib/mission-core-vesc')
|
||||
HALL_SERVER = '0cfd1172d0a0f3402f7753218e3532d1b614b33dd1761ddecb914183b14a7e61'
|
||||
HALL_IMPLEMENTATIONS = {
|
||||
'941e4babf038cb4cb53dd3fa714958b1b0267e5ab6d07db8ac5c49547d0ecc21', # 0.19.5
|
||||
'6f37b66f7e2069190215a11018cc7ddc27cf3eb5c0d624435c9a464b729a032a', # 0.19.6
|
||||
}
|
||||
|
||||
|
||||
def hall_recovery_supported(runtime=Path('/usr/lib/mission-core-vesc/runtime')):
|
||||
def digest(name):
|
||||
path = runtime / name
|
||||
return hashlib.sha256(path.read_bytes()).hexdigest() if path.is_file() else None
|
||||
return digest('server.py') == HALL_SERVER and digest('hall_detection.py') in HALL_IMPLEMENTATIONS
|
||||
|
||||
|
||||
def hall_json(path):
|
||||
if path.is_symlink() or not path.is_file() or path.stat().st_size > 1024 * 1024:
|
||||
raise RuntimeError('Недопустимое свидетельство измерения Холлов.')
|
||||
return json.loads(path.read_bytes())
|
||||
|
||||
|
||||
def hall_operation(value):
|
||||
if not isinstance(value, str) or not re.fullmatch(r'op_[0-9a-f]{32}', value):
|
||||
raise RuntimeError('Не подтверждена принадлежность измерения Холлов.')
|
||||
return value
|
||||
|
||||
|
||||
def recover_hall(read, inventory, root=HALL_ROOT, sleep=time.sleep, now=None):
|
||||
"""read(command) is a one-shot authenticated /operation on the fenced socket."""
|
||||
pending = root / 'hall-pending.json'
|
||||
original = pending.read_bytes()
|
||||
record = hall_json(pending)
|
||||
now = datetime.now(timezone.utc) if now is None else now
|
||||
age = (now - datetime.fromisoformat(record['started_at'])).total_seconds()
|
||||
if not 60 <= age:
|
||||
raise RuntimeError('Нативное измерение Холлов ещё могло не завершиться.')
|
||||
backups = record['backups']
|
||||
if not isinstance(backups, list) or not 1 <= len(backups) <= 8 or len(set(backups)) != len(backups):
|
||||
raise RuntimeError('Не подтверждён полный набор исходных конфигураций.')
|
||||
expected, parents = {}, set()
|
||||
for identifier in backups:
|
||||
backup = hall_json(root / ('backup_' + hall_operation(identifier) + '.json'))
|
||||
parents.add(hall_operation(backup['parent_operation_id']))
|
||||
if backup['device_id'] in expected or backup['operation_id'] != identifier:
|
||||
raise RuntimeError('Конфликт резервных копий контроллеров.')
|
||||
identity = backup['identity']
|
||||
if (identity['version'], identity['hardware'], identity['test_firmware'], identity['hardware_type']) != ('5.02', '75_300_R2', 0, 0):
|
||||
raise RuntimeError('Восстановление не проверено для этой прошивки.')
|
||||
for kind in ('motor', 'application'):
|
||||
cfg = backup['configs'][kind]
|
||||
raw = base64.b64decode(cfg['payload'], validate=True)
|
||||
if len(raw) != cfg['bytes'] or hashlib.sha256(raw).hexdigest() != cfg['sha256']:
|
||||
raise RuntimeError('Повреждена исходная конфигурация.')
|
||||
expected[backup['device_id']] = backup
|
||||
if len(parents) != 1 or record['device_id'] not in expected or record['identity'] != expected[record['device_id']]['identity']:
|
||||
raise RuntimeError('Не подтверждена принадлежность измерения Холлов.')
|
||||
operation = parents.pop()
|
||||
receipt = hall_json(root / (operation + '.json'))['receipt']
|
||||
result = receipt.get('result', {})
|
||||
if (receipt.get('state') != 'complete' or result.get('procedure') != 'native_foc_hall'
|
||||
or result.get('completed') is not False or result.get('configuration_written') is not False
|
||||
or result.get('device_id') != record['device_id'] or result.get('backups') != backups):
|
||||
raise RuntimeError('Нет завершённой записи о потере результата измерения Холлов.')
|
||||
devices = {item['id']: item for item in inventory['items']}
|
||||
if len(devices) != len(inventory['items']) or set(devices) != set(expected):
|
||||
raise RuntimeError('Состав контроллеров изменился после измерения.')
|
||||
for identifier, device in devices.items():
|
||||
state = device['vesc_status']
|
||||
if not state['connected'] or state['identity'] != expected[identifier]['identity']:
|
||||
raise RuntimeError('Личность подключённых контроллеров не подтверждена.')
|
||||
|
||||
reads = []
|
||||
def query(identifier, action):
|
||||
# Fixed read allowlist; never accept an operation from a journal or argument.
|
||||
if action not in ('vesc.configuration.read', 'vesc.telemetry.read', 'vesc.input.read'):
|
||||
raise RuntimeError('Recovery is read-only')
|
||||
current = datetime.now(timezone.utc)
|
||||
op = 'op_' + uuid.uuid4().hex
|
||||
response = read({'api_version': 'missioncore.nodedc/plugin-sdk/v0alpha2', 'kind': 'OperationRequest',
|
||||
'operation_id': op, 'idempotency_key': op, 'action_id': action, 'parameters': {},
|
||||
'session': {'device_id': identifier, 'session_id': devices[identifier]['snapshot']['context']['session_id']},
|
||||
'requested_at': current.isoformat(), 'deadline_at': (current + timedelta(seconds=30)).isoformat()})
|
||||
if response.get('state') != 'complete' or response.get('result', {}).get('identity') != expected[identifier]['identity']:
|
||||
raise RuntimeError('Свежий ответ контроллера не подтверждён. Измерение не повторяется.')
|
||||
reads.append({'operation_id': op, 'action_id': action, 'device_id': identifier})
|
||||
return response['result']
|
||||
|
||||
configurations = {}
|
||||
for identifier, backup in expected.items():
|
||||
actual = query(identifier, 'vesc.configuration.read')['configuration']
|
||||
hashes = {kind: actual[kind]['packet_sha256'] for kind in ('motor', 'application')}
|
||||
if hashes != {kind: backup['configs'][kind]['sha256'] for kind in hashes}:
|
||||
raise RuntimeError('Конфигурация после измерения отличается; автоматическое восстановление запрещено.')
|
||||
configurations[identifier] = hashes
|
||||
samples = []
|
||||
for _ in range(3):
|
||||
for identifier in expected:
|
||||
value = query(identifier, 'vesc.telemetry.read')['values']
|
||||
incoming = query(identifier, 'vesc.input.read')['input']
|
||||
limits = {'motor_current_a': .5, 'input_current_a': .5, 'erpm': 0, 'duty': .001}
|
||||
if any(not math.isfinite(value[k]) or abs(value[k]) > limit for k, limit in limits.items()) or value['fault_code'] != 0:
|
||||
raise RuntimeError('Не подтверждена остановка привода без тока и ошибок.')
|
||||
if incoming['level'] != 0 or incoming['pulse_ms'] != 0:
|
||||
raise RuntimeError('Для восстановления отключите пульт управления.')
|
||||
samples.append({'device_id': identifier, 'values': value, 'input': incoming})
|
||||
sleep(.5)
|
||||
if pending.read_bytes() != original:
|
||||
raise RuntimeError('Запись незавершённого измерения изменилась.')
|
||||
evidence = {'schema': 'missioncore.vesc.hall-recovery/v1', 'operation_id': operation,
|
||||
'observed_at': datetime.now(timezone.utc).isoformat(), 'pending_sha256': hashlib.sha256(original).hexdigest(),
|
||||
'pending': record, 'outcome': 'measurement-result-unknown', 'idle_verified': True,
|
||||
'configuration_verified': True, 'motor_commands': False, 'configuration_writes': False,
|
||||
'measurement_replayed': False, 'configurations': configurations, 'reads': reads, 'samples': samples}
|
||||
# Durable evidence precedes removal of the interlock. Crash before unlink is
|
||||
# safe to re-check; the original measurement receipt is never overwritten.
|
||||
output = root / ('hall_recovered_' + operation + '.json')
|
||||
temporary = root / ('.hall-recovery-' + uuid.uuid4().hex)
|
||||
try:
|
||||
with temporary.open('x') as stream:
|
||||
os.chmod(temporary, 0o640)
|
||||
info = pending.stat()
|
||||
os.chown(temporary, info.st_uid, info.st_gid)
|
||||
json.dump(evidence, stream, ensure_ascii=False)
|
||||
stream.flush(); os.fsync(stream.fileno())
|
||||
temporary.replace(output)
|
||||
fd = os.open(root, os.O_RDONLY)
|
||||
try:
|
||||
os.fsync(fd)
|
||||
pending.unlink()
|
||||
os.fsync(fd)
|
||||
finally:
|
||||
os.close(fd)
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
return evidence
|
||||
@@ -0,0 +1,253 @@
|
||||
#!/usr/bin/python3
|
||||
"""Installed, bounded BCM4331/wl power-save qualification, with automatic restore.
|
||||
|
||||
Ubuntu 24.04 amd64 only. No association, profile, route, radio, service, motor or
|
||||
persistent network change. Invoke the shipped oneshot; it owns rollback even if
|
||||
SSH closes. Other hardware is deliberately unsupported pending qualification.
|
||||
"""
|
||||
|
||||
import fcntl
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import signal
|
||||
import socket
|
||||
import stat
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path("/run/mission-core-node-wifi-trial")
|
||||
STATE = ROOT / "state.json"
|
||||
SYS = Path("/sys/class/net")
|
||||
ENV = {"PATH": "/usr/sbin:/usr/bin:/sbin:/bin", "LANG": "C.UTF-8"}
|
||||
GET_POWER, SET_POWER = 0x8B2D, 0x8B2C
|
||||
OFF = (0, 0, 1, 0)
|
||||
DURATION = 180
|
||||
|
||||
|
||||
def command(args):
|
||||
return subprocess.check_output(args, env=ENV, timeout=8, text=True).strip()
|
||||
|
||||
|
||||
def power(name, setting=None):
|
||||
if not re.fullmatch(r"[A-Za-z0-9_.-]{1,15}", name):
|
||||
raise ValueError("Invalid interface identity")
|
||||
request = struct.pack("@16siBBH8x", name.encode(), *(setting or (0, 0, 0, 0)))
|
||||
assert len(request) == 32
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
|
||||
result = fcntl.ioctl(sock.fileno(), GET_POWER if setting is None else SET_POWER, request)
|
||||
return struct.unpack("@16siBBH8x", result)[1:]
|
||||
|
||||
|
||||
def fingerprint(name):
|
||||
root = SYS / name
|
||||
return {
|
||||
"ifindex": int((root / "ifindex").read_text()),
|
||||
"device": str((root / "device").resolve()),
|
||||
"connection": command(["/usr/bin/nmcli", "-g", "GENERAL.CON-UUID", "device", "show", name]),
|
||||
}
|
||||
|
||||
|
||||
def inspect():
|
||||
release = dict(
|
||||
line.split("=", 1)
|
||||
for line in Path("/etc/os-release").read_text().splitlines()
|
||||
if "=" in line
|
||||
)
|
||||
if (
|
||||
release.get("ID", "").strip('"'),
|
||||
release.get("VERSION_ID", "").strip('"'),
|
||||
os.uname().machine,
|
||||
) != ("ubuntu", "24.04", "x86_64"):
|
||||
raise RuntimeError("Unsupported environment profile")
|
||||
found = []
|
||||
for root in sorted(SYS.iterdir()):
|
||||
device = root / "device"
|
||||
try:
|
||||
if (
|
||||
(device / "vendor").read_text().strip(),
|
||||
(device / "device").read_text().strip(),
|
||||
(device / "driver").resolve().name,
|
||||
) != ("0x14e4", "0x4331", "wl"):
|
||||
continue
|
||||
except OSError:
|
||||
continue
|
||||
identity = fingerprint(root.name)
|
||||
if not re.fullmatch(r"[0-9a-f-]{36}", identity["connection"]):
|
||||
raise RuntimeError("Supported adapter is not connected")
|
||||
policy = command(
|
||||
[
|
||||
"/usr/bin/nmcli",
|
||||
"-g",
|
||||
"802-11-wireless.powersave",
|
||||
"connection",
|
||||
"show",
|
||||
"uuid",
|
||||
identity["connection"],
|
||||
]
|
||||
)
|
||||
if policy not in ("default", "disable", "0", "2"):
|
||||
raise RuntimeError("Explicit foreign power policy preserved")
|
||||
original = power(root.name)
|
||||
if original[2] not in (0, 1):
|
||||
raise RuntimeError("Power-saving state not established")
|
||||
found.append({"interface": root.name, "identity": identity, "original": list(original)})
|
||||
if len(found) != 1:
|
||||
raise RuntimeError("Exactly one supported adapter is required")
|
||||
return found
|
||||
|
||||
|
||||
def idle():
|
||||
# Same admitted local UID as the shipped installer reader, GET only.
|
||||
sys.path.insert(0, "/usr/lib/mission-core-node")
|
||||
from can_maintenance import SOCKETS, probe
|
||||
|
||||
view = probe(SOCKETS["vesc"], "/observe", legacy=True)
|
||||
devices = view.get("devices", [])
|
||||
if (
|
||||
view.get("state") not in ("observing", "stopped")
|
||||
or view.get("control_active") is True
|
||||
or view.get("release_confirmed") is False
|
||||
or len(devices) != 2
|
||||
or any(
|
||||
d.get("age_ms", 1e9) > 500
|
||||
or d.get("values", {}).get("erpm") != 0
|
||||
or d.get("values", {}).get("duty") != 0
|
||||
for d in devices
|
||||
)
|
||||
):
|
||||
raise RuntimeError("Fresh stationary inactive rover required")
|
||||
|
||||
|
||||
def trusted_root():
|
||||
ROOT.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
info = ROOT.lstat()
|
||||
if not stat.S_ISDIR(info.st_mode) or info.st_uid != 0 or info.st_mode & 0o077:
|
||||
raise RuntimeError("Unsafe trial state directory")
|
||||
|
||||
|
||||
def save(value):
|
||||
# Own lock serializes fixed file names. Refuse foreign files/symlinks.
|
||||
temporary = ROOT / "state.new"
|
||||
fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600)
|
||||
try:
|
||||
with os.fdopen(fd, "w") as out:
|
||||
json.dump(value, out)
|
||||
out.flush()
|
||||
os.fsync(out.fileno())
|
||||
os.replace(temporary, STATE)
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def read_state():
|
||||
if not STATE.exists() and not STATE.is_symlink():
|
||||
return None
|
||||
info = STATE.lstat()
|
||||
if (
|
||||
not stat.S_ISREG(info.st_mode)
|
||||
or info.st_uid != 0
|
||||
or info.st_mode & 0o077
|
||||
or info.st_size > 16384
|
||||
):
|
||||
raise RuntimeError("Unsafe trial state")
|
||||
value = json.loads(STATE.read_text())
|
||||
if value.get("schema") != "missioncore.wifi-latency-trial/v1":
|
||||
raise RuntimeError("Unknown trial state")
|
||||
return value
|
||||
|
||||
|
||||
def restore(value):
|
||||
if value["state"] == "restored":
|
||||
return value
|
||||
if value["boot_id"] != Path("/proc/sys/kernel/random/boot_id").read_text().strip():
|
||||
raise RuntimeError("Different boot; automatic restoration refused")
|
||||
idle() # Never re-enable power saving during another operator's control.
|
||||
for item in value["adapters"]:
|
||||
name = item["interface"]
|
||||
if fingerprint(name) != item["identity"]:
|
||||
raise RuntimeError("Interface or connection changed; preserve newer settings")
|
||||
current = power(name)
|
||||
if list(current) == item["original"]:
|
||||
continue
|
||||
if current[2] != 1:
|
||||
raise RuntimeError("Another power setting replaced the trial; preserved")
|
||||
power(name, tuple(item["original"]))
|
||||
if power(name)[2] != item["original"][2]:
|
||||
raise RuntimeError("Original power state not restored")
|
||||
value.update(state="restored", restored_at=time.time())
|
||||
save(value)
|
||||
return value
|
||||
|
||||
|
||||
def trial(adapters):
|
||||
idle()
|
||||
previous = read_state()
|
||||
if previous and previous["state"] != "restored":
|
||||
raise RuntimeError("Previous trial requires restoration")
|
||||
value = {
|
||||
"schema": "missioncore.wifi-latency-trial/v1",
|
||||
"state": "prepared",
|
||||
"boot_id": Path("/proc/sys/kernel/random/boot_id").read_text().strip(),
|
||||
"started_at": time.time(),
|
||||
"duration_s": DURATION,
|
||||
"adapters": adapters,
|
||||
"motor_commands": False,
|
||||
"persistent_network_changes": False,
|
||||
}
|
||||
save(value) # Journal original state BEFORE the first ioctl.
|
||||
try:
|
||||
for item in adapters:
|
||||
if item["original"][2] == 0:
|
||||
power(item["interface"], OFF)
|
||||
if power(item["interface"])[2] != 1:
|
||||
raise RuntimeError("Power saving still enabled")
|
||||
value.update(state="running", applied_at=time.time())
|
||||
save(value)
|
||||
print(
|
||||
json.dumps({"state": "running", "duration_s": DURATION, "power_saving": False}),
|
||||
flush=True,
|
||||
)
|
||||
deadline = time.monotonic() + DURATION
|
||||
while time.monotonic() < deadline:
|
||||
idle() # Passive-only qualification. Never starts or stops control.
|
||||
if any(fingerprint(i["interface"]) != i["identity"] for i in adapters):
|
||||
raise RuntimeError("Connection changed during qualification")
|
||||
time.sleep(min(2, max(0, deadline - time.monotonic())))
|
||||
finally:
|
||||
restore(value)
|
||||
return value
|
||||
|
||||
|
||||
def interrupted(_signal, _frame):
|
||||
raise RuntimeError("Trial interrupted; restoring original state")
|
||||
|
||||
|
||||
def main():
|
||||
if sys.argv[1:] == ["--inspect"]:
|
||||
print(json.dumps({"profile": "ubuntu-24.04-amd64-bcm4331-wl/1", "adapters": inspect()}))
|
||||
return
|
||||
if os.geteuid() != 0 or sys.argv[1:] not in (["--trial"], ["--restore"]):
|
||||
raise SystemExit("Use the installed Wi-Fi latency qualification service")
|
||||
os.environ.clear()
|
||||
os.environ.update(ENV)
|
||||
os.umask(0o077)
|
||||
trusted_root()
|
||||
fd = os.open(ROOT / "lock", os.O_WRONLY | os.O_CREAT | os.O_NOFOLLOW, 0o600)
|
||||
with os.fdopen(fd, "w") as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
if sys.argv[1] == "--restore":
|
||||
value = read_state()
|
||||
if value:
|
||||
print(json.dumps(restore(value)))
|
||||
return
|
||||
signal.signal(signal.SIGTERM, interrupted)
|
||||
signal.signal(signal.SIGINT, interrupted)
|
||||
print(json.dumps(trial(inspect())))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -3,6 +3,7 @@ import { ActivityIndicator, Button, ConfirmationModal, Select, SettingsCard, Sta
|
||||
import { request } from "./api";
|
||||
|
||||
interface CoreState {
|
||||
network_profile?: {provider:string;phase:string;error?:string;tailscale_endpoint?:string};
|
||||
phase: "unpaired" | "inviting" | "pending" | "paired" | "revoked";
|
||||
connection: string; node_id: string; last_seen: number; notice: string; addresses: string[];
|
||||
invitation?: { id: string; endpoint: string; expires_at: number };
|
||||
@@ -65,6 +66,12 @@ export function CoreConnectionView({ failure }: { failure: (error: unknown) => v
|
||||
{notice && <p role="status" className="node-note">{notice}</p>}
|
||||
</>}
|
||||
</SettingsCard>
|
||||
{paired&&value?.network_profile&&<SettingsCard title="Связь с Core" description="Настройки применяются к этому БК из Mission Core: Парк → Бортовой компьютер → Связь с Core.">
|
||||
<StatusBadge tone={value.connection==='online'?'success':'neutral'}>{value.network_profile.provider==='wireguard'?'WireGuard · VPS':'Tailscale'}</StatusBadge>
|
||||
{['preparing','verifying'].includes(value.network_profile.phase)&&<p className="node-note">Проверяем новое подключение. При отсутствии подтверждения вернётся прежний профиль.</p>}
|
||||
{value.network_profile.error&&<p role="status" className="node-note">{value.network_profile.error}</p>}
|
||||
{value.network_profile.provider==='wireguard'&&<Button disabled={pending||!value.network_profile.tailscale_endpoint||['preparing','verifying'].includes(value.network_profile.phase)} onClick={async()=>{setPending(true);try{await request('/api/network/profile/tailscale','POST',{});await refresh();}catch(e){failure(e);}finally{setPending(false);}}}>Восстановить Tailscale</Button>}
|
||||
</SettingsCard>}
|
||||
<ConfirmationModal open={remove} title={value?.binding ? "Отозвать привязку к Core?" : "Отменить приглашение?"} description={value?.binding ? "Этот БК прекратит соединение с Core. Аппарат останется в его реестре; отзыв будет доставлен при доступности сети." : "Этот код больше нельзя будет использовать. Вы сможете создать новый."} confirmLabel="Отозвать" cancelLabel="Отмена" danger onClose={() => setRemove(false)} onConfirm={async () => { try { await request("/api/core", "DELETE"); setCode(""); setNotice(""); await refresh(); setRemove(false); } catch (error) { failure(error); throw error; } }} />
|
||||
</div>;
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import {usbCanSensorUi} from '../../../../plugins/usb-can/frontend/src/plugin';
|
||||
import {vescSensorUi} from '../../../../plugins/vesc/frontend/src/plugin';
|
||||
import {xgridsK1SensorUi} from '../../../../plugins/xgrids-k1/frontend/src/sensors/plugin';
|
||||
import {insta360X4SensorUi} from '../../../../plugins/insta360-x4/frontend/src/plugin';
|
||||
@@ -5,9 +6,10 @@ import {createIsolatedRerunHost} from '../../../control-station/src/components/r
|
||||
import {SensorWorkspace} from '../../../../packages/sensor-ui/src/SensorWorkspace';
|
||||
import type {SensorTransport} from '../../../../packages/sensor-ui/src/contracts';
|
||||
import {request,type Status} from './api';
|
||||
import {NodeRouters} from './NodeRouters';
|
||||
import {Button,Icon,SettingsCard} from '@nodedc/ui-react';
|
||||
import {createBoardLayoutStore} from '../../../../packages/sensor-ui/src/boardLayout';
|
||||
const layout=createBoardLayoutStore({read:()=>request('/api/presentation/board-layout'),patch:(section,open)=>request('/api/presentation/board-layout','PATCH',{section,open})});
|
||||
const configurationArchive:NonNullable<SensorTransport['configurationArchive']>={list:(device,before)=>request(`/api/device-configurations/${encodeURIComponent(device)}${before?'?before='+encodeURIComponent(before):''}`),read:(device,version)=>request(`/api/device-configurations/${encodeURIComponent(device)}/${encodeURIComponent(version)}`)};
|
||||
const transport:SensorTransport={configurationArchive,localPreview:{open:(command,signal)=>fetch("/api/devices/preview",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify(command),signal}),read:(peer,after,signal)=>fetch("/api/devices/preview/read",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify({peer_id:peer,after}),signal})},enrollment:{state:()=>request("/api/devices/enrollment"),submit:value=>request("/api/devices/enrollment/operations","POST",value),operation:id=>request("/api/devices/enrollment/operations/"+encodeURIComponent(id))},subscribe:(receive,unavailable)=>{const events=new EventSource('/api/devices/events');events.onmessage=e=>{try{receive(JSON.parse(e.data));}catch{unavailable();}};events.onerror=unavailable;return()=>events.close();},inventory:()=>request('/api/devices'),submit:value=>request('/api/devices/operations','POST',value),operation:id=>request('/api/devices/operations/'+encodeURIComponent(id))};
|
||||
export function NodeSensors({value,openSettings}:{value:Status;openSettings:()=>void}){return <SensorWorkspace board={{layout,description:value.name,computer:<SettingsCard title={value.name} description={value.host.hostname}><dl className="node-facts"><div><dt>Бортовой компьютер</dt><dd>{value.node_id}</dd></div><div><dt>Операционная система</dt><dd>{value.host.os}</dd></div><div><dt>Архитектура</dt><dd>{value.host.architecture}</dd></div><div><dt>Процессоры</dt><dd>{value.host.cpus}</dd></div><div><dt>Память</dt><dd>{value.host.memory_kib?`${(value.host.memory_kib/1048576).toFixed(1)} ГиБ`:"Нет сведений"}</dd></div><div><dt>Mission Core Node</dt><dd>{value.version}</dd></div></dl><Button onClick={openSettings}><Icon name="settings"/>Подготовка среды</Button></SettingsCard>}} contributions={[xgridsK1SensorUi,insta360X4SensorUi,vescSensorUi]} createRerunHost={createIsolatedRerunHost} transport={transport}/>;}
|
||||
const transport:SensorTransport={liveTelemetry:signal=>request('/api/devices/telemetry','GET',undefined,signal),configurationArchive,localPreview:{open:(command,signal)=>fetch("/api/devices/preview",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify(command),signal}),read:(peer,after,signal)=>fetch("/api/devices/preview/read",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify({peer_id:peer,after}),signal})},enrollment:{state:()=>request("/api/devices/enrollment"),submit:value=>request("/api/devices/enrollment/operations","POST",value),operation:id=>request("/api/devices/enrollment/operations/"+encodeURIComponent(id))},subscribe:(receive,unavailable)=>{const events=new EventSource('/api/devices/events');events.onmessage=e=>{try{receive(JSON.parse(e.data));}catch{unavailable();}};events.onerror=unavailable;return()=>events.close();},inventory:signal=>request('/api/devices','GET',undefined,signal),submit:value=>request('/api/devices/operations','POST',value),operation:id=>request('/api/devices/operations/'+encodeURIComponent(id))};
|
||||
export function NodeSensors({value,openSettings}:{value:Status;openSettings:()=>void}){return <div className="sensor-content"><NodeRouters/><SensorWorkspace board={{layout,description:value.name,computer:<SettingsCard title={value.name} description={value.host.hostname}><dl className="node-facts"><div><dt>Бортовой компьютер</dt><dd>{value.node_id}</dd></div><div><dt>Операционная система</dt><dd>{value.host.os}</dd></div><div><dt>Архитектура</dt><dd>{value.host.architecture}</dd></div><div><dt>Процессоры</dt><dd>{value.host.cpus}</dd></div><div><dt>Память</dt><dd>{value.host.memory_kib?`${(value.host.memory_kib/1048576).toFixed(1)} ГиБ`:"Нет сведений"}</dd></div><div><dt>Mission Core Node</dt><dd>{value.version}</dd></div></dl><Button onClick={openSettings}><Icon name="settings"/>Подготовка среды</Button></SettingsCard>}} contributions={[xgridsK1SensorUi,insta360X4SensorUi,vescSensorUi,usbCanSensorUi]} createRerunHost={createIsolatedRerunHost} transport={transport}/></div>;}
|
||||
|
||||
@@ -27,8 +27,8 @@ export function desktopAction(action: DesktopAction): boolean {
|
||||
return true;
|
||||
}
|
||||
export function desktopLogin(): boolean { return desktopAction("authorize"); }
|
||||
export async function request<T>(path: string, method = "GET", body?: unknown): Promise<T> {
|
||||
const res = await fetch(path, { method, credentials: "same-origin", cache: "no-store", headers: body === undefined ? {} : {"Content-Type": "application/json"}, body: body === undefined ? undefined : JSON.stringify(body), signal: AbortSignal.timeout(10000) }).catch(() => { throw new Error("БК не ответил вовремя. Обновите сведения; действие могло продолжиться на борту."); });
|
||||
export async function request<T>(path: string, method = "GET", body?: unknown, signal?:AbortSignal): Promise<T> {
|
||||
const res = await fetch(path, { method, credentials: "same-origin", cache: "no-store", headers: body === undefined ? {} : {"Content-Type": "application/json"}, body: body === undefined ? undefined : JSON.stringify(body), signal: signal?AbortSignal.any([signal,AbortSignal.timeout(10000)]):AbortSignal.timeout(10000) }).catch(() => { throw new Error("БК не ответил вовремя. Обновите сведения; действие могло продолжиться на борту."); });
|
||||
if (!res.ok) {
|
||||
const error = await res.json().catch(() => ({}));
|
||||
throw new APIError(error.error ?? "Не удалось выполнить запрос к ноде", res.status);
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
# CAN maintenance during Node installation
|
||||
|
||||
The standard Node owner installer owns this transition on Ubuntu 24.04 amd64.
|
||||
The USB adapter can remain connected. No device firmware, motor configuration,
|
||||
control route, current setpoint or motion command is changed by maintenance.
|
||||
|
||||
## Admission and sequencing
|
||||
|
||||
1. The installer serializes maintenance with a root-owned lock under
|
||||
`/run/mission-core-node-maintenance`.
|
||||
2. The VESC service admits maintenance only when no client operation, live
|
||||
control lease, control worker, motor procedure, firmware operation, pending
|
||||
configuration/limits/code restoration, or Sample Data capture owns it.
|
||||
Active control is rejected before closing admission; it is not stopped to
|
||||
force an update through.
|
||||
3. A condition-protected gate closes new client and observer/discovery work.
|
||||
Already admitted passive callbacks drain within five seconds. State is
|
||||
checked again; transport links are closed and old device generations retired.
|
||||
This path never invokes current, duty, RPM, calibration or firmware RPCs.
|
||||
4. Only then does the installer stop the VESC service. The CAN owner must confirm
|
||||
that every channel has stopped; an independent analyser/transmit job is not
|
||||
silently cancelled. CAN is stopped before APT/dpkg replaces runtime files.
|
||||
5. A root-owned volatile marker keeps newly started services in maintenance
|
||||
throughout package configuration. The owner installer removes it and leaves
|
||||
maintenance after the transaction, including ordinary failure cleanup.
|
||||
Previously stopped services are started in CAN-before-VESC order; running
|
||||
services are not redundantly restarted. A clean installation also releases
|
||||
newly created services even though no predecessor existed.
|
||||
6. Discovery/observation resumes with new connection generations. VESC remote
|
||||
control must be primed again through its normal operator path; no prior
|
||||
motor command or input lease is replayed.
|
||||
|
||||
Both services expose only root-peer Unix-socket `/maintenance/enter` and
|
||||
`/maintenance/leave` operations. They are not public HTTP, Core UI, arbitrary
|
||||
command or controller-command endpoints. The existing service users, network
|
||||
namespace and device permissions remain unchanged. `GET /prepare-safe` remains
|
||||
compatible with device preparation and package removal checks.
|
||||
|
||||
## Migration from the pre-maintenance runtime
|
||||
|
||||
The first transition uses the exact reviewed server SHA-256 identities carried
|
||||
in `apps/node-agent/packaging/can_maintenance.py`. Unknown predecessor code is
|
||||
not guessed or patched in place. For this bounded compatibility path, the
|
||||
installer relocates the old Unix socket into a root-controlled private directory,
|
||||
so normal Node clients cannot open another request. It waits out the old
|
||||
10-second socket read deadline plus bounded read admission and checks the Node
|
||||
operation journal and old service snapshots before stopping anything. Active
|
||||
control is checked before this fence as well. Recent Sample Data activity and
|
||||
unresolved hardware changes refuse the migration.
|
||||
|
||||
The old CAN bridge's expiring claims are allowed to close their channels; the
|
||||
old root `/prepare-safe` check must then pass. Failure restores the same socket
|
||||
inode when its original path is still vacant; a newly started service generation
|
||||
is never overwritten by an old socket. The compatibility path sends only
|
||||
inventory/observation/lifecycle queries, never an OperationRequest.
|
||||
|
||||
## Failure boundary and portability
|
||||
|
||||
A normal Python/APT failure runs maintenance cleanup and records the result in
|
||||
`report.json`. An unknown service state fails closed. A hard process kill or
|
||||
power loss is not represented as successful recovery: an orphaned marker/fence
|
||||
blocks another installer until reconciled; `/run` is volatile across reboot.
|
||||
There is deliberately no timer that re-enables commands during a long install.
|
||||
No installer kills APT/dpkg to meet a polling deadline.
|
||||
|
||||
The common gate comes from the plugin SDK and its exact bytes are included in
|
||||
both model payloads. The installer embeds its maintenance owner in the signed-off
|
||||
release content, and Node also ships that source. There are no manual board-only
|
||||
service edits, USB resets, extra packages or compiler requirements. Clean-OS
|
||||
branch behavior is covered by synthetic tests; a new Ubuntu installation was
|
||||
not exercised in this task.
|
||||
|
||||
## Evidence
|
||||
|
||||
Private qualification, installation receipt, immutable release hashes and Core
|
||||
read acceptance are recorded under `outputs/can-maintenance-20261022`.
|
||||
No movement, new sample capture, new diagnostic logging or firmware flashing is
|
||||
part of this acceptance. The separate Hall UI does not claim raw H1/H2/H3 data:
|
||||
stock firmware 5.02 does not expose those inputs through the admitted passive API.
|
||||
|
||||
## Lost Hall measurement reply (recovery v1)
|
||||
|
||||
The owner installer also reconciles an abandoned `COMM_DETECT_HALL_FOC`
|
||||
operation on the explicitly qualified FW 5.02 / 75_300_R2 profile. This is not
|
||||
calibration recovery or a generic pending-file exemption. It supports only the
|
||||
reviewed service/procedure source hashes and a terminal receipt recording lost
|
||||
completion with no configuration write. Other pending changes still refuse it.
|
||||
|
||||
Before recovery, active control/procedures are refused and the existing socket
|
||||
is fenced; admitted requests drain. At least 60 seconds must have elapsed since
|
||||
this bounded native procedure started. Time alone is insufficient: the exact
|
||||
controller set/firmware identity and both raw configuration hashes must match
|
||||
the pre-measurement backups. Three new reads per controller must show zero ERPM,
|
||||
low zero-output current/duty, no fault and no receiver pulses. Only the fixed
|
||||
configuration/telemetry/input read operations are allowed; no motion, release,
|
||||
configuration write or replay is sent. Any unavailable or changed evidence
|
||||
leaves the interlock intact. This does not claim to measure physical standstill.
|
||||
|
||||
A durable `hall_recovered_<operation>.json` stores the original pending record,
|
||||
configuration hashes and fresh evidence before removing the pending marker.
|
||||
The original failed receipt is preserved, and the outcome remains
|
||||
`measurement-result-unknown`. The ordinary service maintenance admission guard
|
||||
must then pass before it is stopped. On update completion normal observation
|
||||
resumes; a new measurement requires a separate explicitly requested operation.
|
||||
The installer ships this recovery source on every supported installation; no
|
||||
board-specific identifiers, manual file deletion or service override is needed.
|
||||
@@ -16,7 +16,7 @@ def main():
|
||||
parser.add_argument("--file", type=Path, required=True)
|
||||
parser.add_argument("--sha256", required=True)
|
||||
parser.add_argument("--version", required=True)
|
||||
parser.add_argument("--kind", choices=("node", "vps-arnavi"), required=True)
|
||||
parser.add_argument("--kind", choices=("node", "vps-arnavi", "vps-wireguard"), required=True)
|
||||
args = parser.parse_args()
|
||||
if not re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9]+)?", args.version):
|
||||
raise ValueError("Invalid release version")
|
||||
@@ -54,6 +54,11 @@ def main():
|
||||
else "Создайте в Node код приглашения и вставьте его в поле ниже.",
|
||||
],
|
||||
}
|
||||
if args.kind == "vps-wireguard":
|
||||
value.update(label="WireGuard для парка", os="Ubuntu Server 24.04 LTS · x86-64", instructions=[
|
||||
"Скопируйте пакет на VPS. Запустите: sudo python3 mission-core-wireguard-vps.pyz",
|
||||
"Дождитесь завершения установки. Файл подключения: /var/lib/ndc-wireguard-vps/mission-core-wireguard.json.",
|
||||
"Перенесите файл подключения на этот компьютер и загрузите его в настройках связи БК."])
|
||||
temporary = root / (args.kind + ".json.new")
|
||||
temporary.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n")
|
||||
temporary.chmod(0o600)
|
||||
|
||||
@@ -14,10 +14,11 @@ from k1link.web.fleet_api import local_operator
|
||||
|
||||
router = APIRouter(prefix="/api/v1/fleet/installers", tags=["installers"])
|
||||
Fleet = Annotated[FleetRegistry, Depends(local_operator)]
|
||||
KINDS = {"node", "vps-arnavi"}
|
||||
KINDS = {"node", "vps-arnavi", "vps-wireguard"}
|
||||
DOWNLOAD_NAMES = {
|
||||
"node": "mission-core-node-install.pyz",
|
||||
"vps-arnavi": "mission-core-vps-install.pyz",
|
||||
"vps-wireguard": "mission-core-wireguard-vps.pyz",
|
||||
}
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user