Compare commits
15
Commits
c59f390a32
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8220039bf6 | ||
|
|
4e2eb29b26 | ||
|
|
26789736b1 | ||
|
|
de705c908e | ||
|
|
c6e8da311f | ||
|
|
1e98cb2477 | ||
|
|
7d5e3b9ca2 | ||
|
|
d1b39f7c69 | ||
|
|
e3f760ebf1 | ||
|
|
3020e076d4 | ||
|
|
f2345b979b | ||
|
|
f3b979fad9 | ||
|
|
92d163b98c | ||
|
|
78a45ce897 | ||
|
|
dcd33b4e7d |
Binary file not shown.
+137
-47
@@ -24,13 +24,27 @@ from pathlib import Path
|
|||||||
import logging
|
import logging
|
||||||
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
|
||||||
# ==========================================
|
# ==========================================
|
||||||
@@ -61,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():
|
||||||
@@ -127,7 +140,21 @@ 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
|
||||||
published_sig = {} # percorso file -> (mtime_ns, size) dell'ultima versione pubblicata
|
|
||||||
|
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
|
||||||
_warned_units = set()
|
_warned_units = set()
|
||||||
|
|
||||||
cmd_queue = queue.Queue(maxsize=20)
|
cmd_queue = queue.Queue(maxsize=20)
|
||||||
@@ -167,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:
|
||||||
@@ -206,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:
|
||||||
@@ -219,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():
|
||||||
@@ -244,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)
|
||||||
@@ -253,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)
|
||||||
|
|
||||||
@@ -307,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)}")
|
||||||
|
|
||||||
|
|
||||||
@@ -347,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):
|
||||||
@@ -361,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)
|
||||||
@@ -401,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:
|
||||||
@@ -417,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):
|
||||||
@@ -425,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):
|
||||||
@@ -460,7 +482,7 @@ def hardware_reset(auto=False):
|
|||||||
|
|
||||||
|
|
||||||
# ==========================================
|
# ==========================================
|
||||||
# 7. TELEMETRIA
|
# 7. TELEMETRIA E LETTURA VERSIONI
|
||||||
# ==========================================
|
# ==========================================
|
||||||
def get_cpu_temperature():
|
def get_cpu_temperature():
|
||||||
temp = 0.0
|
temp = 0.0
|
||||||
@@ -479,6 +501,49 @@ def get_cpu_temperature():
|
|||||||
logger.debug(f"Temperature read error: {e}")
|
logger.debug(f"Temperature read error: {e}")
|
||||||
return round(temp, 1)
|
return round(temp, 1)
|
||||||
|
|
||||||
|
def get_binary_versions():
|
||||||
|
"""Interroga direttamente tutti i binari della suite MMDVM supportando nomi multipli."""
|
||||||
|
versions = {}
|
||||||
|
|
||||||
|
def find_cmd(names):
|
||||||
|
for name in names:
|
||||||
|
cmd_path = shutil.which(name)
|
||||||
|
if cmd_path:
|
||||||
|
return cmd_path
|
||||||
|
for base in ['/usr/local/bin', '/usr/bin', '/opt/MMDVMHost', '/opt/DMRGateway']:
|
||||||
|
full = os.path.join(base, name)
|
||||||
|
if os.path.isfile(full):
|
||||||
|
return full
|
||||||
|
return names[0]
|
||||||
|
|
||||||
|
binaries = {
|
||||||
|
"MMDVMHost": ["MMDVMHost", "MMDVM-Host"],
|
||||||
|
"DMRGateway": ["DMRGateway"],
|
||||||
|
"YSFGateway": ["YSFGateway"],
|
||||||
|
"NXDNGateway": ["NXDNGateway"],
|
||||||
|
"P25Gateway": ["P25Gateway"],
|
||||||
|
"DStarGateway": ["dstargateway", "dstar-gateway"]
|
||||||
|
}
|
||||||
|
|
||||||
|
for chiave, lista_eseguibili in binaries.items():
|
||||||
|
cmd_reale = [find_cmd(lista_eseguibili), "-v"]
|
||||||
|
r = run_cmd(cmd_reale, timeout=3)
|
||||||
|
|
||||||
|
if r.returncode == 0 and r.stdout:
|
||||||
|
testo = r.stdout.strip().split('\n')[0]
|
||||||
|
|
||||||
|
import re
|
||||||
|
testo_pulito = re.sub(r'^[A-Za-z0-9_\-]+\s+version\s+', '', testo, flags=re.IGNORECASE)
|
||||||
|
|
||||||
|
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:]
|
||||||
|
|
||||||
|
if chiave not in versions or versions[chiave] == "":
|
||||||
|
versions[chiave] = testo_pulito.strip()
|
||||||
|
|
||||||
|
return versions
|
||||||
|
|
||||||
def get_system_status():
|
def get_system_status():
|
||||||
status = {
|
status = {
|
||||||
@@ -490,39 +555,71 @@ 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})",
|
||||||
|
"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:
|
||||||
status["processes"][n] = "online" if n in running else "offline"
|
# Trova i processi che matchano il nome (ignorando i trattini)
|
||||||
|
matching_procs = [p for p in running_procs if (p.info.get('name') or '').lower().replace('-', '') == n.replace('-', '')]
|
||||||
|
|
||||||
|
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():
|
||||||
status = get_system_status()
|
status = get_system_status()
|
||||||
stems = [Path(f).stem for f in read_lines(FILE_LIST_PATH)]
|
stems = [Path(f).stem for f in read_lines(FILE_LIST_PATH)]
|
||||||
status["config_files"] = stems
|
status["config_files"] = stems
|
||||||
status["files"] = stems
|
status["files"] = stems
|
||||||
<<<<<<< HEAD
|
|
||||||
# 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)]
|
||||||
=======
|
|
||||||
>>>>>>> 50f362009085ba48f19cd80b8453876407b3cb1d
|
|
||||||
if connected():
|
if connected():
|
||||||
mqtt_client.publish(TOPIC_SERVICES, json.dumps(status), qos=1)
|
mqtt_client.publish(TOPIC_SERVICES, json.dumps(status), qos=1)
|
||||||
return status
|
return status
|
||||||
|
|
||||||
|
|
||||||
# ==========================================
|
# ==========================================
|
||||||
# 8. PUBBLICAZIONE CONFIGURAZIONI (solo se cambiate)
|
# 8. PUBBLICAZIONE CONFIGURAZIONI
|
||||||
# ==========================================
|
# ==========================================
|
||||||
def parse_ini(text):
|
def parse_ini(text):
|
||||||
ini_data = {}
|
ini_data = {}
|
||||||
@@ -545,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():
|
||||||
@@ -554,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 []):
|
||||||
@@ -566,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()
|
||||||
@@ -608,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"
|
||||||
@@ -618,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):
|
||||||
@@ -684,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:
|
||||||
@@ -763,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)
|
||||||
@@ -776,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)
|
||||||
@@ -785,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:
|
||||||
@@ -818,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:
|
||||||
@@ -851,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()
|
||||||
|
|
||||||
@@ -878,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)
|
||||||
@@ -894,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)
|
||||||
|
|
||||||
|
|
||||||
@@ -932,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):
|
||||||
@@ -960,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()
|
||||||
@@ -976,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()
|
||||||
@@ -988,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()
|
||||||
@@ -1028,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}")
|
||||||
@@ -1083,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())
|
||||||
@@ -1148,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()
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user