0.3.0: card CPU toccabile con dettaglio per servizio/container
This commit is contained in:
1 parent
227c423d73
commit
70f7ac4bd2
7 files changed
+313
-46
No files matched your search
+160
-35
@@ -34,6 +34,10 @@ BORG_MARKER = "/var/lib/borg-last-run"
|
||||
|
||||
CGROUP_ROOT = Path("/sys/fs/cgroup")
|
||||
|
||||
# Ultima lettura di cpu.stat per cgroup: serve a calcolare la percentuale come
|
||||
# differenza fra due giri del timer (60 s), senza misurare sul posto.
|
||||
CPU_STATE = Path.home() / ".cache" / "statusd" / "cpu-usage.json"
|
||||
|
||||
|
||||
# ── helper ────────────────────────────────────────────────────────────────
|
||||
def run(cmd: list[str], timeout: float = 4.0) -> str:
|
||||
@@ -77,12 +81,26 @@ def _cpu_ticks() -> tuple[int, int]:
|
||||
return idle, sum(vals)
|
||||
|
||||
|
||||
def cpu_info(sample: float = 0.1) -> dict:
|
||||
i0, t0 = _cpu_ticks()
|
||||
time.sleep(sample)
|
||||
i1, t1 = _cpu_ticks()
|
||||
dt, di = t1 - t0, i1 - i0
|
||||
percent = max(0.0, min(100.0, 100.0 * (dt - di) / dt)) if dt > 0 else 0.0
|
||||
def cpu_info() -> dict:
|
||||
"""CPU totale e per servizio, misurate sulla STESSA finestra.
|
||||
|
||||
cpu.stat è gerarchico: il genitore include i figli. Per la classifica serve
|
||||
quindi il delta di ogni cgroup meno quello dei suoi discendenti, altrimenti
|
||||
`system.slice` e la radice finirebbero in cima con il totale della macchina.
|
||||
"""
|
||||
cores = os.cpu_count() or 1
|
||||
now = time.time()
|
||||
cur = _cgroup_cpu_usec()
|
||||
base, cur, dt = _cpu_baseline(now, cur)
|
||||
|
||||
deltas = {
|
||||
path: usec - base[path] for path, usec in cur.items() if path in base
|
||||
}
|
||||
root = str(CGROUP_ROOT)
|
||||
if root in deltas and dt > 0:
|
||||
percent = max(0.0, min(100.0, deltas[root] / 1_000_000.0 / (dt * cores) * 100.0))
|
||||
else:
|
||||
percent = 0.0
|
||||
|
||||
temps = []
|
||||
for zone in sorted(Path("/sys/class/thermal").glob("thermal_zone*/temp")):
|
||||
@@ -93,10 +111,40 @@ def cpu_info(sample: float = 0.1) -> dict:
|
||||
return {
|
||||
"percent": round(percent, 1),
|
||||
"temp_c": round(max(temps), 1) if temps else None,
|
||||
"cores": os.cpu_count(),
|
||||
"cores": cores,
|
||||
"consumers": _cgroup_rows_cpu(deltas, dt, cores),
|
||||
}
|
||||
|
||||
|
||||
def _cgroup_label(path: str, docker_names: dict) -> tuple[str, str]:
|
||||
"""(nome leggibile, tipo) dall'ultimo componente del path del cgroup."""
|
||||
leaf = path.rsplit("/", 1)[-1]
|
||||
kind = "service"
|
||||
name = leaf
|
||||
if leaf.startswith("docker-") and leaf.endswith(".scope"):
|
||||
cid = leaf[len("docker-") : -len(".scope")]
|
||||
name = docker_names.get(cid[:12], cid[:12])
|
||||
kind = "container"
|
||||
elif leaf.endswith(".service"):
|
||||
name = leaf[: -len(".service")]
|
||||
elif leaf.endswith(".scope"):
|
||||
name = leaf[: -len(".scope")]
|
||||
kind = "session"
|
||||
elif leaf.endswith(".slice"):
|
||||
name = leaf[: -len(".slice")]
|
||||
kind = "slice"
|
||||
return name, kind
|
||||
|
||||
|
||||
def _docker_names() -> dict:
|
||||
names = {}
|
||||
for line in run(["docker", "ps", "--format", "{{.ID}} {{.Names}}"]).splitlines():
|
||||
parts = line.split()
|
||||
if len(parts) >= 2:
|
||||
names[parts[0]] = parts[1]
|
||||
return names
|
||||
|
||||
|
||||
def _cgroup_anon(path: Path) -> int | None:
|
||||
"""Memoria anonima (heap, stack: RAM vera) di un cgroup, in byte."""
|
||||
try:
|
||||
@@ -109,6 +157,19 @@ def _cgroup_anon(path: Path) -> int | None:
|
||||
return None
|
||||
|
||||
|
||||
def _walk_cgroups() -> list[Path]:
|
||||
found = []
|
||||
stack = [CGROUP_ROOT]
|
||||
while stack:
|
||||
path = stack.pop()
|
||||
found.append(path)
|
||||
try:
|
||||
stack.extend(p for p in path.iterdir() if p.is_dir())
|
||||
except OSError:
|
||||
pass
|
||||
return found
|
||||
|
||||
|
||||
def memory_consumers(limit: int = 12, min_mb: int = 16) -> list[dict]:
|
||||
"""Chi occupa la RAM, ordinato dal più grande.
|
||||
|
||||
@@ -119,23 +180,12 @@ def memory_consumers(limit: int = 12, min_mb: int = 16) -> list[dict]:
|
||||
anche i figli e la somma sballerebbe.
|
||||
"""
|
||||
anon: dict[str, int] = {}
|
||||
stack = [CGROUP_ROOT]
|
||||
while stack:
|
||||
path = stack.pop()
|
||||
try:
|
||||
stack.extend(p for p in path.iterdir() if p.is_dir())
|
||||
except OSError:
|
||||
pass
|
||||
for path in _walk_cgroups():
|
||||
value = _cgroup_anon(path)
|
||||
if value:
|
||||
anon[str(path)] = value
|
||||
|
||||
# system.slice/docker-<id>.scope -> nome del contenitore
|
||||
docker_names = {}
|
||||
for line in run(["docker", "ps", "--format", "{{.ID}} {{.Names}}"]).splitlines():
|
||||
parts = line.split()
|
||||
if len(parts) >= 2:
|
||||
docker_names[parts[0]] = parts[1]
|
||||
docker_names = _docker_names()
|
||||
|
||||
rows = []
|
||||
for path, value in anon.items():
|
||||
@@ -145,27 +195,102 @@ def memory_consumers(limit: int = 12, min_mb: int = 16) -> list[dict]:
|
||||
exclusive = value - children
|
||||
if exclusive < min_mb * 1024 * 1024:
|
||||
continue
|
||||
leaf = path.rsplit("/", 1)[-1]
|
||||
kind = "service"
|
||||
name = leaf
|
||||
if leaf.startswith("docker-") and leaf.endswith(".scope"):
|
||||
cid = leaf[len("docker-") : -len(".scope")]
|
||||
name = docker_names.get(cid[:12], cid[:12])
|
||||
kind = "container"
|
||||
elif leaf.endswith(".service"):
|
||||
name = leaf[: -len(".service")]
|
||||
elif leaf.endswith(".scope"):
|
||||
name = leaf[: -len(".scope")]
|
||||
kind = "session"
|
||||
elif leaf.endswith(".slice"):
|
||||
name = leaf[: -len(".slice")]
|
||||
kind = "slice"
|
||||
name, kind = _cgroup_label(path, docker_names)
|
||||
rows.append({"name": name, "kind": kind, "bytes": exclusive})
|
||||
|
||||
rows.sort(key=lambda row: -row["bytes"])
|
||||
return rows[:limit]
|
||||
|
||||
|
||||
def _cgroup_cpu_usec() -> dict[str, int]:
|
||||
"""Tempo di CPU consumato da ogni cgroup, in microsecondi.
|
||||
|
||||
cpu.stat non è ricorsivo: ogni cgroup conta solo i propri task, quindi non
|
||||
serve sottrarre i discendenti come per la memoria.
|
||||
"""
|
||||
usage = {}
|
||||
for path in _walk_cgroups():
|
||||
try:
|
||||
with open(path / "cpu.stat") as fh:
|
||||
for line in fh:
|
||||
if line.startswith("usage_usec "):
|
||||
usage[str(path)] = int(line.split()[1])
|
||||
break
|
||||
except OSError:
|
||||
continue
|
||||
return usage
|
||||
|
||||
|
||||
def _save_cpu_state(when: float, usage: dict[str, int]) -> None:
|
||||
try:
|
||||
CPU_STATE.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(CPU_STATE, "w") as fh:
|
||||
json.dump({"t": when, "usage": usage}, fh)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def _cpu_baseline(
|
||||
now: float, current: dict[str, int]
|
||||
) -> tuple[dict[str, int], dict[str, int], float]:
|
||||
"""Lettura di riferimento, lettura attuale e intervallo trascorso.
|
||||
|
||||
Uso la lettura salvata al giro precedente (~60 s, la stessa finestra del
|
||||
timer). Se manca o è troppo vecchia misuro sul posto per un secondo: senza
|
||||
riferimento non esiste percentuale, e uno zero sarebbe una bugia.
|
||||
"""
|
||||
prev = None
|
||||
try:
|
||||
with open(CPU_STATE) as fh:
|
||||
prev = json.load(fh)
|
||||
except (OSError, ValueError):
|
||||
prev = None
|
||||
|
||||
if prev and isinstance(prev.get("usage"), dict):
|
||||
dt = now - float(prev.get("t", 0))
|
||||
if 5 <= dt <= 300:
|
||||
_save_cpu_state(now, current)
|
||||
return prev["usage"], current, dt
|
||||
|
||||
time.sleep(1.0)
|
||||
later = _cgroup_cpu_usec()
|
||||
_save_cpu_state(now, later)
|
||||
return current, later, 1.0
|
||||
|
||||
|
||||
def _cgroup_rows_cpu(
|
||||
deltas: dict[str, int], dt: float, cores: int, limit: int = 12, min_pct: float = 0.5
|
||||
) -> list[dict]:
|
||||
"""Classifica CPU esclusiva per cgroup, dal più affamato.
|
||||
|
||||
Scarto la radice e le slice di primo livello (`system.slice`, `user.slice`):
|
||||
essendo gerarchico il loro valore è il totale della macchina e coprirebbe
|
||||
tutti gli altri. Per gli altri sottraggo i discendenti.
|
||||
"""
|
||||
if dt <= 0:
|
||||
return []
|
||||
docker_names = _docker_names()
|
||||
root = str(CGROUP_ROOT)
|
||||
rows = []
|
||||
for path, delta in deltas.items():
|
||||
if path == root:
|
||||
continue
|
||||
relative = path[len(root) :].strip("/")
|
||||
if not relative or "/" not in relative:
|
||||
continue
|
||||
children = sum(
|
||||
dd for p, dd in deltas.items() if p != path and p.startswith(path + "/")
|
||||
)
|
||||
percent = (delta - children) / 1_000_000.0 / (dt * cores) * 100.0
|
||||
if percent < min_pct:
|
||||
continue
|
||||
name, kind = _cgroup_label(path, docker_names)
|
||||
rows.append({"name": name, "kind": kind, "percent": round(percent, 1)})
|
||||
|
||||
rows.sort(key=lambda row: -row["percent"])
|
||||
return rows[:limit]
|
||||
|
||||
|
||||
def memory_info() -> dict:
|
||||
mem = {}
|
||||
for line in Path("/proc/meminfo").read_text().splitlines():
|
||||
|
||||
Reference in new issue
Block a user