cmvr-visual/inference/admin/gpu_guard.py
zhanghao 88cf14d794 feat: consolidate story studio and editable automatic production
Restructure backend and frontend modules; add story, library, and editor schema migrations.

Support editable automatic production, manual confirmation modes, account and user lifecycle management, compact container scrolling, consistent forms, and per-task result previews.

Update inference and TTS scheduling, deployment guidance, and regression coverage; remove obsolete standalone pages and temporary acceptance artifacts.
2026-11-14 14:07:26 +08:00

700 lines
31 KiB
Python

#!/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 concurrent.futures import ThreadPoolExecutor
from contextlib import contextmanager
from dataclasses import dataclass
import importlib.util
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
# 与容器端快照有效期一致;慢查询可以延续观察,超时或时钟倒退必须清空历史。
MAX_OBSERVATION_AGE_SECONDS = 20.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 load_nvml_binding(policy_dir: Path):
"""Load only the optional root-managed single file, never its directory."""
path = Path(policy_dir) / "nvml_binding.py"
try:
before = path.lstat()
except FileNotFoundError:
return None
except OSError:
raise GuardError("nvml_binding_invalid") from None
try:
if not stat.S_ISREG(before.st_mode):
raise GuardError("nvml_binding_invalid")
flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)
descriptor = os.open(path, flags)
with os.fdopen(descriptor, "rb") as stream:
metadata = os.fstat(stream.fileno())
if (not stat.S_ISREG(metadata.st_mode) or metadata.st_uid != 0
or metadata.st_mode & 0o022
or (before.st_dev, before.st_ino) != (metadata.st_dev, metadata.st_ino)):
raise GuardError("nvml_binding_invalid")
# 从已核验的文件描述符读取,避免校验后由 import loader 重新打开路径。
source = stream.read(2 * 1024 * 1024 + 1)
if len(source) > 2 * 1024 * 1024:
raise GuardError("nvml_binding_invalid")
name = f"_llmuser_gpu_guard_nvml_{metadata.st_dev}_{metadata.st_ino}"
spec = importlib.util.spec_from_file_location(name, path)
binding = importlib.util.module_from_spec(spec)
previous = sys.modules.get(name)
sys.modules[name] = binding # pynvml 在导入时通过自身模块注册异常类型。
try:
exec(compile(source, str(path), "exec", dont_inherit=True), binding.__dict__)
except (Exception, SystemExit):
if previous is None:
sys.modules.pop(name, None)
else:
sys.modules[name] = previous
raise
return binding
except (Exception, SystemExit):
raise GuardError("nvml_binding_invalid") from None
class NvmlSampler:
"""Read the same four physical GPUs and both process types, without CUDA."""
def __init__(self, binding):
self.binding = binding
try:
binding.nvmlInit()
except Exception:
raise GuardError("nvml_init_failed") from None
def __call__(self) -> bytes:
try:
count = self.binding.nvmlDeviceGetCount()
if type(count) is not int or count != 4:
raise GuardError("nvml_query_invalid")
# NVML 官方确认线程安全;四卡并行避免驱动查询长尾串行累加。
# https://docs.nvidia.com/deploy/nvml-api/nvml-api-reference.html
with ThreadPoolExecutor(max_workers=4) as pool:
sampled = list(pool.map(self._sample_gpu, range(count)))
# map 保持物理 index 顺序,且必须四卡全部成功后才能发布完整 XML。
root = ET.Element("nvidia_smi_log")
root.extend(sampled)
return ET.tostring(root, encoding="utf-8")
except GuardError:
raise
except Exception:
raise GuardError("nvml_query_failed") from None
def _sample_gpu(self, index):
handle = self.binding.nvmlDeviceGetHandleByIndex(index)
actual_index = self.binding.nvmlDeviceGetIndex(handle)
if type(actual_index) is not int or actual_index != index:
raise GuardError("nvml_query_invalid")
uuid = self.binding.nvmlDeviceGetUUID(handle)
if isinstance(uuid, bytes):
uuid = uuid.decode("ascii")
if not isinstance(uuid, str):
raise GuardError("nvml_query_invalid")
memory = self.binding.nvmlDeviceGetMemoryInfo(handle)
if (type(memory.total) is not int or type(memory.free) is not int
or not 0 <= memory.free <= memory.total < 2**64 - 1 or memory.total == 0):
raise GuardError("nvml_query_invalid")
gpu = ET.Element("gpu")
ET.SubElement(gpu, "uuid").text = uuid
usage = ET.SubElement(gpu, "fb_memory_usage")
ET.SubElement(usage, "total").text = f"{memory.total} B"
ET.SubElement(usage, "free").text = f"{memory.free} B"
records = {}
for kind, query in (("C", self.binding.nvmlDeviceGetComputeRunningProcesses),
("G", self.binding.nvmlDeviceGetGraphicsRunningProcesses)):
processes = query(handle)
if not isinstance(processes, (list, tuple)) or len(processes) > 4096:
raise GuardError("nvml_query_invalid")
for process in processes:
pid, used = process.pid, process.usedGpuMemory
if type(pid) is not int or not 0 < pid < 2**31:
raise GuardError("nvml_query_invalid")
if used is not None and (type(used) is not int or not 0 <= used <= 2**64 - 1):
raise GuardError("nvml_query_invalid")
if used == 2**64 - 1:
used = None
previous = records.get(pid)
if previous is None:
records[pid] = ({kind}, used)
else:
kinds, old_used = previous
kinds.add(kind)
records[pid] = (kinds, None if old_used is None or used is None else max(old_used, used))
processes = ET.SubElement(gpu, "processes")
for pid, (kinds, used) in sorted(records.items()):
row = ET.SubElement(processes, "process_info")
ET.SubElement(row, "pid").text = str(pid)
# C+G 不能匹配仅限 G 的图形基线;未知显存也不能变成零。
ET.SubElement(row, "type").text = "+".join(sorted(kinds))
ET.SubElement(row, "used_memory").text = "N/A" if used is None else f"{used} B"
return gpu
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 | None = None, 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.nvml_sampler = None
self.query = query if query is not None else self._query_default
self.wall_time, self.monotonic = 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 _query_default(self):
if self.nvml_sampler is None:
binding = load_nvml_binding(self.policy_dir)
if binding is None:
return query_nvidia_xml()
self.nvml_sampler = NvmlSampler(binding)
return self.nvml_sampler()
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
sample_started, sample_started_at = self.monotonic(), self.wall_time()
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 now < sample_started or epoch < sample_started_at:
raise GuardError("gpu_sample_time_invalid")
if now - sample_started > MAX_OBSERVATION_AGE_SECONDS:
raise GuardError("gpu_sample_stale")
if self.last_sample is not None and (now < self.last_sample
or now - self.last_sample > MAX_OBSERVATION_AGE_SECONDS):
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(),
"sample_started_at": sample_started_at, "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())