fix(installer): coordinate K1 maintenance with active recordings
This commit is contained in:
@@ -18,6 +18,9 @@ from pathlib import Path
|
||||
if "CanMaintenance" not in globals():
|
||||
from can_maintenance import CanMaintenance
|
||||
|
||||
if "K1Maintenance" not in globals():
|
||||
from k1_maintenance import K1Maintenance
|
||||
|
||||
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")
|
||||
@@ -311,6 +314,7 @@ def main():
|
||||
return result.stdout.decode().strip()
|
||||
|
||||
maintenance = CanMaintenance(report.setdefault("can_maintenance", {}))
|
||||
k1_maintenance = K1Maintenance(report.setdefault("k1_maintenance", {}))
|
||||
publish()
|
||||
try:
|
||||
report["legacy_pager_recovery"] = finish_legacy_monitor_pager()
|
||||
@@ -330,6 +334,7 @@ def main():
|
||||
],
|
||||
)
|
||||
maintenance.begin()
|
||||
k1_maintenance.begin()
|
||||
report["interrupted_node_recovery"] = resume_interrupted_node(run, version)
|
||||
publish()
|
||||
# APT refuses package removal and downgrade without explicit flags.
|
||||
@@ -359,6 +364,8 @@ def main():
|
||||
)
|
||||
if installed != version + "\tinstall ok installed":
|
||||
raise RuntimeError("Версия установленного Node не подтверждена.")
|
||||
report["netbird_monitor"] = json.loads(run("netbird-monitor-policy", [
|
||||
"/usr/bin/python3", "-I", "/usr/lib/mission-core-node/netbird_monitor.py"]))
|
||||
report["x4_bundle"] = update_installed_x4(run)
|
||||
publish()
|
||||
run(
|
||||
@@ -404,6 +411,10 @@ def main():
|
||||
except Exception as error:
|
||||
report.update(state="error", error=str(error)[:500])
|
||||
finally:
|
||||
try:
|
||||
k1_maintenance.finish()
|
||||
except Exception as error:
|
||||
report.update(state="error", error=str(error)[:500])
|
||||
try:
|
||||
maintenance.finish()
|
||||
except Exception as error:
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
"""Retire a legacy K1 worker only after an explicit, completed local reset.
|
||||
|
||||
The old prepare-safe endpoint omits interrupted terminal acquisitions. This
|
||||
migration does not stop acquisition, edit evidence or resolve physical state.
|
||||
It proves operator retirement and closed evidence writers before service stop.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
if "probe" not in globals():
|
||||
from can_maintenance import MAINTENANCE_ROOT, probe
|
||||
|
||||
K1_LEGACY_BRIDGE = "3fb93fc296222b7dc21fc93d48263e0d16ebb86a71b2c53a80b82e0cf8723569"
|
||||
K1_SOCKET = Path("/run/mission-core-k1/driver.sock")
|
||||
K1_STATE = Path("/var/lib/mission-core-k1")
|
||||
|
||||
|
||||
def closed_k1_reset(state, physical, checkpoint):
|
||||
retired = (physical.get("operator_retirements") or [{}])[-1]
|
||||
original = retired.get("original_attempt") or {}
|
||||
runtime = state.get("runtime_id")
|
||||
return bool(
|
||||
state.get("phase") == "idle"
|
||||
and state.get("device_session") is None
|
||||
and state.get("selected_device_id") is None
|
||||
and isinstance(runtime, str)
|
||||
and runtime
|
||||
and physical.get("stage") == "resolved"
|
||||
and physical.get("resolution") == "operator-retired-outcome-unknown"
|
||||
and retired.get("reason") == "connection-scenario-reset-by-operator"
|
||||
and retired.get("retirement_id", "").startswith("scenario-reset-" + runtime + "-")
|
||||
and original.get("operation_id") == physical.get("operation_id")
|
||||
and original.get("acquisition_id") == physical.get("acquisition_id")
|
||||
and physical.get("acquisition_id") == checkpoint.get("acquisition_id")
|
||||
and isinstance(physical.get("acquisition_id"), str)
|
||||
)
|
||||
|
||||
|
||||
def evidence_identity(folder):
|
||||
rows = []
|
||||
for path in sorted(folder.rglob("*")):
|
||||
if path.is_symlink():
|
||||
raise RuntimeError("Не подтверждено хранилище записи K1.")
|
||||
if path.is_file():
|
||||
info = path.stat()
|
||||
rows.append((str(path.relative_to(folder)), info.st_size, info.st_mtime_ns))
|
||||
if not rows or not (folder / "manifest.redacted.json").is_file():
|
||||
raise RuntimeError("Не подтверждены сохранённые файлы K1.")
|
||||
return {
|
||||
"files": len(rows),
|
||||
"bytes": sum(row[1] for row in rows),
|
||||
"metadata_sha256": hashlib.sha256(json.dumps(rows).encode()).hexdigest(),
|
||||
}
|
||||
|
||||
|
||||
class K1Maintenance:
|
||||
def __init__(self, report):
|
||||
self.report = report
|
||||
self.fenced = None
|
||||
self.stopped = False
|
||||
self.evidence = None
|
||||
report.update(state="not-required", physical_stop_confirmed=False)
|
||||
|
||||
def begin(self):
|
||||
if not K1_SOCKET.exists() or probe(K1_SOCKET, "/prepare-safe").get("safe") is True:
|
||||
return
|
||||
source = Path(
|
||||
"/usr/lib/mission-core-node/k1/src/k1link/device_plugins/xgrids_k1/node_bridge.py"
|
||||
)
|
||||
if hashlib.sha256(source.read_bytes()).hexdigest() != K1_LEGACY_BRIDGE:
|
||||
raise RuntimeError("Завершите запись K1 перед обновлением.")
|
||||
target = MAINTENANCE_ROOT / "private/k1.sock"
|
||||
if target.exists():
|
||||
raise RuntimeError("Обслуживание K1 уже выполняется.")
|
||||
K1_SOCKET.rename(target)
|
||||
self.fenced = target
|
||||
state = probe(target, "/status")
|
||||
physical = json.loads((K1_STATE / "xgrids-k1/physical-command.json").read_text())
|
||||
checkpoint = json.loads(
|
||||
(K1_STATE / "xgrids-k1/active-acquisition-recovery-checkpoint.json").read_text()
|
||||
)
|
||||
if not closed_k1_reset(state, physical, checkpoint):
|
||||
raise RuntimeError("K1 не подтвердил завершение локальной сессии оператором.")
|
||||
name = checkpoint.get("current_evidence_session_id", "")
|
||||
if not re.fullmatch(r"[A-Za-z0-9_-]{1,128}", name):
|
||||
raise RuntimeError("Не подтверждена запись K1.")
|
||||
self.evidence = K1_STATE / "evidence/sessions" / name
|
||||
manifest = json.loads((self.evidence / "manifest.redacted.json").read_text())
|
||||
if not manifest.get("completed_at_utc") or manifest.get("final_phase") != "idle":
|
||||
raise RuntimeError("Запись K1 ещё не завершена.")
|
||||
before = evidence_identity(self.evidence)
|
||||
# Root inspection proves no process still owns a capture file. The
|
||||
# fenced socket prevents a new device command during this transaction.
|
||||
prefix = str(self.evidence) + "/"
|
||||
for fd in Path("/proc").glob("[0-9]*/fd/*"):
|
||||
try:
|
||||
if str(fd.readlink()).startswith(prefix):
|
||||
raise RuntimeError("Файлы записи K1 ещё открыты. Дождитесь завершения.")
|
||||
except (FileNotFoundError, PermissionError, OSError):
|
||||
continue
|
||||
self.report.update(
|
||||
state="retired-session-verified",
|
||||
evidence=before,
|
||||
acquisition_id=physical["acquisition_id"],
|
||||
)
|
||||
subprocess.run(
|
||||
["/usr/bin/systemctl", "stop", "mission-core-k1.service"], check=True, timeout=30
|
||||
)
|
||||
self.stopped = True
|
||||
if evidence_identity(self.evidence) != before:
|
||||
raise RuntimeError("Файлы записи изменились при завершении K1.")
|
||||
self.report.update(state="quiesced", evidence_preserved=True)
|
||||
|
||||
def finish(self):
|
||||
if self.fenced and self.fenced.exists():
|
||||
if not self.stopped and not K1_SOCKET.exists():
|
||||
self.fenced.rename(K1_SOCKET)
|
||||
else:
|
||||
self.fenced.unlink()
|
||||
if self.stopped:
|
||||
subprocess.run(
|
||||
["/usr/bin/systemctl", "start", "mission-core-k1.service"], check=True, timeout=30
|
||||
)
|
||||
self.report["state"] = "restored"
|
||||
@@ -0,0 +1,75 @@
|
||||
"""Only an operator-retired K1 session admits the legacy terminal migration."""
|
||||
|
||||
import copy
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
import k1_maintenance as k
|
||||
|
||||
|
||||
class K1Retirement(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.state = dict(
|
||||
phase="idle", device_session=None, selected_device_id=None, runtime_id="runtime-current"
|
||||
)
|
||||
self.physical = dict(
|
||||
stage="resolved",
|
||||
resolution="operator-retired-outcome-unknown",
|
||||
operation_id="op-current",
|
||||
acquisition_id="acq-current",
|
||||
operator_retirements=[
|
||||
dict(
|
||||
reason="connection-scenario-reset-by-operator",
|
||||
retirement_id="scenario-reset-runtime-current-2-bridge",
|
||||
original_attempt=dict(operation_id="op-current", acquisition_id="acq-current"),
|
||||
)
|
||||
],
|
||||
)
|
||||
self.checkpoint = dict(acquisition_id="acq-current")
|
||||
|
||||
def test_explicit_local_retirement_is_admitted_without_claiming_physical_stop(self):
|
||||
self.assertTrue(k.closed_k1_reset(self.state, self.physical, self.checkpoint))
|
||||
|
||||
def test_active_or_new_session_and_unresolved_physical_command_are_rejected(self):
|
||||
for owner, key, value in [
|
||||
("state", "phase", "device_selected"),
|
||||
("state", "device_session", {"id": "new"}),
|
||||
("state", "runtime_id", "restarted"),
|
||||
("physical", "resolution", "start-active-observed"),
|
||||
("physical", "operation_id", "new-command"),
|
||||
("physical", "stage", "dispatching"),
|
||||
("checkpoint", "acquisition_id", "new-acquisition"),
|
||||
]:
|
||||
values = {
|
||||
"state": copy.deepcopy(self.state),
|
||||
"physical": copy.deepcopy(self.physical),
|
||||
"checkpoint": copy.deepcopy(self.checkpoint),
|
||||
}
|
||||
values[owner][key] = value
|
||||
self.assertFalse(k.closed_k1_reset(**values), (owner, key))
|
||||
|
||||
def test_file_inventory_detects_changes_and_refuses_symlinks(self):
|
||||
with tempfile.TemporaryDirectory() as raw:
|
||||
root = Path(raw)
|
||||
(root / "manifest.redacted.json").write_text("{}")
|
||||
before = k.evidence_identity(root)
|
||||
(root / "data.bin").write_bytes(b"recorded")
|
||||
self.assertNotEqual(before, k.evidence_identity(root))
|
||||
(root / "alias").symlink_to(root / "data.bin")
|
||||
with self.assertRaises(RuntimeError):
|
||||
k.evidence_identity(root)
|
||||
|
||||
def test_failed_admission_restores_existing_socket(self):
|
||||
with tempfile.TemporaryDirectory() as raw:
|
||||
root = Path(raw)
|
||||
source = root / "source.sock"
|
||||
target = root / "private.sock"
|
||||
target.touch()
|
||||
m = k.K1Maintenance({})
|
||||
m.fenced = target
|
||||
with patch.object(k, "K1_SOCKET", source), patch.object(k.subprocess, "run") as run:
|
||||
m.finish()
|
||||
self.assertTrue(source.exists())
|
||||
run.assert_not_called()
|
||||
@@ -17,6 +17,7 @@ class OwnerDependencyTests(unittest.TestCase):
|
||||
(node/'build').mkdir()
|
||||
(packaging/'vesc_hall_recovery.py').write_bytes(b'# hall recovery\n')
|
||||
(packaging/'can_maintenance.py').write_bytes(b'# maintenance\n')
|
||||
(packaging/'k1_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)
|
||||
@@ -49,6 +50,6 @@ class OwnerDependencyTests(unittest.TestCase):
|
||||
(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()),[])
|
||||
self.assertEqual(list((node/'build').glob('*.pyz')),[])
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
|
||||
@@ -36,9 +36,12 @@ def build(native=None):
|
||||
]
|
||||
paths += list((REPOSITORY / "packages/plugin-sdk/python/missioncore_plugin_sdk").rglob("*.py"))
|
||||
paths += [REPOSITORY / "scripts/packaging/debian.py"]
|
||||
paths += [REPOSITORY / "tests/test_media_reconfiguration.py",
|
||||
REPOSITORY / "tests/test_media_profile_recovery.py"]
|
||||
paths += [REPOSITORY / "apps/node-agent/packaging/insta360_profile.py"]
|
||||
paths += [REPOSITORY / "apps/node-agent/packaging" / name for name in (
|
||||
"install_owner_release.py", "can_maintenance.py", "vesc_hall_recovery.py")]
|
||||
"install_owner_release.py", "can_maintenance.py", "vesc_hall_recovery.py",
|
||||
"k1_maintenance.py")]
|
||||
paths += [
|
||||
REPOSITORY / name
|
||||
for name in (
|
||||
|
||||
Reference in New Issue
Block a user