Files

129 lines
5.8 KiB
Python

"""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"