feat(fleet): preserve operator VESC integration before final driver merge
This commit is contained in:
@@ -0,0 +1 @@
|
||||
"""VESC configuration storage on Core; serial execution remains on the board."""
|
||||
@@ -0,0 +1,131 @@
|
||||
"""Immutable VESC backups, shared by Core and the packaged board plugin.
|
||||
|
||||
Storage has no hardware or restore authority. Versions survive transient
|
||||
operation receipt cleanup, reboots and controller disconnects.
|
||||
"""
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import sqlite3
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from contextlib import contextmanager
|
||||
|
||||
|
||||
def validate(value):
|
||||
if not isinstance(value, dict) or len(json.dumps(value)) > 40000:
|
||||
raise ValueError("Invalid configuration backup")
|
||||
if value.get("schema") != "missioncore.vesc.config-backup/v1":
|
||||
raise ValueError("Unsupported backup format")
|
||||
if not re.fullmatch(r"op_[0-9a-f]{32}", value.get("operation_id", "")):
|
||||
raise ValueError("Invalid backup identity")
|
||||
identity = value["identity"]
|
||||
uid = identity["uuid"]
|
||||
if not re.fullmatch(r"[0-9a-f]{24}", uid) or int(uid, 16) == 0:
|
||||
raise ValueError("Invalid controller identity")
|
||||
expected = "vesc_" + hashlib.sha256(("uuid:" + uid).encode()).hexdigest()[:32]
|
||||
if value.get("device_id") != expected:
|
||||
raise ValueError("Backup controller mismatch")
|
||||
if datetime.fromisoformat(value["observed_at"].replace("Z", "+00:00")).tzinfo is None:
|
||||
raise ValueError("Backup time is missing its timezone")
|
||||
if set(value["configs"]) != {"motor", "application"}:
|
||||
raise ValueError("Incomplete backup")
|
||||
for key, command in (("motor", 14), ("application", 17)):
|
||||
blob = value["configs"][key]
|
||||
data = base64.b64decode(blob["payload"], validate=True)
|
||||
if (blob.get("encoding") != "base64" or not 5 <= len(data) <= 10000
|
||||
or data[0] != command or blob["bytes"] != len(data)
|
||||
or blob["sha256"] != hashlib.sha256(data).hexdigest()
|
||||
or blob["signature_hex"] != data[1:5].hex()):
|
||||
raise ValueError("Backup integrity check failed")
|
||||
return value
|
||||
|
||||
|
||||
def metadata(sequence, value):
|
||||
return {"sequence": sequence, "id": value["operation_id"], "device_id": value["device_id"],
|
||||
"observed_at": value["observed_at"], "firmware": value["identity"]["version"],
|
||||
"configs": {key: {"sha256": blob["sha256"], "bytes": blob["bytes"]}
|
||||
for key, blob in value["configs"].items()}}
|
||||
|
||||
|
||||
class Archive:
|
||||
def __init__(self, root):
|
||||
root = Path(root)
|
||||
root.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
if root.is_symlink() or root.stat().st_mode & 0o077:
|
||||
raise ValueError("Configuration archive must be private")
|
||||
self.path = root / "configurations.sqlite3"
|
||||
if self.path.is_symlink():
|
||||
raise ValueError("Invalid configuration archive path")
|
||||
with self.connect() as db:
|
||||
db.execute("CREATE TABLE IF NOT EXISTS versions (seq INTEGER PRIMARY KEY AUTOINCREMENT, "
|
||||
"node TEXT NOT NULL, device TEXT NOT NULL, operation TEXT NOT NULL, "
|
||||
"body TEXT NOT NULL, UNIQUE(node,device,operation))")
|
||||
self.path.chmod(0o600)
|
||||
|
||||
@contextmanager
|
||||
def connect(self):
|
||||
db = sqlite3.connect(self.path, timeout=10)
|
||||
try:
|
||||
db.execute("PRAGMA synchronous=FULL")
|
||||
with db:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
def add(self, node, value):
|
||||
validate(value)
|
||||
body = json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
|
||||
with self.connect() as db:
|
||||
existing = db.execute("SELECT body FROM versions WHERE node=? AND device=? AND operation=?",
|
||||
(node, value["device_id"], value["operation_id"])).fetchone()
|
||||
if existing:
|
||||
if existing[0] != body:
|
||||
raise ValueError("An immutable configuration version changed")
|
||||
return
|
||||
db.execute("INSERT INTO versions(node,device,operation,body) VALUES(?,?,?,?)",
|
||||
(node, value["device_id"], value["operation_id"], body))
|
||||
|
||||
def listing(self, node, device, before=0):
|
||||
if type(before) is not int or before < 0:
|
||||
raise ValueError("Invalid archive cursor")
|
||||
with self.connect() as db:
|
||||
rows = db.execute("SELECT seq,body FROM versions WHERE node=? AND device=? "
|
||||
"AND (?=0 OR seq<?) ORDER BY seq DESC LIMIT 51",
|
||||
(node, device, before, before)).fetchall()
|
||||
return {"items": [metadata(seq, json.loads(body)) for seq, body in rows[:50]],
|
||||
"next": str(rows[49][0]) if len(rows) > 50 else None}
|
||||
|
||||
def read(self, node, device, operation):
|
||||
with self.connect() as db:
|
||||
row = db.execute("SELECT body FROM versions WHERE node=? AND device=? AND operation=?",
|
||||
(node, device, operation)).fetchone()
|
||||
if row is None:
|
||||
raise ValueError("Configuration version not found")
|
||||
return json.loads(row[0])
|
||||
|
||||
def export(self, node, after):
|
||||
if type(after) is not int or after < 0:
|
||||
raise ValueError("Invalid archive cursor")
|
||||
with self.connect() as db:
|
||||
rows = db.execute("SELECT seq,body FROM versions WHERE node=? AND seq>? ORDER BY seq LIMIT 4",
|
||||
(node, after)).fetchall()
|
||||
return {"after": after, "items": [{"sequence": seq, "backup": json.loads(body)} for seq, body in rows],
|
||||
"next": rows[-1][0] if rows else after}
|
||||
|
||||
def receive(self, node, batch):
|
||||
if not isinstance(batch, dict) or len(json.dumps(batch)) > 165000:
|
||||
raise ValueError("Invalid archive batch")
|
||||
items, last = batch.get("items"), batch.get("after")
|
||||
if not isinstance(items, list) or len(items) > 4 or type(last) is not int or last < 0:
|
||||
raise ValueError("Invalid archive batch")
|
||||
for row in items:
|
||||
seq = row["sequence"]
|
||||
if type(seq) is not int or seq <= last:
|
||||
raise ValueError("Invalid archive sequence")
|
||||
self.add(node, row["backup"])
|
||||
last = seq
|
||||
if batch.get("next") != last:
|
||||
raise ValueError("Invalid archive acknowledgement")
|
||||
return last
|
||||
Reference in New Issue
Block a user