argus-iris 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
argus_iris/__init__.py ADDED
@@ -0,0 +1,16 @@
1
+ """argus-iris — VRAM-aware GPU lease broker for the Argus suite: priorities, schedules, keepalive and idle-kill across GPU nodes"""
2
+
3
+ from __future__ import annotations
4
+
5
+ try:
6
+ # Written by hatch-vcs at build time (see pyproject [tool.hatch.build.hooks.vcs]).
7
+ from argus_iris._version import __version__
8
+ except ImportError: # running from a source checkout that hasn't been built
9
+ from importlib.metadata import PackageNotFoundError, version
10
+
11
+ try:
12
+ __version__ = version("argus-iris")
13
+ except PackageNotFoundError:
14
+ __version__ = "0.0.0+unknown"
15
+
16
+ __all__ = ["__version__"]
argus_iris/_version.py ADDED
@@ -0,0 +1,24 @@
1
+ # file generated by vcs-versioning
2
+ # don't change, don't track in version control
3
+ from __future__ import annotations
4
+
5
+ __all__ = [
6
+ "__version__",
7
+ "__version_tuple__",
8
+ "version",
9
+ "version_tuple",
10
+ "__commit_id__",
11
+ "commit_id",
12
+ ]
13
+
14
+ version: str
15
+ __version__: str
16
+ __version_tuple__: tuple[int | str, ...]
17
+ version_tuple: tuple[int | str, ...]
18
+ commit_id: str | None
19
+ __commit_id__: str | None
20
+
21
+ __version__ = version = '0.1.0'
22
+ __version_tuple__ = version_tuple = (0, 1, 0)
23
+
24
+ __commit_id__ = commit_id = None
@@ -0,0 +1,5 @@
1
+ """iris-agent: per-host GPU sampler (NVML + cgroups) and allow-listed container actions.
2
+
3
+ Behind the ``[agent]`` extra. Run with ``argus-iris agent``; it needs ``pid: host``, NVML, the Docker socket and the
4
+ host's ``/sys/fs/cgroup`` read-only.
5
+ """
@@ -0,0 +1,307 @@
1
+ """iris-agent's FastAPI app: a polled snapshot, Prometheus metrics, and allow-listed container actions."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import contextlib
7
+ import hmac
8
+ import os
9
+ import socket
10
+ import time
11
+ from collections.abc import AsyncIterator, Callable
12
+ from dataclasses import dataclass, field
13
+ from pathlib import Path
14
+
15
+ import structlog
16
+ from fastapi import FastAPI, Header, HTTPException
17
+ from fastapi.responses import Response
18
+ from prometheus_client import CONTENT_TYPE_LATEST, CollectorRegistry, generate_latest
19
+ from prometheus_client.core import GaugeMetricFamily
20
+
21
+ import argus_iris
22
+ from argus_iris.agent import procfs
23
+ from argus_iris.agent.docker import DEFAULT_SOCKET, ContainerInfo, DockerClient, DockerError
24
+ from argus_iris.agent.nvml import NvmlSampler, Sample
25
+ from argus_iris.agent.tracker import ProcessTracker
26
+ from argus_iris.models import ActionResult, ContainerAction, ContainerMemory, GpuProcess, NodeSnapshot, utcnow
27
+
28
+ log = structlog.get_logger("argus_iris.agent")
29
+
30
+
31
+ def _csv(raw: str) -> frozenset[str]:
32
+ return frozenset(x.strip() for x in raw.split(",") if x.strip())
33
+
34
+
35
+ @dataclass
36
+ class AgentSettings:
37
+ node: str = field(default_factory=socket.gethostname)
38
+ poll_s: float = 5.0
39
+ token: str | None = None # broker→agent token; unset disables container actions
40
+ containers: frozenset[str] = frozenset() # containers the broker may start/stop/restart
41
+ docker_socket: str = DEFAULT_SOCKET
42
+ proc_root: Path = Path("/proc")
43
+ cgroup_root: Path = Path("/sys/fs/cgroup")
44
+ idle_util_pct: int = 5
45
+
46
+ @classmethod
47
+ def from_env(cls) -> AgentSettings:
48
+ env = os.environ.get
49
+ return cls(
50
+ node=env("IRIS_AGENT_NODE") or socket.gethostname(),
51
+ poll_s=float(env("IRIS_AGENT_POLL_S", "5")),
52
+ token=env("IRIS_AGENT_TOKEN") or None,
53
+ containers=_csv(env("IRIS_AGENT_CONTAINERS", "")),
54
+ docker_socket=env("IRIS_AGENT_DOCKER_SOCKET", DEFAULT_SOCKET),
55
+ proc_root=Path(env("IRIS_AGENT_PROC", "/proc")),
56
+ cgroup_root=Path(env("IRIS_AGENT_CGROUP_ROOT", "/sys/fs/cgroup")),
57
+ idle_util_pct=int(env("IRIS_AGENT_IDLE_UTIL_PCT", "5")),
58
+ )
59
+
60
+
61
+ class Agent:
62
+ """Owns the sampler, tracker and container lookups; :meth:`poll_once` produces a :class:`NodeSnapshot`."""
63
+
64
+ def __init__(
65
+ self,
66
+ settings: AgentSettings,
67
+ *,
68
+ sample: Callable[[], Sample] | None = None,
69
+ docker: DockerClient | None = None,
70
+ clock: Callable[[], float] = time.monotonic,
71
+ ) -> None:
72
+ self.settings = settings
73
+ self._sampler = None if sample else NvmlSampler()
74
+ self._sample = sample or self._sampler.sample # type: ignore[union-attr]
75
+ self.docker = docker or DockerClient(settings.docker_socket)
76
+ self._clock = clock
77
+ self.tracker = ProcessTracker(settings.idle_util_pct)
78
+ self._containers: dict[str, ContainerInfo | None] = {} # container id -> info (None: not found)
79
+ self._pid_cgroup: dict[int, tuple[str | None, str | None]] = {} # pid -> (container id, cgroup path)
80
+ self.snapshot: NodeSnapshot | None = None
81
+ self.last_poll_monotonic: float | None = None
82
+ self.docker_error: str | None = None
83
+ self._poll_docker_error: str | None = None # this poll's, published to docker_error when it ends
84
+
85
+ async def aclose(self) -> None:
86
+ await self.docker.aclose()
87
+ if self._sampler:
88
+ self._sampler.close()
89
+
90
+ async def _container(self, cid: str) -> ContainerInfo | None:
91
+ # One Docker lookup per new container ID, cached; gothmog ran `docker top` on every container per new PID.
92
+ if cid not in self._containers:
93
+ try:
94
+ self._containers[cid] = await self.docker.inspect(cid)
95
+ except DockerError as exc:
96
+ self._poll_docker_error = str(exc)
97
+ return None # not cached: retry next poll
98
+ return self._containers[cid]
99
+
100
+ def _cgroup_of(self, pid: int) -> tuple[str | None, str | None]:
101
+ if pid not in self._pid_cgroup:
102
+ text = procfs.read_cgroup(self.settings.proc_root, pid)
103
+ self._pid_cgroup[pid] = (
104
+ (procfs.container_id_from_cgroup(text), procfs.cgroup_v2_path(text)) if text else (None, None)
105
+ )
106
+ return self._pid_cgroup[pid]
107
+
108
+ async def poll_once(self) -> NodeSnapshot:
109
+ self._poll_docker_error = None
110
+ sample = await asyncio.to_thread(self._sample)
111
+ now, wall = self._clock(), utcnow()
112
+ if sample.error:
113
+ # Keep the trackers as they were: an NVML hiccup should not reset every process's idle time.
114
+ tracked = []
115
+ log.warning("nvml_sample_failed", error=sample.error)
116
+ else:
117
+ tracked = self.tracker.update(sample, now=now, wall=wall)
118
+
119
+ live_pids = {t.pid for t in tracked}
120
+ for gone in set(self._pid_cgroup) - live_pids:
121
+ del self._pid_cgroup[gone]
122
+
123
+ processes: list[GpuProcess] = []
124
+ cgroups: dict[str, str] = {} # container name -> cgroup path, for anon memory
125
+ for t in tracked:
126
+ cid, cg_path = self._cgroup_of(t.pid)
127
+ info = await self._container(cid) if cid else None
128
+ if info and cg_path:
129
+ cgroups.setdefault(info.name, cg_path)
130
+ processes.append(
131
+ GpuProcess(
132
+ pid=t.pid,
133
+ gpu=t.gpu,
134
+ vram_mb=t.vram_mb,
135
+ container=info.name if info else None,
136
+ container_id=cid,
137
+ service=info.service if info else None,
138
+ sm_util_pct=t.sm_util_pct,
139
+ first_seen=t.first_seen,
140
+ idle_s=round(t.idle_s(now), 1),
141
+ )
142
+ )
143
+ live_cids = {p.container_id for p in processes if p.container_id}
144
+ for stale in set(self._containers) - live_cids:
145
+ del self._containers[stale]
146
+
147
+ # Allow-listed containers matter even with nothing on the GPU (ComfyUI holding offloaded weights in RAM).
148
+ for name in sorted(self.settings.containers - set(cgroups)):
149
+ try:
150
+ info = await self.docker.inspect(name)
151
+ except DockerError as exc:
152
+ self._poll_docker_error = str(exc)
153
+ continue
154
+ if info and info.running and info.pid:
155
+ text = procfs.read_cgroup(self.settings.proc_root, info.pid)
156
+ path = procfs.cgroup_v2_path(text) if text else None
157
+ if path:
158
+ cgroups[name] = path
159
+
160
+ containers = []
161
+ for name, path in sorted(cgroups.items()):
162
+ anon = procfs.read_anon_mb(self.settings.cgroup_root, path)
163
+ if anon is not None:
164
+ containers.append(ContainerMemory(container=name, anon_mb=anon))
165
+
166
+ self.snapshot = NodeSnapshot(
167
+ node=self.settings.node,
168
+ taken_at=wall,
169
+ agent_version=argus_iris.__version__,
170
+ gpus=sample.gpus,
171
+ processes=processes,
172
+ host=procfs.read_host_memory(self.settings.proc_root / "meminfo"),
173
+ containers=containers,
174
+ nvml_error=sample.error,
175
+ )
176
+ self.last_poll_monotonic = now
177
+ self.docker_error = self._poll_docker_error # a Docker failure is reported only while it lasts
178
+ return self.snapshot
179
+
180
+ async def act(self, name: str, action: ContainerAction) -> ActionResult:
181
+ try:
182
+ outcome = await self.docker.act(name, action)
183
+ except DockerError as exc:
184
+ log.warning("container_action_failed", container=name, action=action.value, error=str(exc))
185
+ return ActionResult(container=name, action=action, ok=False, detail=str(exc))
186
+ log.info("container_action", container=name, action=action.value, outcome=outcome)
187
+ return ActionResult(container=name, action=action, ok=True, detail=outcome)
188
+
189
+
190
+ class _SnapshotCollector:
191
+ def __init__(self, agent: Agent) -> None:
192
+ self.agent = agent
193
+
194
+ def collect(self):
195
+ snap = self.agent.snapshot
196
+ node = self.agent.settings.node
197
+ total = GaugeMetricFamily("iris_agent_gpu_vram_total_mb", "Total VRAM", labels=["node", "gpu"])
198
+ free = GaugeMetricFamily("iris_agent_gpu_vram_free_mb", "Free VRAM (NVML)", labels=["node", "gpu"])
199
+ util = GaugeMetricFamily("iris_agent_gpu_util_pct", "GPU utilisation", labels=["node", "gpu"])
200
+ pvram = GaugeMetricFamily(
201
+ "iris_agent_process_vram_mb", "VRAM per process", labels=["node", "gpu", "service", "container", "pid"]
202
+ )
203
+ pidle = GaugeMetricFamily(
204
+ "iris_agent_process_idle_seconds",
205
+ "Seconds since the process last changed VRAM or used the GPU",
206
+ labels=["node", "gpu", "service", "container", "pid"],
207
+ )
208
+ ram = GaugeMetricFamily("iris_agent_host_ram_available_mb", "Host MemAvailable", labels=["node"])
209
+ anon = GaugeMetricFamily(
210
+ "iris_agent_container_anon_mb", "Container anonymous memory (cgroup)", labels=["node", "container"]
211
+ )
212
+ up = GaugeMetricFamily("iris_agent_nvml_up", "1 when the last NVML sample succeeded", labels=["node"])
213
+ if snap:
214
+ up.add_metric([node], 0.0 if snap.nvml_error else 1.0)
215
+ for g in snap.gpus:
216
+ total.add_metric([node, str(g.index)], g.total_mb)
217
+ free.add_metric([node, str(g.index)], g.free_mb)
218
+ if g.util_pct is not None:
219
+ util.add_metric([node, str(g.index)], g.util_pct)
220
+ for p in snap.processes:
221
+ labels = [node, str(p.gpu), p.service or "", p.container or "", str(p.pid)]
222
+ pvram.add_metric(labels, p.vram_mb)
223
+ pidle.add_metric(labels, p.idle_s)
224
+ if snap.host:
225
+ ram.add_metric([node], snap.host.available_mb)
226
+ for c in snap.containers:
227
+ anon.add_metric([node, c.container], c.anon_mb)
228
+ yield from (total, free, util, pvram, pidle, ram, anon, up)
229
+
230
+
231
+ def create_app(settings: AgentSettings | None = None, *, agent: Agent | None = None, poll: bool = True) -> FastAPI:
232
+ settings = settings or (agent.settings if agent else AgentSettings.from_env())
233
+ agent = agent or Agent(settings)
234
+ registry = CollectorRegistry(auto_describe=False)
235
+ registry.register(_SnapshotCollector(agent))
236
+
237
+ async def _poller() -> None:
238
+ while True:
239
+ try:
240
+ await agent.poll_once()
241
+ except Exception: # noqa: BLE001 - keep polling; the failure is logged
242
+ log.exception("agent_poll_failed")
243
+ await asyncio.sleep(settings.poll_s)
244
+
245
+ @contextlib.asynccontextmanager
246
+ async def lifespan(app: FastAPI) -> AsyncIterator[None]:
247
+ task = asyncio.create_task(_poller(), name="iris-agent-poll") if poll else None
248
+ log.info(
249
+ "agent_started",
250
+ node=settings.node,
251
+ poll_s=settings.poll_s,
252
+ actions="enabled" if settings.token else "disabled (no IRIS_AGENT_TOKEN)",
253
+ containers=sorted(settings.containers),
254
+ )
255
+ try:
256
+ yield
257
+ finally:
258
+ if task:
259
+ task.cancel()
260
+ with contextlib.suppress(asyncio.CancelledError):
261
+ await task
262
+ await agent.aclose()
263
+
264
+ app = FastAPI(title="iris-agent", version=argus_iris.__version__, lifespan=lifespan)
265
+ app.state.agent = agent
266
+
267
+ @app.get("/snapshot", response_model=NodeSnapshot)
268
+ async def snapshot() -> NodeSnapshot:
269
+ if agent.snapshot is None:
270
+ raise HTTPException(503, "no sample yet")
271
+ return agent.snapshot
272
+
273
+ @app.get("/health")
274
+ async def health() -> dict:
275
+ snap = agent.snapshot
276
+ age = None if agent.last_poll_monotonic is None else round(time.monotonic() - agent.last_poll_monotonic, 1)
277
+ return {
278
+ "status": "ok" if snap and not snap.nvml_error else "degraded",
279
+ "node": settings.node,
280
+ "version": argus_iris.__version__,
281
+ "last_poll_age_s": age,
282
+ "nvml_error": snap.nvml_error if snap else None,
283
+ "docker_error": agent.docker_error,
284
+ "actions_enabled": bool(settings.token),
285
+ }
286
+
287
+ @app.get("/metrics")
288
+ async def metrics() -> Response:
289
+ return Response(generate_latest(registry), media_type=CONTENT_TYPE_LATEST)
290
+
291
+ @app.post("/containers/{name}/{action}", response_model=ActionResult)
292
+ async def container_action(
293
+ name: str, action: ContainerAction, authorization: str | None = Header(default=None)
294
+ ) -> ActionResult:
295
+ if not settings.token:
296
+ raise HTTPException(403, "container actions are disabled: IRIS_AGENT_TOKEN is not set")
297
+ scheme, _, presented = (authorization or "").partition(" ")
298
+ if scheme.lower() != "bearer" or not hmac.compare_digest(presented.encode(), settings.token.encode()):
299
+ raise HTTPException(401, "bad or missing bearer token", headers={"WWW-Authenticate": "Bearer"})
300
+ if name not in settings.containers:
301
+ raise HTTPException(403, f"container {name!r} is not on this agent's allowlist")
302
+ result = await agent.act(name, action)
303
+ if not result.ok:
304
+ raise HTTPException(502, result.detail or "docker action failed")
305
+ return result
306
+
307
+ return app
@@ -0,0 +1,88 @@
1
+ """A minimal Docker Engine API client over the Unix socket: inspect, start, stop, restart.
2
+
3
+ Only what the agent needs, so it does not pull in the Docker SDK.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import re
9
+ from dataclasses import dataclass
10
+
11
+ import httpx
12
+
13
+ from argus_iris.models import ContainerAction
14
+
15
+ DEFAULT_SOCKET = "/var/run/docker.sock"
16
+ # Docker's container name grammar (an ID matches it too). It has no "/", "?" or "#", so a ref cannot step out of
17
+ # /containers/{ref}/ to another Engine endpoint on the root-equivalent socket.
18
+ _REF = re.compile(r"/?[a-zA-Z0-9][a-zA-Z0-9_.-]*")
19
+
20
+
21
+ class DockerError(RuntimeError):
22
+ pass
23
+
24
+
25
+ def _checked(ref: str) -> str:
26
+ if not _REF.fullmatch(ref):
27
+ raise DockerError(f"not a container name or ID: {ref!r}")
28
+ return ref.lstrip("/")
29
+
30
+
31
+ @dataclass(frozen=True)
32
+ class ContainerInfo:
33
+ id: str
34
+ name: str
35
+ service: str # compose service label, else the container name
36
+ running: bool
37
+ pid: int | None # main process, host PID namespace
38
+
39
+
40
+ def parse_inspect(data: dict) -> ContainerInfo:
41
+ name = (data.get("Name") or "").lstrip("/") or data.get("Id", "")[:12]
42
+ labels = (data.get("Config") or {}).get("Labels") or {}
43
+ state = data.get("State") or {}
44
+ pid = state.get("Pid") or None
45
+ return ContainerInfo(
46
+ id=data.get("Id", ""),
47
+ name=name,
48
+ service=labels.get("com.docker.compose.service") or name,
49
+ running=bool(state.get("Running")),
50
+ pid=pid,
51
+ )
52
+
53
+
54
+ class DockerClient:
55
+ def __init__(self, socket_path: str = DEFAULT_SOCKET, *, transport: httpx.AsyncBaseTransport | None = None) -> None:
56
+ self._client = httpx.AsyncClient(
57
+ transport=transport or httpx.AsyncHTTPTransport(uds=socket_path),
58
+ base_url="http://docker",
59
+ timeout=httpx.Timeout(10.0, read=40.0), # stop/restart wait up to the container's stop timeout
60
+ )
61
+
62
+ async def aclose(self) -> None:
63
+ await self._client.aclose()
64
+
65
+ async def inspect(self, ref: str) -> ContainerInfo | None:
66
+ """A container by ID or name; ``None`` when it does not exist."""
67
+ try:
68
+ resp = await self._client.get(f"/containers/{_checked(ref)}/json")
69
+ except httpx.HTTPError as exc:
70
+ raise DockerError(f"docker unreachable: {exc}") from exc
71
+ if resp.status_code == 404:
72
+ return None
73
+ if resp.status_code != 200:
74
+ raise DockerError(f"inspect {ref}: HTTP {resp.status_code}")
75
+ return parse_inspect(resp.json())
76
+
77
+ async def act(self, name: str, action: ContainerAction) -> str:
78
+ """Run *action*; returns ``"done"`` or ``"unchanged"`` (already in that state)."""
79
+ try:
80
+ resp = await self._client.post(f"/containers/{_checked(name)}/{action.value}")
81
+ except httpx.HTTPError as exc:
82
+ raise DockerError(f"docker unreachable: {exc}") from exc
83
+ if resp.status_code == 204:
84
+ return "done"
85
+ if resp.status_code == 304:
86
+ return "unchanged"
87
+ detail = resp.text[:200]
88
+ raise DockerError(f"{action.value} {name}: HTTP {resp.status_code} {detail}")
@@ -0,0 +1,117 @@
1
+ """NVML sampling: card memory and utilisation, per-process VRAM and SM utilisation.
2
+
3
+ Synchronous (pynvml is); the agent calls :meth:`NvmlSampler.sample` from a worker thread.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import threading
9
+ from dataclasses import dataclass, field
10
+
11
+ from argus_iris.models import MIB, GpuInfo
12
+
13
+
14
+ @dataclass(frozen=True)
15
+ class RawProcess:
16
+ gpu: int
17
+ pid: int
18
+ vram_mb: int
19
+
20
+
21
+ @dataclass
22
+ class Sample:
23
+ gpus: list[GpuInfo] = field(default_factory=list)
24
+ processes: list[RawProcess] = field(default_factory=list)
25
+ # pid -> max SM utilisation since the last sample. ``None`` per GPU when the driver does not report it.
26
+ proc_util: dict[int, dict[int, int] | None] = field(default_factory=dict)
27
+ error: str | None = None
28
+
29
+
30
+ def _text(value: str | bytes) -> str:
31
+ return value.decode() if isinstance(value, bytes) else value
32
+
33
+
34
+ class NvmlSampler:
35
+ def __init__(self) -> None:
36
+ self._lock = threading.Lock()
37
+ self._ready = False
38
+ self._last_util_ts: dict[int, int] = {}
39
+
40
+ def _init(self):
41
+ import pynvml # noqa: PLC0415 - behind the [agent] extra
42
+
43
+ if not self._ready:
44
+ pynvml.nvmlInit()
45
+ self._ready = True
46
+ return pynvml
47
+
48
+ def close(self) -> None:
49
+ with self._lock:
50
+ if self._ready:
51
+ import pynvml # noqa: PLC0415
52
+
53
+ pynvml.nvmlShutdown()
54
+ self._ready = False
55
+
56
+ def sample(self) -> Sample:
57
+ with self._lock:
58
+ try:
59
+ nv = self._init()
60
+ return self._sample(nv)
61
+ except Exception as exc: # noqa: BLE001 - any NVML failure becomes a reported error, not a crash
62
+ self._ready = False # re-init next time (driver reload, container restart)
63
+ return Sample(error=f"{type(exc).__name__}: {exc}")
64
+
65
+ def _sample(self, nv) -> Sample:
66
+ out = Sample()
67
+ for idx in range(nv.nvmlDeviceGetCount()):
68
+ handle = nv.nvmlDeviceGetHandleByIndex(idx)
69
+ mem = nv.nvmlDeviceGetMemoryInfo(handle)
70
+ try:
71
+ util = int(nv.nvmlDeviceGetUtilizationRates(handle).gpu)
72
+ except nv.NVMLError:
73
+ util = None
74
+ try:
75
+ major, minor = nv.nvmlDeviceGetCudaComputeCapability(handle)
76
+ cc, bf16 = f"{major}.{minor}", major >= 8
77
+ except nv.NVMLError:
78
+ cc, bf16 = None, None
79
+ out.gpus.append(
80
+ GpuInfo(
81
+ index=idx,
82
+ name=_text(nv.nvmlDeviceGetName(handle)),
83
+ uuid=_text(nv.nvmlDeviceGetUUID(handle)),
84
+ total_mb=int(mem.total) // MIB,
85
+ free_mb=int(mem.free) // MIB,
86
+ used_mb=int(mem.used) // MIB,
87
+ util_pct=util,
88
+ compute_capability=cc,
89
+ bf16=bf16,
90
+ )
91
+ )
92
+ # Compute (CUDA) and graphics (the desktop's Xorg) both hold VRAM; a process can be in both lists.
93
+ vram: dict[int, int] = {}
94
+ for getter in (nv.nvmlDeviceGetComputeRunningProcesses, nv.nvmlDeviceGetGraphicsRunningProcesses):
95
+ try:
96
+ procs = getter(handle)
97
+ except nv.NVMLError:
98
+ continue
99
+ for p in procs:
100
+ used = int(p.usedGpuMemory or 0) // MIB # None where the driver cannot attribute (WSL)
101
+ vram[p.pid] = max(vram.get(p.pid, 0), used)
102
+ out.processes.extend(RawProcess(gpu=idx, pid=pid, vram_mb=mb) for pid, mb in vram.items())
103
+ out.proc_util[idx] = self._process_util(nv, idx, handle)
104
+ return out
105
+
106
+ def _process_util(self, nv, idx: int, handle) -> dict[int, int] | None:
107
+ try:
108
+ samples = nv.nvmlDeviceGetProcessUtilization(handle, self._last_util_ts.get(idx, 0))
109
+ except nv.NVMLError_NotFound:
110
+ return {} # no samples since the last call: nothing ran
111
+ except nv.NVMLError:
112
+ return None # not supported on this card/driver
113
+ util: dict[int, int] = {}
114
+ for s in samples:
115
+ util[s.pid] = max(util.get(s.pid, 0), int(s.smUtil))
116
+ self._last_util_ts[idx] = max(self._last_util_ts.get(idx, 0), int(s.timeStamp))
117
+ return util
@@ -0,0 +1,82 @@
1
+ """Reading /proc and cgroup v2 files: container IDs, host memory, container anonymous memory.
2
+
3
+ Pure functions over paths, so tests point them at a temp directory.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import re
9
+ from pathlib import Path
10
+
11
+ from argus_iris.models import MIB, HostMemory
12
+
13
+ # A container ID is 64 hex characters. Seen as:
14
+ # 0::/system.slice/docker-<id>.scope (systemd cgroup driver)
15
+ # 0::/docker/<id> (cgroupfs driver)
16
+ # 0::/kubepods/.../cri-containerd-<id>.scope (containerd)
17
+ # 0::/.../libpod-<id>.scope (podman)
18
+ _CONTAINER_ID = re.compile(r"(?:^|[/-])([0-9a-f]{64})(?:\.scope)?(?:/|$)")
19
+
20
+
21
+ def read_cgroup(proc_root: Path, pid: int) -> str | None:
22
+ try:
23
+ return (proc_root / str(pid) / "cgroup").read_text()
24
+ except OSError:
25
+ return None
26
+
27
+
28
+ def cgroup_v2_path(cgroup_text: str) -> str | None:
29
+ """The unified-hierarchy path (the ``0::`` line), e.g. ``/system.slice/docker-<id>.scope``.
30
+
31
+ ``None`` for a path relative to a private cgroup namespace (``/../..``): the agent then runs without
32
+ ``cgroup: host`` and the path cannot be found under the host's ``/sys/fs/cgroup``.
33
+ """
34
+ for line in cgroup_text.splitlines():
35
+ if line.startswith("0::"):
36
+ path = line[3:].strip()
37
+ return path if path and not path.startswith("/..") else None
38
+ return None
39
+
40
+
41
+ def container_id_from_cgroup(cgroup_text: str) -> str | None:
42
+ """The container ID a process belongs to, or ``None`` for a host process."""
43
+ for line in cgroup_text.splitlines():
44
+ path = line.split(":", 2)[-1]
45
+ match = _CONTAINER_ID.search(path)
46
+ if match:
47
+ return match.group(1)
48
+ return None
49
+
50
+
51
+ def read_host_memory(meminfo: Path) -> HostMemory | None:
52
+ try:
53
+ text = meminfo.read_text()
54
+ except OSError:
55
+ return None
56
+ fields: dict[str, int] = {}
57
+ for line in text.splitlines():
58
+ key, _, rest = line.partition(":")
59
+ parts = rest.split()
60
+ if parts and parts[0].isdigit():
61
+ fields[key] = int(parts[0]) # kB
62
+ if "MemTotal" not in fields or "MemAvailable" not in fields:
63
+ return None
64
+ return HostMemory(total_mb=fields["MemTotal"] // 1024, available_mb=fields["MemAvailable"] // 1024)
65
+
66
+
67
+ def read_anon_mb(cgroup_root: Path, cgroup_path: str) -> int | None:
68
+ """``anon`` from a cgroup's ``memory.stat``, in MiB.
69
+
70
+ Anonymous memory is what ComfyUI's offloaded weights occupy and what only a restart returns (voluptas #16); page
71
+ cache is reclaimable and not counted.
72
+ """
73
+ stat = cgroup_root / cgroup_path.lstrip("/") / "memory.stat"
74
+ try:
75
+ text = stat.read_text()
76
+ except OSError:
77
+ return None
78
+ for line in text.splitlines():
79
+ key, _, value = line.partition(" ")
80
+ if key == "anon" and value.strip().isdigit():
81
+ return int(value) // MIB
82
+ return None