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:
DCCONSTRUCTIONS
2026-10-29 09:10:02 +03:00
parent fa8bde584f
commit 755a124bd8
36 changed files with 2322 additions and 59 deletions
@@ -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))