0.3.0: card CPU toccabile con dettaglio per servizio/container
This commit is contained in:
1 parent
227c423d73
commit
70f7ac4bd2
7 files changed
+333
-66
No files matched your search
@@ -22,11 +22,11 @@ Card impilate con valore, dettaglio e barra; soglie: verde, giallo all'85%,
|
||||
rosso al 95%. Pull-to-refresh, aggiornamento automatico ogni 60 s, copertina
|
||||
con CPU/RAM/disco in percentuale, badge rosso sulle card fuori soglia.
|
||||
|
||||
La card **Memoria** è toccabile (chevron a destra) e apre il dettaglio dei
|
||||
consumatori di RAM ordinati dal più grande. Con `/proc` montato `hidepid=invisible`
|
||||
il singolo PID degli altri utenti non è leggibile senza root: l'unità è quindi
|
||||
il **servizio o il contenitore** (memoria anonima dei cgroup v2), che è la stessa
|
||||
grandezza mostrata dalla card.
|
||||
Le card **CPU** e **Memoria** sono toccabili (chevron a destra) e aprono il
|
||||
dettaglio dei consumatori ordinati dal più grande. Con `/proc` montato
|
||||
`hidepid=invisible` il singolo PID degli altri utenti non è leggibile senza
|
||||
root: l'unità è quindi il **servizio o il contenitore**, misurata sui cgroup v2
|
||||
(memoria anonima e tempo di CPU), che è la stessa grandezza mostrata dalla card.
|
||||
|
||||
## Build
|
||||
|
||||
@@ -40,7 +40,7 @@ Requisiti: SDK Sailfish in `~/SailfishOS`, build engine Docker.
|
||||
## Installazione sul telefono
|
||||
|
||||
```sh
|
||||
devel-su rpm -Uvh harbour-server-0.2.0-1.aarch64.rpm
|
||||
devel-su rpm -Uvh harbour-server-0.3.0-1.aarch64.rpm
|
||||
```
|
||||
|
||||
Poi, all'apertura: indicare indirizzo (es. `http://192.168.3.21:8792`) e token.
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
import QtQuick 2.0
|
||||
import Sailfish.Silica 1.0
|
||||
|
||||
// Dettaglio della card CPU: chi consuma processore, dal più affamato.
|
||||
// Come per la memoria, con hidepid=invisible il singolo PID degli altri utenti
|
||||
// non è leggibile da /proc: l'unità è il servizio o il contenitore, misurata
|
||||
// sul tempo di CPU dei cgroup v2.
|
||||
Page {
|
||||
id: page
|
||||
allowedOrientations: Orientation.All
|
||||
|
||||
function list() {
|
||||
var d = statusClient.data
|
||||
if (!d || !d.cpu || !d.cpu.consumers) return []
|
||||
return d.cpu.consumers
|
||||
}
|
||||
function maxPercent() {
|
||||
var l = list()
|
||||
return (l.length > 0 && l[0].percent > 0) ? l[0].percent : 1
|
||||
}
|
||||
function cores() {
|
||||
var d = statusClient.data
|
||||
return (d && d.cpu && d.cpu.cores) ? d.cpu.cores : 0
|
||||
}
|
||||
function headText() {
|
||||
var d = statusClient.data
|
||||
if (!d || !d.cpu) return ""
|
||||
var text = qsTr("adesso ") + statusClient.fmtNum(d.cpu.percent, 0) + "%"
|
||||
if (d.cpu.temp_c !== null && d.cpu.temp_c !== undefined)
|
||||
text += " · " + statusClient.fmtNum(d.cpu.temp_c, 0) + " °C"
|
||||
return text
|
||||
}
|
||||
function noteText() {
|
||||
var n = cores()
|
||||
if (n < 1) return qsTr("Percentuale sulla capacità totale del sistema, non sul singolo core.")
|
||||
return qsTr("Percentuale sulla capacità totale (") + n
|
||||
+ (n === 1 ? qsTr(" core), non sul singolo core.")
|
||||
: qsTr(" core), non sul singolo core."))
|
||||
}
|
||||
|
||||
SilicaListView {
|
||||
id: view
|
||||
anchors.fill: parent
|
||||
model: page.list()
|
||||
|
||||
header: Column {
|
||||
width: view.width
|
||||
spacing: Theme.paddingSmall
|
||||
|
||||
PageHeader { title: qsTr("CPU") }
|
||||
|
||||
Label {
|
||||
x: Theme.paddingLarge
|
||||
width: parent.width - 2 * Theme.paddingLarge
|
||||
text: page.headText()
|
||||
font.pixelSize: Theme.fontSizeSmall
|
||||
color: Theme.secondaryColor
|
||||
}
|
||||
|
||||
Label {
|
||||
x: Theme.paddingLarge
|
||||
width: parent.width - 2 * Theme.paddingLarge
|
||||
text: page.noteText()
|
||||
font.pixelSize: Theme.fontSizeExtraSmall
|
||||
color: Theme.secondaryColor
|
||||
wrapMode: Text.WordWrap
|
||||
}
|
||||
|
||||
Item { width: 1; height: Theme.paddingSmall }
|
||||
}
|
||||
|
||||
delegate: Column {
|
||||
x: Theme.paddingLarge
|
||||
width: view.width - 2 * Theme.paddingLarge
|
||||
spacing: Theme.paddingSmall / 2
|
||||
|
||||
Row {
|
||||
width: parent.width
|
||||
|
||||
Label {
|
||||
text: modelData.name + (modelData.kind === "container" ? qsTr(" · contenitore") : "")
|
||||
width: parent.width * 0.68
|
||||
font.pixelSize: Theme.fontSizeSmall
|
||||
truncationMode: TruncationMode.Fade
|
||||
}
|
||||
|
||||
Label {
|
||||
text: statusClient.fmtNum(modelData.percent, 1) + "%"
|
||||
width: parent.width * 0.32
|
||||
horizontalAlignment: Text.AlignRight
|
||||
font.pixelSize: Theme.fontSizeSmall
|
||||
color: Theme.highlightColor
|
||||
}
|
||||
}
|
||||
|
||||
Rectangle {
|
||||
width: parent.width * Math.max(2, Math.min(100, modelData.percent / page.maxPercent() * 100)) / 100
|
||||
height: 3
|
||||
radius: 1.5
|
||||
color: Theme.rgba(Theme.highlightColor, 0.5)
|
||||
}
|
||||
}
|
||||
|
||||
footer: Column {
|
||||
width: view.width
|
||||
spacing: Theme.paddingSmall
|
||||
|
||||
Label {
|
||||
x: Theme.paddingLarge
|
||||
width: parent.width - 2 * Theme.paddingLarge
|
||||
text: qsTr("Media della finestra di campionamento (circa un minuto). Le voci sotto lo 0,5% non sono elencate.")
|
||||
font.pixelSize: Theme.fontSizeExtraSmall
|
||||
color: Theme.secondaryColor
|
||||
wrapMode: Text.WordWrap
|
||||
}
|
||||
|
||||
Item { width: 1; height: Theme.paddingLarge }
|
||||
}
|
||||
|
||||
ViewPlaceholder {
|
||||
enabled: page.list().length === 0
|
||||
text: qsTr("Nessun dato")
|
||||
hintText: qsTr("Serve una seconda lettura del server per calcolare la percentuale")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,12 @@ Page {
|
||||
function cpuPct() { var d = statusClient.data; return (d && d.cpu && d.cpu.percent !== undefined) ? d.cpu.percent : -1 }
|
||||
function cpuTemp() { var d = statusClient.data; return (d && d.cpu && d.cpu.temp_c !== undefined) ? d.cpu.temp_c : -1 }
|
||||
function cpuCores() { var d = statusClient.data; return (d && d.cpu && d.cpu.cores !== undefined) ? d.cpu.cores : 0 }
|
||||
function cpuDetail() {
|
||||
var parts = []
|
||||
if (cpuTemp() >= 0) parts.push(statusClient.fmtNum(cpuTemp(), 0) + " °C")
|
||||
if (cpuCores() > 0) parts.push(cpuCores() + qsTr(" core"))
|
||||
return parts.join(" · ")
|
||||
}
|
||||
function memPercent() { var d = statusClient.data; return (d && d.memory && d.memory.percent !== undefined) ? d.memory.percent : -1 }
|
||||
function memText() {
|
||||
var d = statusClient.data
|
||||
@@ -212,9 +218,11 @@ Page {
|
||||
width: parent.width - 2 * Theme.paddingLarge
|
||||
title: qsTr("CPU")
|
||||
value: cpuPct() < 0 ? "—" : statusClient.fmtNum(cpuPct(), 0) + " %"
|
||||
detail: (cpuTemp() >= 0 ? statusClient.fmtNum(cpuTemp(), 0) + " °C · " : "") + cpuCores() + " core"
|
||||
detail: cpuDetail()
|
||||
progress: cpuPct()
|
||||
level: levelFor(cpuPct(), 85, 95)
|
||||
interactive: true
|
||||
onClicked: pageStack.push(Qt.resolvedUrl("CpuPage.qml"))
|
||||
}
|
||||
|
||||
MetricCard {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
Name: harbour-server
|
||||
Summary: Parametri del server in una schermata
|
||||
Version: 0.2.0
|
||||
Version: 0.3.0
|
||||
Release: 1
|
||||
Group: Qt/Qt
|
||||
License: MIT
|
||||
@@ -23,6 +23,12 @@ schermata sola. Il formato consumato (schema status/1) non dipende dalla
|
||||
macchina: qualunque host che serva lo stesso JSON funziona senza modifiche.
|
||||
|
||||
%changelog
|
||||
* Sat Oct 31 2026 Carlo Baratto <carlo@carlobaratto.it> - 0.3.0-1
|
||||
- Card CPU toccabile: apre CpuPage con i consumatori di CPU ordinati dal più
|
||||
grande, in percentuale sulla capacità totale del sistema
|
||||
- Collector: nuova chiave cpu.consumers dal delta di cpu.stat fra due giri del
|
||||
timer (~60 s); sottratti i discendenti, perché cpu.stat è gerarchico e
|
||||
system.slice avrebbe coperto tutto
|
||||
* Sat Oct 31 2026 Carlo Baratto <carlo@carlobaratto.it> - 0.2.0-1
|
||||
- Card Memoria toccabile: apre ProcessPage con i consumatori di RAM ordinati
|
||||
dal più grande (MB, % sul totale, barra comparativa)
|
||||
|
||||
+3
-1
@@ -78,7 +78,9 @@ Nessun log HTTP: il token non finisce su disco. Il server non ha altre rotte.
|
||||
"collected_at": "2026-10-27T19:12:21+00:00",
|
||||
"host": { "hostname": "…", "kernel": "…", "uptime_s": 209666,
|
||||
"boot_time": "…", "load": [0.3, 0.57, 0.48] },
|
||||
"cpu": { "percent": 7.1, "temp_c": 41.0, "cores": 4 },
|
||||
"cpu": { "percent": 7.1, "temp_c": 41.0, "cores": 4,
|
||||
"consumers": [ { "name": "gitea", "kind": "service",
|
||||
"percent": 3.2 } ] },
|
||||
"memory": { "total_bytes": 0, "used_bytes": 0, "percent": 0,
|
||||
"swap_total_bytes": 0, "swap_used_bytes": 0,
|
||||
"consumers": [ { "name": "hermes-webui", "kind": "service",
|
||||
|
||||
+180
-55
@@ -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,58 +111,13 @@ 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_anon(path: Path) -> int | None:
|
||||
"""Memoria anonima (heap, stack: RAM vera) di un cgroup, in byte."""
|
||||
try:
|
||||
with open(path / "memory.stat") as fh:
|
||||
for line in fh:
|
||||
if line.startswith("anon "):
|
||||
return int(line.split()[1])
|
||||
except OSError:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def memory_consumers(limit: int = 12, min_mb: int = 16) -> list[dict]:
|
||||
"""Chi occupa la RAM, ordinato dal più grande.
|
||||
|
||||
/proc è montato con hidepid=invisible: i processi degli altri utenti sono
|
||||
invisibili, quindi il dettaglio per PID non è ottenibile senza root. I
|
||||
cgroup v2 invece sono leggibili e danno la memoria anonima per unità o
|
||||
contenitore. Sottraggo i discendenti, altrimenti un genitore conterebbe
|
||||
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
|
||||
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]
|
||||
|
||||
rows = []
|
||||
for path, value in anon.items():
|
||||
children = sum(
|
||||
v for p, v in anon.items() if p != path and p.startswith(path + "/")
|
||||
)
|
||||
exclusive = value - children
|
||||
if exclusive < min_mb * 1024 * 1024:
|
||||
continue
|
||||
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
|
||||
@@ -160,12 +133,164 @@ def memory_consumers(limit: int = 12, min_mb: int = 16) -> list[dict]:
|
||||
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:
|
||||
with open(path / "memory.stat") as fh:
|
||||
for line in fh:
|
||||
if line.startswith("anon "):
|
||||
return int(line.split()[1])
|
||||
except OSError:
|
||||
return 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.
|
||||
|
||||
/proc è montato con hidepid=invisible: i processi degli altri utenti sono
|
||||
invisibili, quindi il dettaglio per PID non è ottenibile senza root. I
|
||||
cgroup v2 invece sono leggibili e danno la memoria anonima per unità o
|
||||
contenitore. Sottraggo i discendenti, altrimenti un genitore conterebbe
|
||||
anche i figli e la somma sballerebbe.
|
||||
"""
|
||||
anon: dict[str, int] = {}
|
||||
for path in _walk_cgroups():
|
||||
value = _cgroup_anon(path)
|
||||
if value:
|
||||
anon[str(path)] = value
|
||||
|
||||
docker_names = _docker_names()
|
||||
|
||||
rows = []
|
||||
for path, value in anon.items():
|
||||
children = sum(
|
||||
v for p, v in anon.items() if p != path and p.startswith(path + "/")
|
||||
)
|
||||
exclusive = value - children
|
||||
if exclusive < min_mb * 1024 * 1024:
|
||||
continue
|
||||
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():
|
||||
|
||||
+2
-2
@@ -15,9 +15,9 @@ Q_DECL_EXPORT int main(int argc, char *argv[])
|
||||
// AppConfigLocation = ~/.config/harbour/server (zona persistente).
|
||||
app->setOrganizationName(QStringLiteral("harbour"));
|
||||
app->setApplicationName(QStringLiteral("server"));
|
||||
app->setApplicationVersion(QStringLiteral("0.2.0"));
|
||||
app->setApplicationVersion(QStringLiteral("0.3.0"));
|
||||
|
||||
qDebug() << "harbour-server v0.2.0 build" << __DATE__ << __TIME__;
|
||||
qDebug() << "harbour-server v0.3.0 build" << __DATE__ << __TIME__;
|
||||
|
||||
Settings settings;
|
||||
StatusClient status(&settings);
|
||||
|
||||
Reference in new issue
Block a user