collector: conteggio aggiornamenti indipendente dalla lingua (LC_ALL=C)
apt risponde in italiano ("[aggiornabile da: ...]"): il filtro sulla parola
inglese 'upgradable' contava sempre zero. Ora legge per posizione con locale C,
con fallback su 'apt-get -s upgrade'. Corretto anche il parsing dei timestamp
systemd per lo stesso motivo (giorno della settimana tradotto).
This commit is contained in:
1 parent
548ec7eaac
commit
d14c59166b
1 file changed
+74
-12
+74
-12
@@ -40,11 +40,16 @@ CPU_STATE = Path.home() / ".cache" / "statusd" / "cpu-usage.json"
|
||||
|
||||
|
||||
# ── helper ────────────────────────────────────────────────────────────────
|
||||
def run(cmd: list[str], timeout: float = 4.0) -> str:
|
||||
def run(cmd: list[str], timeout: float = 4.0, env: dict | None = None) -> str:
|
||||
"""Esegue un comando read-only e torna stdout (stringa vuota se fallisce)."""
|
||||
try:
|
||||
p = subprocess.run(
|
||||
cmd, capture_output=True, text=True, timeout=timeout, check=False
|
||||
cmd,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=timeout,
|
||||
check=False,
|
||||
env={**os.environ, **(env or {})},
|
||||
)
|
||||
return p.stdout if p.returncode == 0 else ""
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
@@ -361,6 +366,29 @@ def _docker_present() -> bool:
|
||||
return shutil.which("docker") is not None
|
||||
|
||||
|
||||
def _parse_systemd_stamp(stamp: str) -> datetime | None:
|
||||
"""Data da `systemctl show` senza dipendere dalla lingua.
|
||||
|
||||
Il formato è "Mon 2026-10-26 02:38:11 CET", ma il giorno è tradotto
|
||||
("lun ...") quando LC_TIME non è C: elimino il primo token e leggo il resto,
|
||||
che è numerico e quindi neutro.
|
||||
"""
|
||||
text = stamp.strip()
|
||||
if not text:
|
||||
return None
|
||||
if not text[0].isdigit():
|
||||
parts = text.split(None, 1)
|
||||
if len(parts) < 2:
|
||||
return None
|
||||
text = parts[1]
|
||||
for fmt in ("%Y-%m-%d %H:%M:%S %Z", "%Y-%m-%d %H:%M:%S"):
|
||||
try:
|
||||
return datetime.strptime(text, fmt)
|
||||
except ValueError:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def backups_info() -> dict:
|
||||
"""Età dell'ultimo giro di backup, da fonti leggibili senza privilegi.
|
||||
|
||||
@@ -410,13 +438,11 @@ def backups_info() -> dict:
|
||||
# l'ultimo giro si legge da InactiveEnterTimestamp (fine esecuzione).
|
||||
stamp = info.get("ActiveEnterTimestamp") or info.get("InactiveEnterTimestamp", "")
|
||||
if stamp:
|
||||
try:
|
||||
dt = datetime.strptime(stamp, "%a %Y-%m-%d %H:%M:%S %Z")
|
||||
dt = _parse_systemd_stamp(stamp)
|
||||
if dt is not None:
|
||||
age_h = round((datetime.now() - dt).total_seconds() / 3600.0, 1)
|
||||
last_run = stamp
|
||||
source = "systemd"
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
return {
|
||||
"name": "borg",
|
||||
@@ -474,10 +500,46 @@ def access_info() -> dict:
|
||||
|
||||
|
||||
def updates_info() -> dict:
|
||||
raw = run(["apt", "list", "--upgradable"], timeout=20)
|
||||
lines = [l for l in raw.splitlines() if "upgradable" in l and "/" in l]
|
||||
security = sum(1 for l in lines if "-security" in l or "Security" in l)
|
||||
packages = [l.split("/")[0].strip() for l in lines][:20]
|
||||
# `apt` parla la lingua del sistema: qui risponde "[aggiornabile da: ...]",
|
||||
# quindi il vecchio filtro sulla parola inglese "upgradable" contava sempre
|
||||
# zero. Forzo il locale C e leggo per POSIZIONE, non per parola chiave.
|
||||
c_locale = {"LC_ALL": "C", "LANG": "C"}
|
||||
raw = run(["apt", "list", "--upgradable"], timeout=25, env=c_locale)
|
||||
|
||||
packages: list[str] = []
|
||||
security = 0
|
||||
seen = set()
|
||||
|
||||
for line in raw.splitlines():
|
||||
line = line.strip()
|
||||
if not line or "/" not in line or line.startswith("Listing"):
|
||||
continue
|
||||
parts = line.split()
|
||||
if len(parts) < 2:
|
||||
continue
|
||||
name, _, pocket = parts[0].partition("/")
|
||||
if not name or name in seen:
|
||||
continue
|
||||
seen.add(name)
|
||||
packages.append(name)
|
||||
if pocket.endswith("-security") or "security" in pocket:
|
||||
security += 1
|
||||
|
||||
# Rete di sicurezza: se la lista esce vuota o non interpretabile, chiedo ad
|
||||
# apt cosa installerebbe. Meglio un conteggio da un'altra fonte che uno zero
|
||||
# che sembra "tutto aggiornato".
|
||||
if not packages:
|
||||
sim = run(["apt-get", "-s", "upgrade"], timeout=30, env=c_locale)
|
||||
for line in sim.splitlines():
|
||||
if not line.startswith("Inst "):
|
||||
continue
|
||||
parts = line.split()
|
||||
if len(parts) < 2 or parts[1] in seen:
|
||||
continue
|
||||
seen.add(parts[1])
|
||||
packages.append(parts[1])
|
||||
if "security" in line.lower():
|
||||
security += 1
|
||||
|
||||
# Quando sono state aggiornate le liste apt. Senza questo dato un "0" non e'
|
||||
# verificabile: un dist-upgrade automatico puo' aver appena svuotato la
|
||||
@@ -492,9 +554,9 @@ def updates_info() -> dict:
|
||||
pass
|
||||
|
||||
return {
|
||||
"total": len(lines),
|
||||
"total": len(packages),
|
||||
"security": security,
|
||||
"packages": packages,
|
||||
"packages": packages[:20],
|
||||
"lists_updated_at": lists_at,
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user