feat: report the busiest processes in /api/stats

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Jan GroßandClaude Sonnet 5.5 committed 2026-11-17 10:56:42 +01:00
1 parent fbae64a11a
commit 0c9dd7c9b3
2 files changed
+35 -1

No files matched your search

+1 -1
View File
@@ -46,7 +46,7 @@ view instead of the host's:
| Mount | Why |
|-------|-----|
| `/proc:/host/proc:ro` | CPU, memory, swap, load average, uptime, disk/network stats |
| `/proc:/host/proc:ro` | CPU, memory, swap, load average, uptime, disk/network stats, and the busiest processes (name, CPU, memory — never command lines) |
| `/sys:/host/sys:ro` | reserved for future use; harmless to include now |
| `/:/host/root:ro` | resolves each disk partition's real usage, and the host's `/etc/hostname` |
+34
View File
@@ -182,6 +182,39 @@ def _network() -> dict:
return {"hostNamespace": use_pid1, "interfaces": interfaces}
PROCESS_KEEP = 25
def _processes() -> list[dict]:
"""The busiest processes: the top by CPU together with the top by memory.
psutil.process_iter() keeps its Process objects between calls, which is what
lets cpu_percent report usage since the previous poll (so the very first
poll after a start reads 0). Only the process name is reported, never the
command line, which often carries secrets. CPU is relative to one core, as
in top, so a busy multi-threaded process can exceed 100."""
rows = []
for proc in psutil.process_iter(["pid", "name", "username", "memory_info", "memory_percent", "cpu_percent"]):
info = proc.info
memory = info.get("memory_info")
if not info.get("name") or memory is None or memory.rss <= 0:
continue # kernel threads and processes that vanished mid-scan
rows.append(
{
"pid": info["pid"],
"name": info["name"],
"user": info.get("username") or "",
"cpuPercent": round(info.get("cpu_percent") or 0.0, 1),
"memoryPercent": round(info.get("memory_percent") or 0.0, 1),
"memoryBytes": memory.rss,
}
)
by_cpu = sorted(rows, key=lambda r: r["cpuPercent"], reverse=True)[:PROCESS_KEEP]
by_memory = sorted(rows, key=lambda r: r["memoryBytes"], reverse=True)[:PROCESS_KEEP]
merged = {r["pid"]: r for r in by_cpu + by_memory}
return sorted(merged.values(), key=lambda r: r["cpuPercent"], reverse=True)
def collect() -> dict:
# A single percpu=True call gives every core's percent over the same
# sampling window; the overall figure is derived from it (its mean)
@@ -215,4 +248,5 @@ def collect() -> dict:
},
"disks": _disks(),
"network": _network(),
"processes": _processes(),
}