9 Commits
Author SHA1 Message Date
iv3jdv 8220039bf6 fix(psutil): sostituito p.connections() con p.net_connections() per compatibilità con versioni future
- Aggiornato system_monitor.py alla riga 587.
- Implementata la logica di fallback per mantenere la retrocompatibilità (tenta prima net_connections, poi connections).
- Risolto il DeprecationWarning relativo a psutil.
2026-11-01 12:24:20 +01:00
iv3jdv 4e2eb29b26 fix standby process 2026-10-31 19:34:27 +01:00
iv3jdv 26789736b1 fix(agent): ripristinato riconoscimento processi con trattino (MMDVM-Host)
Corretto il matching del nome dei processi in psutil. La rimozione dei trattini ora avviene su entrambe le stringhe prima del confronto, risolvendo il falso positivo di stato 'KO' per MMDVMHost introdotto con il recente aggiornamento dei socket MQTT.
2026-10-29 09:08:28 +01:00
iv3jdv de705c908e feat(agent): monitoraggio socket MQTT e tolleranza disconnessione
Implementato il controllo dei socket TCP tramite psutil per verificare la reale connessione dei processi al broker. I demoni attivi ma scollegati segnalano ora lo stato 'disconnected'. Aggiornato l'auto-healing per tollerare questo stato, evitando riavvii forzati e permettendo alla libreria mosquitto (tramite mosquitto_connect_async) di gestire autonomamente le riconnessioni in background.
2026-10-28 22:41:56 +01:00
iv3jdv c6e8da311f fix 2026-10-22 23:42:29 +02:00
iv3jdv 1e98cb2477 update 2026-10-22 23:19:11 +02:00
iv3jdv 7d5e3b9ca2 add hash version 2026-10-22 21:50:27 +02:00
iv3jdv d1b39f7c69 add OTA signal 2026-10-22 19:00:49 +02:00
iv3jdv e3f760ebf1 add uptime 2026-10-22 12:37:38 +02:00
2 changed files with 94 additions and 89 deletions
Binary file not shown.
+93 -88
View File
@@ -22,16 +22,29 @@ import signal
import requests import requests
from pathlib import Path from pathlib import Path
import logging import logging
import shutil
from logging.handlers import RotatingFileHandler from logging.handlers import RotatingFileHandler
AGENT_VERSION = "2.0" AGENT_VERSION = "2.2"
# --- CALCOLO PERCORSI DINAMICI --- # --- CALCOLO PERCORSI DINAMICI ---
AGENT_DIR = os.path.dirname(os.path.abspath(__file__)) AGENT_DIR = os.path.dirname(os.path.abspath(__file__))
LOG_FILE = os.path.join(AGENT_DIR, 'node_agent.log') LOG_FILE = os.path.join(AGENT_DIR, 'node_agent.log')
CONFIG_FILE = os.environ.get('FLEET_AGENT_CONFIG', os.path.join(AGENT_DIR, 'node_config.json')) CONFIG_FILE = os.environ.get('FLEET_AGENT_CONFIG', os.path.join(AGENT_DIR, 'node_config.json'))
# --- CALCOLO HASH GIT ---
def get_agent_commit():
try:
r = subprocess.run(["git", "-c", "safe.directory=*", "rev-parse", "--short", "HEAD"],
cwd=AGENT_DIR, capture_output=True, text=True, timeout=5)
if r.returncode == 0 and r.stdout.strip():
return r.stdout.strip()
except Exception:
pass
return "unknown"
AGENT_GIT_HASH = get_agent_commit()
agent_update_available = False
# ========================================== # ==========================================
# 0. LOGGING & HARDWARE CONFIGURATION # 0. LOGGING & HARDWARE CONFIGURATION
# ========================================== # ==========================================
@@ -62,7 +75,6 @@ except RuntimeError as e:
# ========================================== # ==========================================
CONFIG_PATH = Path(CONFIG_FILE) CONFIG_PATH = Path(CONFIG_FILE)
def load_config(): def load_config():
try: try:
if not CONFIG_PATH.exists(): if not CONFIG_PATH.exists():
@@ -128,6 +140,20 @@ stopped_by_admin = set() # servizi fermati volontariamente dalla dashbo
ops_lock = threading.RLock() # una sola operazione "pesante" alla volta (profilo, config, reset, update...) ops_lock = threading.RLock() # una sola operazione "pesante" alla volta (profilo, config, reset, update...)
heal_pause_until = 0.0 heal_pause_until = 0.0
disconnected_since = None disconnected_since = None
def update_checker_loop():
"""Controlla ogni ora se ci sono aggiornamenti sul branch remoto."""
global agent_update_available
while True:
try:
subprocess.run(["git", "-c", "safe.directory=*", "fetch"], timeout=20, cwd=AGENT_DIR)
local = subprocess.check_output(["git", "-c", "safe.directory=*", "rev-parse", "HEAD"], cwd=AGENT_DIR).decode('utf-8').strip()
remote = subprocess.check_output(["git", "-c", "safe.directory=*", "rev-parse", "@{u}"], cwd=AGENT_DIR).decode('utf-8').strip()
agent_update_available = (local != remote)
except Exception as e:
logger.debug(f"Errore check update agent: {e}")
time.sleep(3600)
published_sig = {} # percorso file -> (mtime_ns, size) dell'ultima versione pubblicata published_sig = {} # percorso file -> (mtime_ns, size) dell'ultima versione pubblicata
_warned_units = set() _warned_units = set()
@@ -168,8 +194,7 @@ def redact(text):
def safe_write_bytes(path, data): def safe_write_bytes(path, data):
"""Scrittura atomica (file temporaneo + fsync + replace) mantenendo permessi e proprietario. """Scrittura atomica (file temporaneo + fsync + replace) mantenendo permessi e proprietario."""
Se la directory non è scrivibile (es. /etc con file concesso all'utente) ripiega sulla scrittura in-place."""
path = str(path) path = str(path)
tmp = f"{path}.tmp.{os.getpid()}" tmp = f"{path}.tmp.{os.getpid()}"
try: try:
@@ -207,7 +232,7 @@ def safe_write_text(path, text):
def run_cmd(args, timeout=30, cwd=None): def run_cmd(args, timeout=30, cwd=None):
"""Esegue un comando SENZA shell e con timeout. rc=124 timeout, rc=127 comando mancante.""" """Esegue un comando SENZA shell e con timeout."""
try: try:
return subprocess.run(args, capture_output=True, text=True, timeout=timeout, cwd=cwd) return subprocess.run(args, capture_output=True, text=True, timeout=timeout, cwd=cwd)
except subprocess.TimeoutExpired: except subprocess.TimeoutExpired:
@@ -220,7 +245,7 @@ def run_cmd(args, timeout=30, cwd=None):
def read_lines(path): def read_lines(path):
"""Righe non vuote e non commentate di un file di testo ([] se manca).""" """Righe non vuote e non commentate di un file di testo."""
try: try:
p = Path(str(path)) p = Path(str(path))
if not str(path) or not p.is_file(): if not str(path) or not p.is_file():
@@ -245,7 +270,7 @@ def log_to_broker(msg):
def publish_status(): def publish_status():
"""Stato del nodo (retained). Va ripubblicato a ogni connessione: dopo un blip il LWT l'ha messo OFFLINE.""" """Stato del nodo (retained). Va ripubblicato a ogni connessione."""
try: try:
if mqtt_client is not None: if mqtt_client is not None:
mqtt_client.publish(TOPIC_STAT, current_status, qos=1, retain=True) mqtt_client.publish(TOPIC_STAT, current_status, qos=1, retain=True)
@@ -254,7 +279,7 @@ def publish_status():
def note_ops_done(): def note_ops_done():
"""Dopo un'operazione l'auto-healing resta in pausa qualche secondo (i servizi stanno ripartendo).""" """Dopo un'operazione l'auto-healing resta in pausa qualche secondo."""
global heal_pause_until global heal_pause_until
heal_pause_until = time.time() + int_setting('heal_grace_seconds', 20, 0) heal_pause_until = time.time() + int_setting('heal_grace_seconds', 20, 0)
@@ -308,7 +333,6 @@ def telegram_worker():
if not r.ok: if not r.ok:
logger.error(f"Telegram HTTP {r.status_code}") logger.error(f"Telegram HTTP {r.status_code}")
except Exception as e: except Exception as e:
# l'eccezione di requests contiene l'URL con il token: va ripulita
logger.error(f"Telegram sending error: {type(e).__name__}: {redact(e)}") logger.error(f"Telegram sending error: {type(e).__name__}: {redact(e)}")
@@ -348,7 +372,7 @@ def get_actual_config_from_disk():
return f"ONLINE - {label}" return f"ONLINE - {label}"
except Exception as e: except Exception as e:
logger.error(f"Errore lettura memoria profilo: {e}") logger.error(f"Errore lettura memoria profilo: {e}")
return "ONLINE" # Default se il file non esiste o è vuoto return "ONLINE"
def save_last_profile(label): def save_last_profile(label):
@@ -362,7 +386,6 @@ def save_last_profile(label):
# 5. SYSTEMD: NOMI UNITÀ (whitelist) E CONTROLLI # 5. SYSTEMD: NOMI UNITÀ (whitelist) E CONTROLLI
# ========================================== # ==========================================
def build_unit_map(): def build_unit_map():
"""nome normalizzato -> nome unità. Solo ciò che il nodo conosce: process_list, profili, settings.service_map."""
m = {} m = {}
for name in read_lines(PROCESS_LIST_PATH): for name in read_lines(PROCESS_LIST_PATH):
n = norm_name(name) n = norm_name(name)
@@ -402,7 +425,6 @@ def unit_is_disabled(unit):
def wait_units_active(units, seconds): def wait_units_active(units, seconds):
"""Attende fino a `seconds` che tutte le unità siano attive. Ritorna la lista di quelle NON attive."""
deadline = time.monotonic() + seconds deadline = time.monotonic() + seconds
pending = list(units) pending = list(units)
while True: while True:
@@ -418,7 +440,7 @@ def wait_units_active(units, seconds):
def gpio_pin_config(): def gpio_pin_config():
pin = cfg['settings'].get('gpio_reset_pin') pin = cfg['settings'].get('gpio_reset_pin')
if pin in (None, '', 0, False): if pin in (None, '', 0, False):
return None # nessun default implicito: il GPIO si usa solo se configurato return None
try: try:
return int(pin) return int(pin)
except (TypeError, ValueError): except (TypeError, ValueError):
@@ -426,7 +448,6 @@ def gpio_pin_config():
def hardware_reset(auto=False): def hardware_reset(auto=False):
"""Reset del modem. Ritorna {"attempted", "ok", "method", "msg"}."""
usb_id = str(cfg['settings'].get('usb_reset_id') or '').strip() usb_id = str(cfg['settings'].get('usb_reset_id') or '').strip()
if usb_id: if usb_id:
if not USB_ID_RE.match(usb_id): if not USB_ID_RE.match(usb_id):
@@ -485,7 +506,6 @@ def get_binary_versions():
versions = {} versions = {}
def find_cmd(names): def find_cmd(names):
# Accetta una lista di nomi e li prova in ordine
for name in names: for name in names:
cmd_path = shutil.which(name) cmd_path = shutil.which(name)
if cmd_path: if cmd_path:
@@ -494,9 +514,8 @@ def get_binary_versions():
full = os.path.join(base, name) full = os.path.join(base, name)
if os.path.isfile(full): if os.path.isfile(full):
return full return full
return names[0] # Se fallisce, tenta col primo nome di default return names[0]
# Mappa: "Nome Bello da mostrare" -> ["Lista", "di", "eseguibili", "da", "cercare"]
binaries = { binaries = {
"MMDVMHost": ["MMDVMHost", "MMDVM-Host"], "MMDVMHost": ["MMDVMHost", "MMDVM-Host"],
"DMRGateway": ["DMRGateway"], "DMRGateway": ["DMRGateway"],
@@ -516,49 +535,10 @@ def get_binary_versions():
import re import re
testo_pulito = re.sub(r'^[A-Za-z0-9_\-]+\s+version\s+', '', testo, flags=re.IGNORECASE) testo_pulito = re.sub(r'^[A-Za-z0-9_\-]+\s+version\s+', '', testo, flags=re.IGNORECASE)
# Pulizia extra per DStarGateway (rimuove il blocco Copyright lunghissimo)
if "Copyright" in testo_pulito: if "Copyright" in testo_pulito:
testo_pulito = testo_pulito.split("Copyright")[0].replace("DStarGateway", "").strip() testo_pulito = testo_pulito.split("Copyright")[0].replace("DStarGateway", "").strip()
if testo_pulito.startswith("v"): if testo_pulito.startswith("v"):
testo_pulito = testo_pulito[1:] # Toglie la 'v' iniziale testo_pulito = testo_pulito[1:]
if chiave not in versions or versions[chiave] == "":
versions[chiave] = testo_pulito.strip()
return versions
binaries = {
"MMDVMHost": ["MMDVMHost", "-v"],
"MMDVMHost (alt)": ["MMDVM-Host", "-v"],
"DMRGateway": ["DMRGateway", "-v"],
"YSFGateway": ["YSFGateway", "-v"],
"NXDNGateway": ["NXDNGateway", "-v"],
"P25Gateway": ["P25Gateway", "-v"],
"DStarGateway": ["dstargateway", "-v"],
"DStarGateway (alt)": ["dstar-gateway", "-v"]
}
for nome, comando in binaries.items():
cmd_reale = [find_cmd(comando[0]), comando[1]]
r = run_cmd(cmd_reale, timeout=3)
if r.returncode == 0 and r.stdout:
# Prende solo la prima riga dell'output
testo = r.stdout.strip().split('\n')[0]
# Pulisce la stringa
import re
testo_pulito = re.sub(r'^[A-Za-z0-9_\-]+\s+version\s+', '', testo, flags=re.IGNORECASE)
# --- PULIZIA EXTRA PER DSTARGATEWAY ---
if "Copyright" in testo_pulito:
testo_pulito = testo_pulito.split("Copyright")[0].replace("DStarGateway", "").strip()
if testo_pulito.startswith("v"):
testo_pulito = testo_pulito[1:] # Toglie la 'v' iniziale per uniformità
# --------------------------------------
# Normalizza il nome
chiave = "DStarGateway" if "DStar" in nome else nome
if chiave not in versions or versions[chiave] == "": if chiave not in versions or versions[chiave] == "":
versions[chiave] = testo_pulito.strip() versions[chiave] = testo_pulito.strip()
@@ -575,22 +555,55 @@ def get_system_status():
"timestamp": time.strftime("%H:%M:%S"), "timestamp": time.strftime("%H:%M:%S"),
"profiles": {k: (v.get('label', f'PROFILE {k}') if isinstance(v, dict) else f'PROFILE {k}') "profiles": {k: (v.get('label', f'PROFILE {k}') if isinstance(v, dict) else f'PROFILE {k}')
for k, v in cfg['profiles'].items()}, for k, v in cfg['profiles'].items()},
"update_interval": get_update_interval(), # il server ne ricava le soglie "agent muto" "update_interval": get_update_interval(),
"agent_version": AGENT_VERSION, "agent_version": f"{AGENT_VERSION} ({AGENT_GIT_HASH})",
"versions": get_binary_versions() # Estrazione versioni dai file binari "agent_update_available": agent_update_available,
"versions": get_binary_versions(),
"uptime_seconds": int(time.time() - psutil.boot_time())
} }
names = read_lines(PROCESS_LIST_PATH) names = read_lines(PROCESS_LIST_PATH)
if names: if names:
try: try:
running = {(p.info.get('name') or '').lower() for p in psutil.process_iter(['name'])} # Recupera la porta MQTT usata dal nodo (es. 1883)
broker_port = int(MQTT_CFG.get('port', 1883))
# Prende tutti i processi in esecuzione
running_procs = list(psutil.process_iter(['name']))
for name in names: for name in names:
n = name.strip().lower() n = name.strip().lower()
if n: if n:
# MAGIA QUI: Controlla se il nome corrisponde, ignorando i trattini (mmdvmhost == mmdvm-host) # Trova i processi che matchano il nome (ignorando i trattini)
is_online = any(r == n or r.replace('-', '') == n.replace('-', '') for r in running) matching_procs = [p for p in running_procs if (p.info.get('name') or '').lower().replace('-', '') == n.replace('-', '')]
status["processes"][n] = "online" if is_online else "offline"
if not matching_procs:
status["processes"][n] = "standby" if norm_name(n) in stopped_by_admin else "offline"
else:
is_mqtt_connected = False
for p in matching_procs:
try:
# Controlla i socket di rete del processo in modo retrocompatibile
conn_func = getattr(p, "net_connections", p.connections)
for conn in conn_func(kind='inet'):
# Se c'è una connessione stabilita verso la porta del broker, è ok
if conn.status == 'ESTABLISHED' and conn.raddr and conn.raddr.port == broker_port:
is_mqtt_connected = True
break
except (psutil.AccessDenied, psutil.NoSuchProcess):
# Se l'agent non ha i permessi per leggere i socket,
# diamo il beneficio del dubbio per evitare falsi positivi
is_mqtt_connected = True
if is_mqtt_connected:
break
# Se è in esecuzione ma senza connessione MQTT, lo dichiariamo 'disconnected'
status["processes"][n] = "online" if is_mqtt_connected else "disconnected"
except Exception as e: except Exception as e:
logger.error(f"Process check error: {e}") logger.error(f"Process check error: {e}")
return status return status
def publish_telemetry(): def publish_telemetry():
@@ -599,7 +612,6 @@ def publish_telemetry():
status["config_files"] = stems status["config_files"] = stems
status["files"] = stems status["files"] = stems
# nomi completi con estensione (es. dstargateway.cfg): la dashboard li usa solo per l'etichetta
status["file_names"] = [Path(f).name for f in read_lines(FILE_LIST_PATH)] status["file_names"] = [Path(f).name for f in read_lines(FILE_LIST_PATH)]
if connected(): if connected():
mqtt_client.publish(TOPIC_SERVICES, json.dumps(status), qos=1) mqtt_client.publish(TOPIC_SERVICES, json.dumps(status), qos=1)
@@ -607,7 +619,7 @@ def publish_telemetry():
# ========================================== # ==========================================
# 8. PUBBLICAZIONE CONFIGURAZIONI (solo se cambiate) # 8. PUBBLICAZIONE CONFIGURAZIONI
# ========================================== # ==========================================
def parse_ini(text): def parse_ini(text):
ini_data = {} ini_data = {}
@@ -630,7 +642,7 @@ def parse_ini(text):
def mask_sensitive(ini_data): def mask_sensitive(ini_data):
"""Nasconde Password/Secret/Token nei topic per sezione (NON tocca PassAllTG/PassAllPC, che servono al server).""" """Nasconde Password/Secret/Token nei topic per sezione."""
for payload in ini_data.values(): for payload in ini_data.values():
for k, v in payload.items(): for k, v in payload.items():
if SENSITIVE_KEY_RE.match(k) and str(v).strip(): if SENSITIVE_KEY_RE.match(k) and str(v).strip():
@@ -639,7 +651,6 @@ def mask_sensitive(ini_data):
def profile_only_sources(): def profile_only_sources():
"""File usati solo come sorgente di un profilo (es. *_BM.ini): per l'editor basta full_config."""
sources, targets = set(), set() sources, targets = set(), set()
for profile in cfg['profiles'].values(): for profile in cfg['profiles'].values():
for s in (profile.get('services', []) if isinstance(profile, dict) else []): for s in (profile.get('services', []) if isinstance(profile, dict) else []):
@@ -651,7 +662,6 @@ def profile_only_sources():
def publish_configs(force=False): def publish_configs(force=False):
"""Pubblica full_config e sezioni INI (retained) SOLO per i file cambiati dall'ultima volta."""
if not connected(): if not connected():
return return
skip_sections = profile_only_sources() skip_sections = profile_only_sources()
@@ -693,8 +703,6 @@ def find_profile(key):
def switch_config(key): def switch_config(key):
"""Ritorna (ok, label_o_errore). Non tocca nessun servizio se i controlli preliminari falliscono;
se qualcosa va storto ripristina la configurazione precedente e riavvia i servizi."""
pkey, profile = find_profile(key) pkey, profile = find_profile(key)
if not profile: if not profile:
return False, f"Profile {key} not found in JSON" return False, f"Profile {key} not found in JSON"
@@ -703,7 +711,6 @@ def switch_config(key):
if not services: if not services:
return False, f"No services configured for {pkey}" return False, f"No services configured for {pkey}"
# --- CONTROLLI PRELIMINARI (prima di fermare qualsiasi cosa) ---
for s in services: for s in services:
name, src, dst = s.get('name'), s.get('source'), s.get('target') name, src, dst = s.get('name'), s.get('source'), s.get('target')
if not (name and src and dst): if not (name and src and dst):
@@ -769,7 +776,6 @@ def switch_config(key):
# 10. SCRITTURA CONFIG DA REMOTO # 10. SCRITTURA CONFIG DA REMOTO
# ========================================== # ==========================================
def service_for_file(path): def service_for_file(path):
"""Servizio da riavviare dopo la modifica di un file di configurazione (None = nessuno)."""
stem = Path(path).stem stem = Path(path).stem
unit = resolve_unit(stem) unit = resolve_unit(stem)
if unit: if unit:
@@ -848,7 +854,7 @@ def check_auto_healing(status):
return return
if time.time() < heal_pause_until: if time.time() < heal_pause_until:
return return
if not ops_lock.acquire(blocking=False): # c'è un'operazione in corso: ci riprovo al prossimo giro if not ops_lock.acquire(blocking=False):
return return
try: try:
_heal(status) _heal(status)
@@ -861,7 +867,8 @@ def _heal(status):
for proc_name, state in status["processes"].items(): for proc_name, state in status["processes"].items():
norm = norm_name(proc_name) norm = norm_name(proc_name)
if state == "online": # Se il processo è online oppure è in esecuzione ma in attesa del broker (disconnected), non riavviarlo
if state in ("online", "disconnected"):
auto_healing_counter[proc_name] = 0 auto_healing_counter[proc_name] = 0
if norm in stopped_by_admin: if norm in stopped_by_admin:
stopped_by_admin.discard(norm) stopped_by_admin.discard(norm)
@@ -870,6 +877,7 @@ def _heal(status):
if norm in stopped_by_admin: if norm in stopped_by_admin:
continue # fermato volontariamente dalla dashboard continue # fermato volontariamente dalla dashboard
unit = resolve_unit(norm) unit = resolve_unit(norm)
if not unit or not unit_exists(unit) or unit_is_disabled(unit): if not unit or not unit_exists(unit) or unit_is_disabled(unit):
if norm not in _warned_units: if norm not in _warned_units:
@@ -903,7 +911,7 @@ def _heal(status):
# ========================================== # ==========================================
# 12. COMANDI (eseguiti da un thread dedicato, mai nella callback MQTT) # 12. COMANDI
# ========================================== # ==========================================
def enqueue(name, fn): def enqueue(name, fn):
try: try:
@@ -936,7 +944,7 @@ def do_switch_profile(key):
logger.error(f"Cambio profilo fallito: {text}") logger.error(f"Cambio profilo fallito: {text}")
log_to_broker(f"❌ {text}") log_to_broker(f"❌ {text}")
send_telegram_message(f"❌ Profile switch failed: {text}") send_telegram_message(f"❌ Profile switch failed: {text}")
publish_status() # anche in caso di errore: il server esce dallo stato "Sent..." publish_status()
publish_telemetry() publish_telemetry()
publish_configs() publish_configs()
@@ -963,7 +971,6 @@ def do_update_agent():
publish_status() publish_status()
return return
# La nuova versione deve almeno essere sintatticamente valida, altrimenti il nodo resterebbe irraggiungibile
check = run_cmd([sys.executable, "-c", check = run_cmd([sys.executable, "-c",
"import ast,sys; ast.parse(open(sys.argv[1], encoding='utf-8').read())", "import ast,sys; ast.parse(open(sys.argv[1], encoding='utf-8').read())",
os.path.abspath(__file__)], timeout=30) os.path.abspath(__file__)], timeout=30)
@@ -979,7 +986,6 @@ def do_update_agent():
log_to_broker("✅ Git pull completato. Riavvio in corso...") log_to_broker("✅ Git pull completato. Riavvio in corso...")
logger.info(f"Aggiornamento completato:\n{pull.stdout}") logger.info(f"Aggiornamento completato:\n{pull.stdout}")
time.sleep(1) time.sleep(1)
# Systemd (Restart=always) lo fa ripartire con il nuovo codice
os._exit(1) os._exit(1)
@@ -1017,7 +1023,6 @@ def do_reset_hat():
def do_toggle_telegram(new_state): def do_toggle_telegram(new_state):
try: try:
# si parte dal file su disco (non dalla copia in memoria) per non perdere modifiche fatte a mano
with open(CONFIG_PATH, 'r') as f: with open(CONFIG_PATH, 'r') as f:
disk = json.load(f) disk = json.load(f)
if not isinstance(disk.get('telegram'), dict): if not isinstance(disk.get('telegram'), dict):
@@ -1045,7 +1050,7 @@ def do_service_control(action, service):
if r.returncode == 0: if r.returncode == 0:
n = norm_name(service) n = norm_name(service)
if action == "stop": if action == "stop":
stopped_by_admin.add(n) # l'auto-healing non lo rialzerà stopped_by_admin.add(n)
else: else:
stopped_by_admin.discard(n) stopped_by_admin.discard(n)
save_state() save_state()
@@ -1061,7 +1066,7 @@ def do_service_control(action, service):
def do_global_request(): def do_global_request():
time.sleep(random.uniform(0, 5)) # evita che tutta la flotta risponda nello stesso istante time.sleep(random.uniform(0, 5))
publish_telemetry() publish_telemetry()
publish_configs(force=True) publish_configs(force=True)
publish_status() publish_status()
@@ -1073,7 +1078,7 @@ def initial_publish():
# ========================================== # ==========================================
# 13. MQTT CALLBACKS (leggere: validano e mettono in coda) # 13. MQTT CALLBACKS
# ========================================== # ==========================================
def handle_command(payload): def handle_command(payload):
cmd = payload.upper() cmd = payload.upper()
@@ -1113,7 +1118,7 @@ def on_connect(client, userdata, flags, reason_code, properties=None):
(TOPIC_CONTROL, 0), (TOPIC_CONTROL, 0),
(TOPIC_CONFIG_SET + "#", 0) (TOPIC_CONFIG_SET + "#", 0)
]) ])
publish_status() # a ogni connessione: dopo un blip il LWT ha messo il nodo OFFLINE publish_status()
enqueue("initial publish", initial_publish) enqueue("initial publish", initial_publish)
else: else:
logger.error(f"❌ MQTT connection error. Code: {reason_code}") logger.error(f"❌ MQTT connection error. Code: {reason_code}")
@@ -1168,7 +1173,7 @@ def telemetry_loop():
publish_configs() publish_configs()
else: else:
status = get_system_status() status = get_system_status()
check_auto_healing(status) # l'auto-healing è locale: funziona anche senza broker check_auto_healing(status)
except Exception as e: except Exception as e:
logger.error(f"❌ Errore critico nel thread telemetria: {e}") logger.error(f"❌ Errore critico nel thread telemetria: {e}")
time.sleep(get_update_interval()) time.sleep(get_update_interval())
@@ -1233,14 +1238,14 @@ def start_service():
client.on_message = on_message client.on_message = on_message
for target, name in ((command_worker, "commands"), (telegram_worker, "telegram"), for target, name in ((command_worker, "commands"), (telegram_worker, "telegram"),
(telemetry_loop, "telemetry"), (watchdog_loop, "watchdog")): (telemetry_loop, "telemetry"), (watchdog_loop, "watchdog"),
(update_checker_loop, "update_checker")):
threading.Thread(target=target, name=name, daemon=True).start() threading.Thread(target=target, name=name, daemon=True).start()
signal.signal(signal.SIGTERM, shutdown_handler) signal.signal(signal.SIGTERM, shutdown_handler)
signal.signal(signal.SIGINT, shutdown_handler) signal.signal(signal.SIGINT, shutdown_handler)
logger.info(f"Node agent v{AGENT_VERSION} avviato ({CLIENT_ID.upper()}). Connessione al broker...") logger.info(f"Node agent v{AGENT_VERSION} avviato ({CLIENT_ID.upper()}). Connessione al broker...")
# connect_async + loop_start: paho gestisce da solo primo collegamento e riconnessioni
client.connect_async(MQTT_CFG['broker'], int(MQTT_CFG['port']), int(MQTT_CFG.get('keepalive', 15))) client.connect_async(MQTT_CFG['broker'], int(MQTT_CFG['port']), int(MQTT_CFG.get('keepalive', 15)))
client.loop_start() client.loop_start()