0.1.5: card UPS; backup con marcatore robusto ai riavvii

This commit is contained in:
Carlo Baratto committed 2026-10-31 13:38:40 +01:00
1 parent 29a63a74d4
commit 8ed183c1fc
6 files changed
+178 -10

No files matched your search

+1 -1
View File
@@ -34,7 +34,7 @@ Requisiti: SDK Sailfish in `~/SailfishOS`, build engine Docker.
## Installazione sul telefono ## Installazione sul telefono
```sh ```sh
devel-su rpm -Uvh harbour-server-0.1.4-1.aarch64.rpm devel-su rpm -Uvh harbour-server-0.1.5-1.aarch64.rpm
``` ```
Poi, all'apertura: indicare indirizzo (es. `http://192.168.3.21:8792`) e token. Poi, all'apertura: indicare indirizzo (es. `http://192.168.3.21:8792`) e token.
+61 -1
View File
@@ -77,6 +77,56 @@ Page {
parts.push(qsTr("liste apt: ") + statusClient.fmtStamp(d.updates.lists_updated_at)) parts.push(qsTr("liste apt: ") + statusClient.fmtStamp(d.updates.lists_updated_at))
return parts.join(" · ") return parts.join(" · ")
} }
function backupEnough() { return backupAge() >= 0 }
function backupDetail() {
var d = statusClient.data
if (!d || !d.backups) return ""
var r = backupResult()
var base = r === "" ? qsTr("nessun dato") : "borg · " + r
// Senza marcatore né timestamp dell'unit non si conosce l'ora del giro
// (dopo un riavvio systemd azzera i suoi timestamp): dirlo, invece di
// far sembrare che il backup non sia mai stato fatto.
if (!backupEnough()) base += " · " + qsTr("ora del giro non registrata")
return base
}
function ups() {
var d = statusClient.data
return (d && d.ups && d.ups.available) ? d.ups : null
}
function upsStatus() {
var u = ups()
return (u && u.status) ? u.status.toUpperCase() : ""
}
function upsLabel() {
var s = upsStatus()
if (s === "") return "—"
if (s.indexOf("OB") >= 0) return qsTr("a batteria")
if (s.indexOf("OL") >= 0) return qsTr("rete")
return s
}
function upsLevel() {
var u = ups()
if (!u) return 1
var s = upsStatus()
if (s.indexOf("ALARM") >= 0 || s.indexOf("FSD") >= 0 || s.indexOf("LB") >= 0) return 2
if (u.charge_pct !== null && u.charge_pct !== undefined && u.charge_pct < 50) return 2
if (u.load_pct !== null && u.load_pct !== undefined && u.load_pct > 85) return 1
return 0
}
function upsDetail() {
var u = ups()
if (!u) return qsTr("nessun UPS rilevato")
var parts = []
if (u.charge_pct !== null && u.charge_pct !== undefined)
parts.push(qsTr("carica ") + statusClient.fmtNum(u.charge_pct, 0) + "%")
if (u.runtime_s)
parts.push(qsTr("autonomia ") + Math.round(u.runtime_s / 60) + " min")
if (u.load_pct !== null && u.load_pct !== undefined)
parts.push(qsTr("carico ") + statusClient.fmtNum(u.load_pct, 0) + "%")
if (u.input_voltage)
parts.push(statusClient.fmtNum(u.input_voltage, 0) + " V")
return parts.join(" · ")
}
function vpnText() { function vpnText() {
var d = statusClient.data var d = statusClient.data
if (!d || !d.net || !d.net.interfaces || d.net.interfaces.length === 0) return "nessuna" if (!d || !d.net || !d.net.interfaces || d.net.interfaces.length === 0) return "nessuna"
@@ -198,11 +248,21 @@ Page {
: (backupDays() === 0 ? qsTr("meno di 1 giorno") : (backupDays() === 0 ? qsTr("meno di 1 giorno")
: (backupDays() === 1 ? qsTr("1 giorno") : (backupDays() === 1 ? qsTr("1 giorno")
: backupDays() + " " + qsTr("giorni"))) : backupDays() + " " + qsTr("giorni")))
detail: backupResult() === "" ? qsTr("nessun dato") : "borg · " + backupResult() detail: backupDetail()
progress: -1 progress: -1
level: backupLevel() level: backupLevel()
} }
MetricCard {
x: Theme.paddingLarge
width: parent.width - 2 * Theme.paddingLarge
title: qsTr("UPS")
value: upsLabel()
detail: upsDetail()
progress: -1
level: upsLevel()
}
MetricCard { MetricCard {
x: Theme.paddingLarge x: Theme.paddingLarge
width: parent.width - 2 * Theme.paddingLarge width: parent.width - 2 * Theme.paddingLarge
+8 -1
View File
@@ -1,6 +1,6 @@
Name: harbour-server Name: harbour-server
Summary: Parametri del server in una schermata Summary: Parametri del server in una schermata
Version: 0.1.4 Version: 0.1.5
Release: 1 Release: 1
Group: Qt/Qt Group: Qt/Qt
License: MIT License: MIT
@@ -23,6 +23,13 @@ schermata sola. Il formato consumato (schema status/1) non dipende dalla
macchina: qualunque host che serva lo stesso JSON funziona senza modifiche. macchina: qualunque host che serva lo stesso JSON funziona senza modifiche.
%changelog %changelog
* Sat Oct 31 2026 Carlo Baratto <carlo@carlobaratto.it> - 0.1.5-1
- Card UPS: stato (rete / a batteria), carica, autonomia, carico e tensione
d'ingresso da NUT; rosso con batteria scarica o allarme, giallo se la
carica scende sotto il 50%
- Card Backup: quando l'ora dell'ultimo giro non è registrabile (dopo un
riavvio systemd azzera i timestamp) lo dice, invece di mostrare un trattino
senza spiegazione
* Wed Oct 28 2026 Carlo Baratto <carlo@carlobaratto.it> - 0.1.4-1 * Wed Oct 28 2026 Carlo Baratto <carlo@carlobaratto.it> - 0.1.4-1
- Card Backup: soglia rossa spostata da 7 a 8 giorni (verde 1-3, giallo 4-7, - Card Backup: soglia rossa spostata da 7 a 8 giorni (verde 1-3, giallo 4-7,
rosso da 8 in su), così la domenica sera — con Borg settimanale — la card rosso da 8 in su), così la domenica sera — con Borg settimanale — la card
+35 -1
View File
@@ -18,6 +18,34 @@ Copia il collector in `~/.local/share/statod/`, genera il token in
`~/.config/statusd/token` (0600) e attiva le due unit utente. La sopravvivenza `~/.config/statusd/token` (0600) e attiva le due unit utente. La sopravvivenza
al logout richiede `loginctl enable-linger <utente>`. al logout richiede `loginctl enable-linger <utente>`.
## Marcatore dell'ultimo backup (una volta, richiede root)
I timestamp delle unit systemd si **azzerano a ogni riavvio**, `/var/log/borg`
è `borg:borg 750` e il journal non è leggibile senza i gruppi `adm` o
`systemd-journal`: senza un marcatore, dopo un reboot l'età del backup è
semplicemente ignota. Il drop-in crea `/var/lib/borg-last-run` (leggibile da
tutti) al termine di ogni giro:
```sh
sudo mkdir -p /etc/systemd/system/borg.service.d
sudo tee /etc/systemd/system/borg.service.d/10-lastrun.conf >/dev/null <<'EOF'
[Service]
ExecStartPost=/bin/sh -c 'date -Is > /var/lib/borg-last-run'
EOF
sudo systemctl daemon-reload
```
Finché il marcatore non esiste, `backups.age_hours` resta `null` e l'app mostra
"—" con la nota "ora del giro non registrata": è voluto, meglio di un numero
inventato.
## UPS (NUT)
Lo stato arriva da `upsc -l` + `upsc <nome>`: nessuna configurazione da fare
nell'app finché NUT è attivo (`nut-server`, `nut-monitor`). Se `upsc -l` non
elenca dispositivi, la sezione `ups` è `null` e la card mostra "nessun UPS
rilevato".
## Esposizione ## Esposizione
`statusd-http.service` ascolta su `0.0.0.0:8792`. Il firewall YunoHost ha `statusd-http.service` ascolta su `0.0.0.0:8792`. Il firewall YunoHost ha
@@ -57,7 +85,13 @@ Nessun log HTTP: il token non finisce su disco. Il server non ha altre rotte.
"containers": { "running": [ { "name": "…", "status": "Up 2 days", "ok": true } ], "containers": { "running": [ { "name": "…", "status": "Up 2 days", "ok": true } ],
"available": true }, "available": true },
"backups": { "name": "borg", "last_run": "…", "result": "success", "backups": { "name": "borg", "last_run": "…", "result": "success",
"exit_code": 0, "age_hours": 41.5 }, "exit_code": 0, "age_hours": 41.5,
"source": "marker" },
"ups": { "name": "ups", "available": true, "status": "OL",
"charge_pct": 100.0, "runtime_s": 3000.0, "load_pct": 2.0,
"input_voltage": 246.5, "battery_voltage": 13.4,
"input_frequency": 50.1, "beeper": "enabled",
"driver": "nutdrv_qx" },
"services": { "failed": [ { "unit": "…", "description": "…" } ] }, "services": { "failed": [ { "unit": "…", "description": "…" } ] },
"access": { "ssh_failed_24h": 0 }, "access": { "ssh_failed_24h": 0 },
"updates": { "total": 0, "security": 0, "packages": [], "updates": { "total": 0, "security": 0, "packages": [],
+71 -4
View File
@@ -28,6 +28,10 @@ SCHEMA = "status/1"
DEFAULT_OUT = "/run/statusd/status.json" DEFAULT_OUT = "/run/statusd/status.json"
DEFAULT_PORT = 8792 DEFAULT_PORT = 8792
# Marcatore scritto dal backup (world-readable): unica fonte che sopravvive ai
# riavvii. Creato con una riga di root, vedi README.
BORG_MARKER = "/var/lib/borg-last-run"
# ── helper ──────────────────────────────────────────────────────────────── # ── helper ────────────────────────────────────────────────────────────────
def run(cmd: list[str], timeout: float = 4.0) -> str: def run(cmd: list[str], timeout: float = 4.0) -> str:
@@ -161,7 +165,28 @@ def _docker_present() -> bool:
def backups_info() -> dict: def backups_info() -> dict:
"""Stato dell'ultimo giro borg.timer (system unit), senza privilegi.""" """Età dell'ultimo giro di backup, da fonti leggibili senza privilegi.
Ordine delle fonti, dalla più affidabile:
1. /var/lib/borg-last-run — marcatore scritto dal backup stesso;
sopravvive ai riavvii (i timestamp delle unit systemd NO: al boot
tornano vuoti, ed è il motivo per cui la card mostrava "—").
2. timestamp dell'unit borg.service — valido solo nello stesso avvio.
3. niente: age_hours null. Meglio un "—" onesto di un numero inventato.
"""
path = Path(BORG_MARKER)
last_run = None
age_h = None
source = None
try:
st = path.stat()
last_run = iso(st.st_mtime)
age_h = round((time.time() - st.st_mtime) / 3600.0, 1)
source = "marker"
except OSError:
pass
out = run( out = run(
[ [
"systemctl", "systemctl",
@@ -182,22 +207,63 @@ def backups_info() -> dict:
info = dict( info = dict(
line.split("=", 1) for line in out.splitlines() if "=" in line line.split("=", 1) for line in out.splitlines() if "=" in line
) )
# borg.service è oneshot: quando è "dead" ActiveEnterTimestamp è vuoto e
if age_h is None:
# borg.service è oneshot: da spento ActiveEnterTimestamp è vuoto e
# l'ultimo giro si legge da InactiveEnterTimestamp (fine esecuzione). # l'ultimo giro si legge da InactiveEnterTimestamp (fine esecuzione).
age_h = None
stamp = info.get("ActiveEnterTimestamp") or info.get("InactiveEnterTimestamp", "") stamp = info.get("ActiveEnterTimestamp") or info.get("InactiveEnterTimestamp", "")
if stamp: if stamp:
try: try:
dt = datetime.strptime(stamp, "%a %Y-%m-%d %H:%M:%S %Z") dt = datetime.strptime(stamp, "%a %Y-%m-%d %H:%M:%S %Z")
age_h = round((datetime.now() - dt).total_seconds() / 3600.0, 1) age_h = round((datetime.now() - dt).total_seconds() / 3600.0, 1)
last_run = stamp
source = "systemd"
except ValueError: except ValueError:
pass pass
return { return {
"name": "borg", "name": "borg",
"last_run": stamp or None, "last_run": last_run,
"result": info.get("Result") or None, "result": info.get("Result") or None,
"exit_code": int(info["ExecMainStatus"]) if info.get("ExecMainStatus") else None, "exit_code": int(info["ExecMainStatus"]) if info.get("ExecMainStatus") else None,
"age_hours": age_h, "age_hours": age_h,
"source": source,
}
def ups_info() -> dict | None:
"""Stato dell'UPS da NUT (upsc). Nessuna scrittura, nessun privilegio."""
names = run(["upsc", "-l"], timeout=5).split()
if not names:
return None
name = names[0]
raw = run(["upsc", name], timeout=8)
if not raw:
return {"name": name, "available": False}
vals = {}
for line in raw.splitlines():
key, _, value = line.partition(":")
if key and value.strip():
vals[key.strip()] = value.strip()
def num(key, cast=float):
try:
return cast(vals[key])
except (KeyError, ValueError):
return None
return {
"name": name,
"available": True,
"status": vals.get("ups.status"),
"charge_pct": num("battery.charge"),
"runtime_s": num("battery.runtime"),
"load_pct": num("ups.load"),
"input_voltage": num("input.voltage"),
"battery_voltage": num("battery.voltage"),
"input_frequency": num("input.frequency"),
"beeper": vals.get("ups.beeper.status"),
"driver": vals.get("driver.name"),
} }
@@ -253,6 +319,7 @@ def collect() -> dict:
("services", services_info), ("services", services_info),
("containers", containers_info), ("containers", containers_info),
("backups", backups_info), ("backups", backups_info),
("ups", ups_info),
("access", access_info), ("access", access_info),
("updates", updates_info), ("updates", updates_info),
("net", vpn_info), ("net", vpn_info),
+2 -2
View File
@@ -15,9 +15,9 @@ Q_DECL_EXPORT int main(int argc, char *argv[])
// AppConfigLocation = ~/.config/harbour/server (zona persistente). // AppConfigLocation = ~/.config/harbour/server (zona persistente).
app->setOrganizationName(QStringLiteral("harbour")); app->setOrganizationName(QStringLiteral("harbour"));
app->setApplicationName(QStringLiteral("server")); app->setApplicationName(QStringLiteral("server"));
app->setApplicationVersion(QStringLiteral("0.1.4")); app->setApplicationVersion(QStringLiteral("0.1.5"));
qDebug() << "harbour-server v0.1.4 build" << __DATE__ << __TIME__; qDebug() << "harbour-server v0.1.5 build" << __DATE__ << __TIME__;
Settings settings; Settings settings;
StatusClient status(&settings); StatusClient status(&settings);