From 0c9dd7c9b39a6128a5f1faf79d5736a7a19aec42 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Gro=C3=9F?= Date: Tue, 17 Nov 2026 10:56:42 +0100 Subject: [PATCH] feat: report the busiest processes in /api/stats Co-Authored-By: Claude Sonnet 5.5 --- README.md | 2 +- app/stats.py | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 8b1c749..48052f4 100644 --- a/README.md +++ b/README.md @@ -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` | diff --git a/app/stats.py b/app/stats.py index ff3d356..23146f6 100644 --- a/app/stats.py +++ b/app/stats.py @@ -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(), }