Files
NODEDC_MISSION_CORE/plugins/vesc/runtime/qml_session.py
T
DCCONSTRUCTIONS f32c7b400b feat(vesc): extend motor diagnostics, configuration and transport recovery
Add firmware and extension catalogues, configuration transactions, sample review and QML diagnostics. Preserve explicit authority, bounded retries and stop recovery in motor transport.
2026-10-29 09:09:59 +03:00

163 lines
5.9 KiB
Python

"""One bounded Qt Quick child with no device FD; broker intents are parent-validated."""
import base64
import json
import os
import select
import subprocess
import tempfile
import time
from pathlib import Path
from .motor_test import Rejected
def environment():
group = Path("/sys/fs/cgroup") / Path("/proc/self/cgroup").read_text().strip().split("::", 1)[
1
].lstrip("/")
maximum = (group / "memory.max").read_text().strip()
if (
maximum == "max"
or int(maximum) < 1024**3
or int((group / "memory.current").read_text()) > 384 * 1024**2
):
raise Rejected("Недостаточно свободной памяти в службе для QML.")
root = Path("/usr/lib/mission-core-vesc/native")
return root, {
"PATH": "/usr/bin:/bin",
"LANG": "C",
"LC_ALL": "C",
"HOME": "/nonexistent",
"LD_LIBRARY_PATH": str(root / "lib"),
"QT_PLUGIN_PATH": str(root / "plugins"),
"QT_QPA_PLATFORM": "offscreen",
"QT_QUICK_BACKEND": "software",
"QML_DISABLE_DISK_CACHE": "1",
"QV4_FORCE_INTERPRETER": "1",
}
def checked_frame(result):
if (
not isinstance(result, dict)
or result.get("hardware_access") is not False
or type(result.get("snapshot_only")) is not bool
or result["snapshot_only"] == (result.get("broker") is True)
or result.get("sandbox_verified") is not True
):
raise Rejected("Не подтверждена изоляция QML.")
if not result.get("ok"):
raise Rejected(str(result.get("error", "Qt Quick не построил кадр."))[:320])
raw = base64.b64decode(result["png"], validate=True)
if (
len(raw) > 512 * 1024
or not raw.startswith(b"\x89PNG\r\n\x1a\n")
or (result["width"], result["height"]) != (640, 480)
):
raise Rejected("Некорректный кадр QML.")
return {**result, "rendered": True}
class QmlSession:
def __init__(self, request):
self.process = None
self.directory = None
self.buffer = b""
self.at = self.used = time.monotonic()
self.count = 0
self.broker = request.get("broker", False)
root, env = environment()
try:
self.directory = tempfile.TemporaryDirectory(
prefix="qml-", dir="/run/mission-core-vesc"
)
env["XDG_RUNTIME_DIR"] = self.directory.name
self.process = subprocess.Popen(
[str(root / "bin/mission-core-vesc-qml-preview")],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
env=env,
close_fds=True,
bufsize=0,
)
os.set_blocking(self.process.stdin.fileno(), False)
os.set_blocking(self.process.stdout.fileno(), False)
self.initial = self.exchange({**request, "interactive": True})
except BaseException:
self.close()
raise
def alive(self):
return self.process is not None and self.process.poll() is None
def expired(self):
return (
not self.alive()
or time.monotonic() - self.at >= 300
or time.monotonic() - self.used >= 60
or self.count >= 240
)
def exchange(self, request):
deadline = time.monotonic() + 6
try:
raw = json.dumps(request, allow_nan=False).encode() + b"\n"
if len(raw) > 512 * 1024:
raise ValueError("QML request exceeds bound")
while raw:
if (
not self.alive()
or not select.select(
[], [self.process.stdin], [], max(0, deadline - time.monotonic())
)[1]
):
raise TimeoutError("QML input timed out")
size = os.write(self.process.stdin.fileno(), raw[:4096])
if size <= 0:
raise OSError("QML input closed")
raw = raw[size:]
while b"\n" not in self.buffer:
if (
not self.alive()
or not select.select(
[self.process.stdout], [], [], max(0, deadline - time.monotonic())
)[0]
):
raise TimeoutError("QML frame timed out")
chunk = os.read(self.process.stdout.fileno(), 65536)
if not chunk:
raise OSError("QML process exited")
self.buffer += chunk
if len(self.buffer) > 800 * 1024:
raise ValueError("QML response exceeds bound")
line, self.buffer = self.buffer.split(b"\n", 1)
result = checked_frame(json.loads(line))
if (
result.get("interactive") is not True
or (result.get("broker") is True) != self.broker
):
raise ValueError("Interactive QML protocol missing")
self.used = time.monotonic()
self.count += 1
return result
except (ValueError, KeyError, OSError, TimeoutError, Rejected) as error:
self.close()
raise Rejected("Сеанс QML завершён: " + str(error)[:240]) from error
def close(self):
if self.process:
if self.alive():
self.process.kill()
try:
self.process.wait(timeout=2)
except subprocess.TimeoutExpired as error:
raise Rejected("Прежний процесс QML ещё завершается.") from error
for stream in (self.process.stdin, self.process.stdout):
if stream:
stream.close()
if self.directory:
self.directory.cleanup()
self.directory = None