Package the adapter SDK boundary and runtime lifecycle. Confirm admitted CAN transactions, bound retained data and test failure paths with synthetic hardware.
159 lines
5.4 KiB
Python
159 lines
5.4 KiB
Python
"""Versioned, idempotent USB-CAN profile; no packages downloaded and no motor I/O."""
|
|
|
|
import fcntl
|
|
import hashlib
|
|
import json
|
|
import os
|
|
import platform
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
import uuid
|
|
from pathlib import Path
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
from runtime.discovery import discover
|
|
|
|
|
|
def atomic(path, value):
|
|
temp = path.with_suffix(".tmp")
|
|
temp.write_text(json.dumps(value, ensure_ascii=False))
|
|
temp.replace(path)
|
|
|
|
|
|
STATE = Path("/var/lib/mission-core-node-profiles/usb-can")
|
|
|
|
|
|
def prepare():
|
|
if os.geteuid() != 0 or sys.argv[1:]:
|
|
raise RuntimeError("Fixed system profile only")
|
|
release = platform.freedesktop_os_release()
|
|
if (release.get("ID"), release.get("VERSION_ID"), platform.machine()) != (
|
|
"ubuntu",
|
|
"24.04",
|
|
"x86_64",
|
|
):
|
|
raise RuntimeError("Ubuntu 24.04 amd64 required")
|
|
STATE.mkdir(mode=0o755, parents=True, exist_ok=True)
|
|
for directory in (STATE.parent, STATE):
|
|
info = directory.lstat()
|
|
if directory.is_symlink() or info.st_uid != 0 or info.st_mode & 0o022:
|
|
raise RuntimeError("Untrusted profile state")
|
|
lock = os.open(STATE / "prepare.lock", os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600)
|
|
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
report_previous = (
|
|
json.loads((STATE / "preparation.json").read_text())
|
|
if (STATE / "preparation.json").exists()
|
|
else {}
|
|
)
|
|
report = {
|
|
"schema": "missioncore.node.device-preparation/v1",
|
|
"model_id": "waveshare.usb-can-fd-b",
|
|
"version": "0.2.7",
|
|
"run_id": uuid.uuid4().hex,
|
|
"started_at": time.time(),
|
|
"monotonic_started": time.monotonic(),
|
|
"state": "running",
|
|
"steps": [],
|
|
}
|
|
|
|
def publish():
|
|
atomic(STATE / "preparation.json", report)
|
|
os.chmod(STATE / "preparation.json", 0o644)
|
|
|
|
def run(name, label, args):
|
|
step = {"id": name, "label": label, "state": "running"}
|
|
report["steps"].append(step)
|
|
publish()
|
|
result = subprocess.run(
|
|
args,
|
|
capture_output=True,
|
|
timeout=45,
|
|
env={"PATH": "/usr/sbin:/usr/bin:/sbin:/bin", "LANG": "C.UTF-8"},
|
|
)
|
|
step["state"] = "complete" if result.returncode == 0 else "error"
|
|
publish()
|
|
if result.returncode:
|
|
raise RuntimeError("Не завершён этап: " + label)
|
|
|
|
try:
|
|
import pwd
|
|
|
|
try:
|
|
pwd.getpwnam("mission-core-usb-can")
|
|
except KeyError:
|
|
run(
|
|
"account",
|
|
"Подготовка доступа",
|
|
[
|
|
"/usr/sbin/adduser",
|
|
"--system",
|
|
"--group",
|
|
"--home",
|
|
"/var/lib/mission-core-usb-can",
|
|
"--no-create-home",
|
|
"--disabled-login",
|
|
"mission-core-usb-can",
|
|
],
|
|
)
|
|
run(
|
|
"native",
|
|
"Проверка USB-CAN Tool",
|
|
[
|
|
"/usr/sbin/runuser",
|
|
"-u",
|
|
"mission-core-usb-can",
|
|
"--",
|
|
"/usr/bin/python3",
|
|
"-I",
|
|
"/usr/lib/mission-core-usb-can/native_check.py",
|
|
],
|
|
)
|
|
source = Path("/usr/share/mission-core-node/profiles/usb-can/70-mission-core-usb-can.rules")
|
|
rules = source.read_bytes()
|
|
report["udev_sha256"] = hashlib.sha256(rules).hexdigest()
|
|
target = Path("/etc/udev/rules.d/70-mission-core-usb-can.rules")
|
|
if target.is_symlink():
|
|
raise RuntimeError("Untrusted udev destination")
|
|
if target.exists() and target.read_bytes() != rules:
|
|
previous = report_previous.get("udev_sha256")
|
|
if hashlib.sha256(target.read_bytes()).hexdigest() != previous:
|
|
raise RuntimeError("Существующее USB-правило изменено вне профиля; сохранено.")
|
|
target.write_bytes(rules)
|
|
target.chmod(0o644)
|
|
run("rules", "Настройка USB-доступа", ["/usr/bin/udevadm", "control", "--reload-rules"])
|
|
for i, device in enumerate(discover()):
|
|
run(
|
|
"usb" + str(i),
|
|
"Применение USB-доступа",
|
|
[
|
|
"/usr/bin/udevadm",
|
|
"trigger",
|
|
"--action=change",
|
|
"/sys/bus/usb/devices/" + device.usb,
|
|
],
|
|
)
|
|
run("settle", "Проверка USB-доступа", ["/usr/bin/udevadm", "settle", "--timeout=10"])
|
|
run(
|
|
"enable",
|
|
"Подготовка службы",
|
|
["/usr/bin/systemctl", "enable", "mission-core-usb-can.service"],
|
|
)
|
|
run(
|
|
"runtime",
|
|
"Обнаружение адаптеров",
|
|
["/usr/bin/systemctl", "restart", "mission-core-usb-can.service"],
|
|
)
|
|
report["state"] = "complete"
|
|
except (OSError, RuntimeError, subprocess.SubprocessError) as error:
|
|
report.update(state="error", message=str(error)[:300])
|
|
finally:
|
|
report["duration_seconds"] = time.monotonic() - report["monotonic_started"]
|
|
publish()
|
|
os.close(lock)
|
|
return report["state"] == "complete"
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(0 if prepare() else 1)
|