cmvr-visual/inference/admin/gpu_guard.py

558 lines
24 KiB
Python
Raw Normal View History

#!/usr/bin/env python3
"""Trusted host-PID GPU observer and last-resort own-container preemption.
Run only in the administrator's isolated utility container. The only policy
input is root-managed target.json; no product settings, user commands, Docker
socket, or process names are trusted. NVIDIA XML reference:
https://docs.nvidia.com/deploy/nvidia-smi/index.html
"""
from __future__ import annotations
import argparse
from contextlib import contextmanager
from dataclasses import dataclass
import json
import math
import os
from pathlib import Path, PurePosixPath
import re
import signal
import stat
import subprocess
import sys
import tempfile
import threading
import time
from typing import Callable
import xml.etree.ElementTree as ET
SIGKILL = getattr(signal, "SIGKILL", 9)
CONFLICT_SECONDS = 4.0
KILL_DELAY_SECONDS = 1.0
CID_PATTERN = re.compile(r"[0-9a-f]{64}\Z")
DOCKER_COMPONENT = re.compile(rb"(?:^|/)docker/([0-9a-f]{64})(?=/|$)|(?:^|/)docker-([0-9a-f]{64})\.scope(?=/|$)")
class GuardError(RuntimeError):
"""Only fixed diagnostic codes belong in this exception, never raw output."""
@dataclass(frozen=True)
class BaselineProcess:
pid: int
start: str
exe: str
max_memory_mib: float
@dataclass(frozen=True)
class BaselineRule:
exe: str
uids: tuple[int, int, int, int]
max_memory_mib: float
@dataclass(frozen=True)
class TargetPolicy:
container_id: str
baseline_processes: tuple[BaselineProcess, ...] = ()
baseline_rules: tuple[BaselineRule, ...] = ()
@dataclass(frozen=True)
class ProcessIdentity:
pid: int
start: str
container_ids: frozenset[str]
state: str
def owned_by(self, container_id: str) -> bool:
return self.container_ids == frozenset({container_id})
def _read_limited(path: Path, limit: int) -> bytes:
with path.open("rb") as stream:
value = stream.read(limit + 1)
if len(value) > limit:
raise GuardError("input_too_large")
return value
def read_target(policy_dir: Path) -> TargetPolicy:
path = Path(policy_dir) / "target.json"
try:
descriptor = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0))
with os.fdopen(descriptor, "rb") as stream:
if not stat.S_ISREG(os.fstat(stream.fileno()).st_mode):
raise GuardError("target_invalid")
raw = stream.read(16385)
if len(raw) > 16384:
raise GuardError("target_invalid")
data = json.loads(raw)
cid = data.get("container_id")
if not isinstance(cid, str) or not CID_PATTERN.fullmatch(cid):
raise GuardError("target_invalid")
baselines = data.get("baseline_processes", [])
if not isinstance(baselines, list) or len(baselines) > 32:
raise GuardError("target_invalid")
parsed, seen = [], set()
for entry in baselines:
pid, start, exe, maximum = (entry.get(key) for key in ("pid", "start", "exe", "max_memory_mib"))
if type(pid) is not int or pid <= 0 or pid in seen:
raise GuardError("target_invalid")
if not isinstance(start, str) or not re.fullmatch(r"[0-9]+", start):
raise GuardError("target_invalid")
if not isinstance(exe, str) or not PurePosixPath(exe).is_absolute() or ".." in PurePosixPath(exe).parts:
raise GuardError("target_invalid")
if isinstance(maximum, bool) or not isinstance(maximum, (int, float)) or not math.isfinite(maximum) or not 0 <= maximum <= 16:
raise GuardError("target_invalid")
seen.add(pid)
parsed.append(BaselineProcess(pid, start, exe, float(maximum)))
rules = data.get("baseline_rules", [])
if not isinstance(rules, list) or len(rules) > 32:
raise GuardError("target_invalid")
parsed_rules = []
for entry in rules:
exe, uids, maximum = (entry.get(key) for key in ("exe", "uids", "max_memory_mib"))
if "uid" in entry or not isinstance(uids, list) or len(uids) != 4:
raise GuardError("target_invalid")
if any(type(uid) is not int or uid < 0 for uid in uids) or uids[1:] != [0, 0, 0]:
raise GuardError("target_invalid")
if not isinstance(exe, str) or not PurePosixPath(exe).is_absolute() or ".." in PurePosixPath(exe).parts:
raise GuardError("target_invalid")
if isinstance(maximum, bool) or not isinstance(maximum, (int, float)) or not math.isfinite(maximum) or not 0 <= maximum <= 16:
raise GuardError("target_invalid")
parsed_rules.append(BaselineRule(exe, tuple(uids), float(maximum)))
return TargetPolicy(cid, tuple(parsed), tuple(parsed_rules))
except GuardError:
raise
except (OSError, ValueError, TypeError, AttributeError):
raise GuardError("target_invalid") from None
def _stat_identity(raw: bytes, expected_pid: int) -> tuple[str, str]:
try:
pid_text, _ = raw.split(b" ", 1)
ending = raw.rindex(b")")
fields = raw[ending + 1:].split()
start = fields[19].decode("ascii") # /proc/PID/stat field 22.
if int(pid_text) != expected_pid or not start.isdigit():
raise ValueError
return start, fields[0].decode("ascii")
except (ValueError, IndexError, UnicodeError):
raise GuardError("process_inspection_failed") from None
def read_process_identity(pid: int, proc_root: Path = Path("/proc")) -> ProcessIdentity:
if type(pid) is not int or pid <= 0:
raise GuardError("process_inspection_failed")
directory = Path(proc_root) / str(pid)
before, _ = _stat_identity(_read_limited(directory / "stat", 8192), pid)
cgroup = _read_limited(directory / "cgroup", 65536)
identities, lines = set(), cgroup.splitlines()
if not lines:
raise GuardError("process_inspection_failed")
for line in lines:
pieces = line.split(b":", 2)
if len(pieces) != 3 or not pieces[0].isdigit() or not pieces[2].startswith(b"/"):
raise GuardError("process_inspection_failed")
for match in DOCKER_COMPONENT.finditer(pieces[2]):
identities.add((match.group(1) or match.group(2)).decode("ascii"))
after, state = _stat_identity(_read_limited(directory / "stat", 8192), pid)
if before != after:
raise GuardError("process_inspection_failed")
return ProcessIdentity(pid, after, frozenset(identities), state)
def read_executable(pid: int, proc_root: Path = Path("/proc")) -> str:
# The host executable need not exist in this utility container's rootfs.
return os.readlink(Path(proc_root) / str(pid) / "exe")
def read_process_uids(pid: int, proc_root: Path = Path("/proc")) -> tuple[int, int, int, int]:
# Directory ownership changes with dumpability; only the kernel's Uid row
# describes the process's real/effective/saved-set/filesystem credentials.
raw = _read_limited(Path(proc_root) / str(pid) / "status", 65536)
rows = [line.split()[1:] for line in raw.splitlines() if line.startswith(b"Uid:")]
if len(rows) != 1 or len(rows[0]) != 4 or any(not value.isdigit() for value in rows[0]):
raise GuardError("process_inspection_failed")
return tuple(int(value) for value in rows[0])
def _memory_mib(value: str | None) -> float:
match = re.fullmatch(r"\s*([0-9]+(?:\.[0-9]+)?)\s+(MiB|GiB|KiB|B)\s*", value or "")
if not match:
raise GuardError("gpu_query_invalid")
return float(match.group(1)) * {"MiB": 1, "GiB": 1024, "KiB": 1 / 1024, "B": 1 / 1048576}[match.group(2)]
def parse_gpu_xml(xml: str | bytes, expected_gpu_count: int = 4) -> list[dict]:
try:
if len(xml) > 4 * 1024 * 1024:
raise GuardError("gpu_query_invalid")
root = ET.fromstring(xml)
nodes = root.findall("gpu")
if root.tag != "nvidia_smi_log" or len(nodes) != expected_gpu_count:
raise GuardError("gpu_query_invalid")
gpus, seen = [], set()
for index, gpu in enumerate(nodes):
uuid = gpu.findtext("uuid", "").strip()
if not re.fullmatch(r"GPU-[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}", uuid) or uuid in seen:
raise GuardError("gpu_query_invalid")
seen.add(uuid)
total = _memory_mib(gpu.findtext("fb_memory_usage/total"))
free = _memory_mib(gpu.findtext("fb_memory_usage/free"))
if total <= 0 or free > total:
raise GuardError("gpu_query_invalid")
processes = gpu.find("processes")
if processes is None or (processes.text or "").strip():
# Includes N/A, driver errors and unidentified process reports.
raise GuardError("gpu_query_invalid")
records = []
for row in processes:
if row.tag != "process_info":
raise GuardError("gpu_query_invalid")
pid = int(row.findtext("pid", ""))
if pid <= 0:
raise GuardError("gpu_query_invalid")
try:
memory = _memory_mib(row.findtext("used_memory"))
except GuardError:
memory = None # Unknown usage can never qualify as baseline.
records.append({"pid": pid, "type": row.findtext("type", "").strip(), "used_memory_mib": memory})
gpus.append({"index": index, "uuid": uuid, "total_gib": total / 1024,
"free_gib": free / 1024, "processes": records})
return gpus
except GuardError:
raise
except (ET.ParseError, ValueError, TypeError, AttributeError):
raise GuardError("gpu_query_invalid") from None
def query_nvidia_xml() -> bytes:
try:
return subprocess.run(["nvidia-smi", "-q", "-x"], stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL, timeout=3, check=True).stdout
except subprocess.TimeoutExpired:
raise GuardError("nvidia_query_timeout") from None
except subprocess.CalledProcessError as exc:
raise GuardError(f"nvidia_query_exit_{int(exc.returncode)}") from None
except (OSError, subprocess.SubprocessError):
raise GuardError("nvidia_query_exec_failed") from None
def signal_owned_process(identity: ProcessIdentity, policy: TargetPolicy, policy_dir: Path,
*, signum: int, proc_root: Path = Path("/proc")) -> bool:
"""Never fall back to numeric-PID killing; pidfd binds the actual process."""
if signum not in {signal.SIGTERM, SIGKILL} or identity.pid <= 1:
return False
if not identity.owned_by(policy.container_id) or any(item.pid == identity.pid for item in policy.baseline_processes):
return False
opener, sender = getattr(os, "pidfd_open", None), getattr(signal, "pidfd_send_signal", None)
if not callable(opener) or not callable(sender):
raise GuardError("pidfd_unavailable")
descriptor = None
try:
descriptor = opener(identity.pid, 0)
if read_target(policy_dir) != policy:
return False
current = read_process_identity(identity.pid, proc_root)
if current.start != identity.start or not current.owned_by(policy.container_id) or current.state in {"Z", "X"}:
return False
if read_target(policy_dir) != policy:
return False
# Recheck immediately before signaling the pidfd, including cgroup.
current = read_process_identity(identity.pid, proc_root)
if current.start != identity.start or not current.owned_by(policy.container_id) or current.state in {"Z", "X"}:
return False
sender(descriptor, signum, None, 0)
return True
except (FileNotFoundError, ProcessLookupError):
return False
except OSError:
raise GuardError("signal_boundary_failed") from None
finally:
if descriptor is not None:
os.close(descriptor)
def write_status(policy_dir: Path, status: dict) -> None:
descriptor, temporary = tempfile.mkstemp(prefix=".status-", dir=policy_dir)
try:
if hasattr(os, "fchmod"):
os.fchmod(descriptor, 0o644)
with os.fdopen(descriptor, "w", encoding="utf-8") as stream:
json.dump(status, stream, allow_nan=False, separators=(",", ":"))
stream.write("\n")
stream.flush()
os.fsync(stream.fileno())
os.replace(temporary, Path(policy_dir) / "status.json")
finally:
try:
os.unlink(temporary)
except FileNotFoundError:
pass
class GpuGuard:
def __init__(self, policy_dir: Path, *, proc_root: Path = Path("/proc"),
query: Callable = query_nvidia_xml, wall_time: Callable = time.time,
monotonic: Callable = time.monotonic, emit_event: Callable | None = None):
self.policy_dir, self.proc_root = Path(policy_dir), Path(proc_root)
self.query, self.wall_time, self.monotonic = query, wall_time, monotonic
self.emit_event = emit_event
self.policy = None
self.idle = {}
self.conflicts = {}
self.pending = {}
self.last_sample = None
self.stop_requested = False
def _reset(self):
self.idle.clear()
self.conflicts.clear()
self.pending.clear()
def _event(self, event):
if self.emit_event:
self.emit_event({"event": event, "count": 1})
def _inspection_failure(self, pid, stage, exc):
if isinstance(exc, (FileNotFoundError, ProcessLookupError)):
category = "not_found"
elif isinstance(exc, PermissionError):
category = "permission_denied"
elif isinstance(exc, GuardError):
category = "identity_invalid"
else:
category = "os_error"
if self.emit_event:
self.emit_event({"event": "process_inspection_failed", "count": 1,
"pid": pid, "stage": stage, "category": category})
# A missing exe/status/cgroup alone is not proof of process exit.
# Only kernel disappearance errors AND an absent PID directory qualify.
if category == "not_found":
try:
(self.proc_root / str(pid)).stat()
except (FileNotFoundError, ProcessLookupError):
return True
except OSError:
pass
return False
def _inspect_sample(self, raw_gpus, policy, forced_external=frozenset()):
identities, failed, missing, ambiguous = {}, set(), set(), set()
for pid in sorted({row["pid"] for gpu in raw_gpus for row in gpu["processes"]}):
try:
identities[pid] = read_process_identity(pid, self.proc_root)
except (OSError, GuardError) as exc:
identities[pid] = None
failed.add(pid)
if self._inspection_failure(pid, "identity", exc):
missing.add(pid)
else:
ambiguous.add(pid)
baselines = {item.pid: item for item in policy.baseline_processes}
inspected = []
for raw in raw_gpus:
own, external, baseline = [], [], []
by_pid = {}
for row in raw["processes"]:
by_pid.setdefault(row["pid"], []).append(row)
for pid, rows in by_pid.items():
identity = identities[pid]
try:
if identity is None or pid in forced_external:
external.append(pid)
elif pid in baselines:
(baseline if self._baseline_ok(identity, rows, baselines[pid]) else external).append(pid)
elif self._dynamic_baseline_ok(identity, rows, policy.baseline_rules):
baseline.append(pid)
elif identity.owned_by(policy.container_id):
own.append(pid)
else:
external.append(pid)
except (OSError, GuardError) as exc:
external.append(pid)
failed.add(pid)
if self._inspection_failure(pid, "baseline", exc):
missing.add(pid)
else:
ambiguous.add(pid)
inspected.append({key: raw[key] for key in ("index", "uuid", "total_gib", "free_gib")}
| {"external_pids": sorted(external), "own_pids": sorted(own),
"baseline_pids": sorted(baseline)})
return inspected, identities, failed, missing - ambiguous
def _baseline_ok(self, identity, rows, baseline):
if identity.start != baseline.start or any(row["type"] != "G" or row["used_memory_mib"] is None
or row["used_memory_mib"] > baseline.max_memory_mib for row in rows):
return False
if read_executable(identity.pid, self.proc_root) != baseline.exe:
return False
return read_process_identity(identity.pid, self.proc_root).start == baseline.start
def _dynamic_baseline_ok(self, identity, rows, rules):
if not rules or identity.container_ids:
return False
candidates = [rule for rule in rules if all(row["type"] == "G" and row["used_memory_mib"] is not None
and row["used_memory_mib"] <= rule.max_memory_mib for row in rows)]
if not candidates:
return False
uids = read_process_uids(identity.pid, self.proc_root)
candidates = [rule for rule in candidates if rule.uids == uids]
if not candidates:
return False
executable = read_executable(identity.pid, self.proc_root)
if not any(rule.exe == executable for rule in candidates):
return False
current = read_process_identity(identity.pid, self.proc_root)
return current.start == identity.start and not current.container_ids
def _preempt(self, gpus, identities, policy, now):
conflicts = {gpu["uuid"]: gpu for gpu in gpus if gpu["external_pids"] and gpu["own_pids"]}
self.conflicts = {uuid: started for uuid, started in self.conflicts.items() if uuid in conflicts}
self.pending = {key: value for key, value in self.pending.items()
if key[0] in conflicts and key[1] in conflicts[key[0]]["own_pids"]
and identities[key[1]].start == key[2]}
sent = set()
for uuid, gpu in conflicts.items():
first = self.conflicts.setdefault(uuid, now)
if now - first < CONFLICT_SECONDS:
continue
for pid in gpu["own_pids"]:
identity = identities[pid]
key = uuid, pid, identity.start
pending = self.pending.get(key)
signum = signal.SIGTERM if pending is None else SIGKILL
if pending is not None and (pending[1] or now - pending[0] < KILL_DELAY_SECONDS):
continue
token = pid, identity.start, signum
if token in sent:
# Same own process can appear on several GPUs.
self.pending[key] = (now, signum == SIGKILL)
continue
if signal_owned_process(identity, policy, self.policy_dir, signum=signum, proc_root=self.proc_root):
sent.add(token)
self.pending[key] = (now, signum == SIGKILL)
self._event("own_term" if signum == signal.SIGTERM else "own_kill")
def run_once(self) -> dict:
gpus, error, policy = [], None, None
try:
policy = read_target(self.policy_dir)
if policy != self.policy:
self._reset()
self.policy = policy
try:
xml = self.query()
except GuardError as exc:
if str(exc) != "nvidia_query_timeout":
raise
xml = self.query() # One retry; leave the old snapshot untouched.
raw_gpus = parse_gpu_xml(xml)
inspected, identities, failed, missing = self._inspect_sample(raw_gpus, policy)
if missing:
# Occupancy in the first sample breaks continuous idle time,
# even when the confirming sample finds that process gone.
for gpu in inspected:
if gpu["own_pids"] or gpu["external_pids"]:
self.idle.pop(gpu["uuid"], None)
# One fresh full sample, with no timeout retry here. Reinspect
# every PID so new external users cannot be lost in the race.
raw_gpus = parse_gpu_xml(self.query())
present = {row["pid"] for gpu in raw_gpus for row in gpu["processes"]}
inspected, identities, fresh_failed, _ = self._inspect_sample(raw_gpus, policy, failed)
failed = (failed - (missing - present)) | fresh_failed
if failed:
error = "process_inspection_failed"
now, epoch = self.monotonic(), self.wall_time()
if self.last_sample is not None and (now < self.last_sample or now - self.last_sample > 5):
self._reset() # No idle credit across a paused/missing observer.
self.last_sample = now
for gpu in inspected:
uuid = gpu["uuid"]
if gpu["own_pids"] or gpu["external_pids"]:
self.idle.pop(uuid, None)
else:
self.idle.setdefault(uuid, epoch)
gpus.append(gpu | {"idle_since": self.idle.get(uuid)})
if self.stop_requested:
raise GuardError("guard_stopped")
if error is None:
self._preempt(gpus, identities, policy, now)
if read_target(self.policy_dir) != policy:
raise GuardError("target_changed")
except GuardError as exc:
error = str(exc)
except Exception:
error = "guard_internal_error"
if error is not None:
self._reset()
for gpu in gpus:
gpu["idle_since"] = None
self._event("snapshot_error")
status = {"schema_version": 1, "generated_at": self.wall_time(), "error": error,
"container_id": policy.container_id if policy else None, "gpus": gpus}
write_status(self.policy_dir, status)
return status
@contextmanager
def guard_lock(policy_dir: Path):
import fcntl
descriptor = os.open(Path(policy_dir) / "guard.lock", os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600)
try:
try:
fcntl.flock(descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
raise GuardError("guard_already_running") from None
yield
finally:
os.close(descriptor)
def _interval(value):
result = float(value)
if not math.isfinite(result) or result <= 0:
raise argparse.ArgumentTypeError("interval must be positive and finite")
return result
def main(argv=None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--policy-dir", type=Path, default=Path("/policy"))
parser.add_argument("--interval", type=_interval, default=1.0)
args = parser.parse_args(argv)
if not sys.platform.startswith("linux") or os.geteuid() != 0:
print(json.dumps({"event": "root_linux_required", "count": 1}), flush=True)
return 2
emit = lambda event: print(json.dumps(event), flush=True)
guard = GpuGuard(args.policy_dir, emit_event=emit)
stop = threading.Event()
def request_stop(_signum, _frame):
guard.stop_requested = True
stop.set()
signal.signal(signal.SIGTERM, request_stop)
signal.signal(signal.SIGINT, request_stop)
try:
with guard_lock(args.policy_dir):
while not stop.is_set():
started = time.monotonic()
guard.run_once()
stop.wait(max(0, args.interval - (time.monotonic() - started)))
write_status(args.policy_dir, {"schema_version": 1, "generated_at": time.time(),
"container_id": guard.policy.container_id if guard.policy else None,
"error": "guard_stopped", "gpus": []})
except (OSError, GuardError):
emit({"event": "guard_failed", "count": 1})
return 2
return 0
if __name__ == "__main__":
raise SystemExit(main())