Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d81ba078be | ||
|
|
00feb2df6c | ||
|
|
311c4053f0 |
@@ -0,0 +1,41 @@
|
|||||||
|
# Modifiche di sicurezza e correzioni / Security fixes & changes
|
||||||
|
|
||||||
|
Tutte le modifiche mantengono il comportamento precedente **per default**; ciò che cambia
|
||||||
|
visibilmente è indicato esplicitamente. / Every change keeps the previous behaviour **by default**;
|
||||||
|
visible differences are listed explicitly.
|
||||||
|
|
||||||
|
## Correzioni attive subito / Active immediately
|
||||||
|
|
||||||
|
| # | Modifica | Effetto visibile |
|
||||||
|
|---|----------|------------------|
|
||||||
|
| 1 | **Scheduler**: i profili/comandi vengono validati come in `/api/command`. `REBOOT`, `RESET_HAT`, `UPDATE_AGENT` possono essere schedulati solo da un `admin` (controllo al salvataggio **e** all'esecuzione). I nodi target vengono validati. | Un `node_admin` non può più programmare comandi riservati agli admin. Schedulazioni già presenti create da non-admin con quei comandi non vengono più eseguite (warning nel log). |
|
||||||
|
| 2 | **WebSocket `live_log_<nodo>`**: inviato solo ai socket con sessione valida **e** autorizzati su quel nodo (ruolo/`allowed_nodes` rivalidati ogni 2 min). | Nessuno per l'uso normale: la console log già richiedeva il login via `/api/logs/<nodo>`. Chi non è loggato non riceve più i log in diretta. |
|
||||||
|
| 3 | **Rate limit login dietro reverse proxy**: se la richiesta arriva da loopback con `X-Forwarded-For`, si usa l'IP reale (ultimo valore, aggiunto dal proxy). Con `trust_proxy: true` il comportamento è invariato. | Un utente che sbaglia la password non blocca più il login a tutti gli altri. |
|
||||||
|
| 4 | **Scheduler su thread dedicato**: non è più ritardato dal download degli ID DMR/NXDN. | Le schedulazioni partono puntuali anche durante i download. |
|
||||||
|
| 5 | **Pruning**: `telemetry_logs` (default 90 giorni) e `config_backups` (ultimi 100 per nodo/servizio) ora vengono potati. | Dati più vecchi di quelle soglie vengono eliminati; configurabile (0 = disattiva). |
|
||||||
|
| 6 | `save_to_sqlite` chiude sempre la connessione; `__main__` usa `web.port`; emoji corrotta nel log; `test-push.py` funzionante; nomi file in `install.txt` corretti; `chart.js` fissato alla versione 4.4.1. | Nessuno. |
|
||||||
|
|
||||||
|
## Opzioni nuove (tutte disattivate / invariate di default) / New opt-in options
|
||||||
|
|
||||||
|
Nel blocco `web` di `config.json` (vedi `config.json.example`):
|
||||||
|
|
||||||
|
* `require_login_for_read: true` – richiede il login per `/api/states`, `/api/logs`, `/api/stats`, `/api/clients` e limita `aprs_msg` ai soli utenti loggati. **Attenzione:** la vista pubblica della dashboard resterà vuota finché non si fa il login.
|
||||||
|
* `cors_origins: "https://tuo.dominio"` – restringe le origini ammesse per Socket.IO (default `"*"`, invariato).
|
||||||
|
* `ota_enabled: false` – disabilita l'aggiornamento OTA da interfaccia (`git pull` + riavvio).
|
||||||
|
* `trust_proxy`, `cookie_secure` (consigliato `true` dietro HTTPS), `session_hours`.
|
||||||
|
|
||||||
|
Nel blocco `mqtt`: `"tls": true` (+ `"ca_certs"`, porta tipicamente 8883) per cifrare la connessione al broker.
|
||||||
|
Altre chiavi: `telemetry_retention_days`, `config_backups_keep`.
|
||||||
|
|
||||||
|
## Non modificato di proposito / Deliberately left as is
|
||||||
|
|
||||||
|
* **Servizio come root e bind su 0.0.0.0**: cambiarlo di default romperebbe le installazioni esistenti
|
||||||
|
(permessi su cartella/log, accesso diretto alla porta 9000). È incluso
|
||||||
|
`systemd/fleet-console.hardened.service.example` con utente dedicato e hardening, da adottare quando vuoi.
|
||||||
|
* **CSP e SRI**: la UI usa molti stili e handler inline, quindi una CSP rigida la romperebbe; l'SRI richiede
|
||||||
|
gli hash delle librerie (calcolabili con `curl -s URL | openssl dgst -sha384 -binary | openssl base64 -A`).
|
||||||
|
* **Broker MQTT**: l'autenticazione dei messaggi e le ACL per nodo si configurano sul broker (es. Mosquitto
|
||||||
|
`acl_file`), non nel server.
|
||||||
|
* **Backup di config in chiaro**: i file `.ini` salvati in `config_backups` possono contenere password di rete.
|
||||||
|
Proteggere `monitor.db` con permessi `600`.
|
||||||
|
* **Schedulazioni sovrapposte** sugli stessi nodi e ripristino del "profilo precedente": non gestiti.
|
||||||
@@ -4,22 +4,26 @@ gevent.monkey.patch_all()
|
|||||||
import os
|
import os
|
||||||
import subprocess
|
import subprocess
|
||||||
import threading
|
import threading
|
||||||
from flask import Flask, render_template, request
|
import time
|
||||||
from flask_socketio import emit
|
from contextlib import closing
|
||||||
|
from flask import Flask, render_template, request, jsonify
|
||||||
|
from flask_socketio import emit, SocketIO
|
||||||
|
|
||||||
# --- IMPORT MODULI CORE ---
|
# --- IMPORT MODULI CORE ---
|
||||||
from core.config import BASE_DIR, get_secret_key, web_cfg, logger
|
from core.config import BASE_DIR, get_secret_key, web_cfg, logger
|
||||||
from core.database import init_db
|
from core.database import init_db, get_last_known_states
|
||||||
import core.state as state
|
import core.state as state
|
||||||
|
from core.state import clear_all_nodes, update_node_state
|
||||||
|
|
||||||
# --- IMPORT SERVIZI ---
|
# --- IMPORT SERVIZI ---
|
||||||
from services.push_service import push_worker
|
from services.push_service import push_worker
|
||||||
from services.watchdog_service import watchdog_loop
|
from services.watchdog_service import watchdog_loop
|
||||||
from services.scheduler_service import auto_update_ids
|
from services.scheduler_service import auto_update_ids, schedule_loop
|
||||||
import services.mqtt_service as mqtt_svc
|
import services.mqtt_service as mqtt_svc
|
||||||
|
|
||||||
# --- IMPORT ROTTE / BLUEPRINTS ---
|
# --- IMPORT ROTTE / BLUEPRINTS ---
|
||||||
from routes.auth_routes import auth_bp
|
from routes.auth_routes import auth_bp, get_auth
|
||||||
|
from core.database import db_connect
|
||||||
from routes.api_routes import api_bp
|
from routes.api_routes import api_bp
|
||||||
|
|
||||||
# Inizializzazione Flask
|
# Inizializzazione Flask
|
||||||
@@ -36,12 +40,31 @@ app.config.update(
|
|||||||
)
|
)
|
||||||
|
|
||||||
# Collegamento SocketIO
|
# Collegamento SocketIO
|
||||||
state.socketio.init_app(app)
|
socketio = SocketIO(app, cors_allowed_origins="*", async_mode='gevent')
|
||||||
|
|
||||||
|
# Rendiamo disponibile l'istanza globale socketio nel modulo state
|
||||||
|
# in modo che gli altri servizi (mqtt_service, push_service, api_routes)
|
||||||
|
# che importano `from core.state import socketio` continuino a funzionare.
|
||||||
|
state.socketio = socketio
|
||||||
|
|
||||||
# Registrazione Blueprint
|
# Registrazione Blueprint
|
||||||
app.register_blueprint(auth_bp)
|
app.register_blueprint(auth_bp)
|
||||||
app.register_blueprint(api_bp)
|
app.register_blueprint(api_bp)
|
||||||
|
|
||||||
|
# Aggiungi la funzione di sincronizzazione
|
||||||
|
def init_fleet_state():
|
||||||
|
"""Bootloader: sincronizza Redis con il DB all'avvio del worker."""
|
||||||
|
app.logger.info("Inizializzazione stato flotta su Redis...")
|
||||||
|
clear_all_nodes()
|
||||||
|
|
||||||
|
last_states = get_last_known_states()
|
||||||
|
for node_id, data in last_states.items():
|
||||||
|
data["status"] = "RECONNECTING"
|
||||||
|
update_node_state(node_id, data)
|
||||||
|
|
||||||
|
# Esegui la sincronizzazione prima di far partire i servizi
|
||||||
|
init_fleet_state()
|
||||||
|
|
||||||
# Security Headers
|
# Security Headers
|
||||||
@app.after_request
|
@app.after_request
|
||||||
def add_security_headers(resp):
|
def add_security_headers(resp):
|
||||||
@@ -52,6 +75,17 @@ def add_security_headers(resp):
|
|||||||
resp.headers['Cache-Control'] = 'no-store'
|
resp.headers['Cache-Control'] = 'no-store'
|
||||||
return resp
|
return resp
|
||||||
|
|
||||||
|
# Se in config.json -> "web": {"require_login_for_read": true} le API di sola lettura richiedono il login.
|
||||||
|
# Default: disattivato (la dashboard pubblica funziona come prima).
|
||||||
|
READ_PROTECTED_PATHS = ('/api/states', '/api/logs', '/api/stats', '/api/clients')
|
||||||
|
|
||||||
|
@app.before_request
|
||||||
|
def enforce_read_login():
|
||||||
|
if web_cfg.get('require_login_for_read') and request.path in READ_PROTECTED_PATHS:
|
||||||
|
if not get_auth():
|
||||||
|
return jsonify({"success": False, "error": "Login richiesto"}), 401
|
||||||
|
return None
|
||||||
|
|
||||||
def get_git_commit():
|
def get_git_commit():
|
||||||
try:
|
try:
|
||||||
return subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD'], cwd=BASE_DIR).decode('utf-8').strip()
|
return subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD'], cwd=BASE_DIR).decode('utf-8').strip()
|
||||||
@@ -64,30 +98,47 @@ SERVER_COMMIT = get_git_commit()
|
|||||||
def index():
|
def index():
|
||||||
return render_template('index.html', git_commit=SERVER_COMMIT)
|
return render_template('index.html', git_commit=SERVER_COMMIT)
|
||||||
|
|
||||||
from flask import session
|
@socketio.on('connect')
|
||||||
|
|
||||||
@state.socketio.on('connect')
|
|
||||||
def handle_connect():
|
def handle_connect():
|
||||||
state.connected_web_clients.add(request.sid)
|
state.connected_web_clients.add(request.sid)
|
||||||
|
|
||||||
# Se l'utente è loggato (session), associamo il suo username al SID
|
# Se l'utente è loggato (session), associamo il suo username al SID
|
||||||
user = session.get('user')
|
auth = get_auth()
|
||||||
if user:
|
if auth:
|
||||||
state.active_logged_users[request.sid] = user
|
state.active_logged_users[request.sid] = auth['username']
|
||||||
|
state.socket_auth[request.sid] = {
|
||||||
|
"username": auth['username'], "role": auth['role'],
|
||||||
|
"allowed_nodes": auth['allowed_nodes'], "ts": time.time()
|
||||||
|
}
|
||||||
|
|
||||||
emit('mqtt_status', {'connected': mqtt_svc.mqtt_connected_status})
|
emit('mqtt_status', {'connected': mqtt_svc.mqtt_connected_status})
|
||||||
|
|
||||||
# Prepariamo la lista unica degli utenti loggati attivi (togliendo i duplicati se un utente ha più tab aperti)
|
# Prepariamo la lista unica degli utenti loggati attivi (togliendo i duplicati se un utente ha più tab aperti)
|
||||||
logged_names = list(set(state.active_logged_users.values()))
|
logged_names = list(set(state.active_logged_users.values()))
|
||||||
state.socketio.emit('web_users_count', {'count': len(state.connected_web_clients), 'users': logged_names})
|
socketio.emit('web_users_count', {'count': len(state.connected_web_clients), 'users': logged_names})
|
||||||
|
|
||||||
@state.socketio.on('disconnect')
|
@socketio.on('disconnect')
|
||||||
def handle_disconnect():
|
def handle_disconnect():
|
||||||
state.connected_web_clients.discard(request.sid)
|
state.connected_web_clients.discard(request.sid)
|
||||||
state.active_logged_users.pop(request.sid, None)
|
state.active_logged_users.pop(request.sid, None)
|
||||||
|
state.socket_auth.pop(request.sid, None)
|
||||||
|
|
||||||
logged_names = list(set(state.active_logged_users.values()))
|
logged_names = list(set(state.active_logged_users.values()))
|
||||||
state.socketio.emit('web_users_count', {'count': len(state.connected_web_clients), 'users': logged_names})
|
socketio.emit('web_users_count', {'count': len(state.connected_web_clients), 'users': logged_names})
|
||||||
|
|
||||||
|
def _lookup_auth(username):
|
||||||
|
"""Ruolo/nodi aggiornati di un utente (usato per rivalidare i socket gia' connessi)."""
|
||||||
|
try:
|
||||||
|
with closing(db_connect(row=True)) as conn:
|
||||||
|
row = conn.execute("SELECT role, allowed_nodes FROM users WHERE username = ?", (username,)).fetchone()
|
||||||
|
if not row:
|
||||||
|
return None
|
||||||
|
return {"role": row['role'], "allowed_nodes": row['allowed_nodes'] or ''}
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"lookup auth socket: {e}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
state.auth_lookup = _lookup_auth
|
||||||
|
|
||||||
# --- INIZIALIZZAZIONE SISTEMA & THREAD ---
|
# --- INIZIALIZZAZIONE SISTEMA & THREAD ---
|
||||||
init_db()
|
init_db()
|
||||||
@@ -95,11 +146,12 @@ state.seed_last_seen()
|
|||||||
mqtt_svc.start_mqtt()
|
mqtt_svc.start_mqtt()
|
||||||
|
|
||||||
threading.Thread(target=auto_update_ids, daemon=True).start()
|
threading.Thread(target=auto_update_ids, daemon=True).start()
|
||||||
|
threading.Thread(target=schedule_loop, daemon=True).start()
|
||||||
threading.Thread(target=push_worker, daemon=True).start()
|
threading.Thread(target=push_worker, daemon=True).start()
|
||||||
threading.Thread(target=watchdog_loop, daemon=True).start()
|
threading.Thread(target=watchdog_loop, daemon=True).start()
|
||||||
|
|
||||||
logger.info(f"🚀 Fleet Control Console modulare pronta (Git Rev: {SERVER_COMMIT})")
|
logger.info(f"🚀 Fleet Control Console modulare pronta (Git Rev: {SERVER_COMMIT})")
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
port = int(config.get('web', {}).get('port', 9000)) if 'config' in locals() else 9000
|
port = int(web_cfg.get('port', 9000))
|
||||||
state.socketio.run(app, host='0.0.0.0', port=port)
|
socketio.run(app, host='0.0.0.0', port=port)
|
||||||
|
|||||||
+18
-2
@@ -17,8 +17,10 @@
|
|||||||
"devices/#",
|
"devices/#",
|
||||||
"data/#",
|
"data/#",
|
||||||
"aprs-gateway/aprs"
|
"aprs-gateway/aprs"
|
||||||
]
|
],
|
||||||
|
"tls": false
|
||||||
},
|
},
|
||||||
|
|
||||||
"web_admin": {
|
"web_admin": {
|
||||||
"default_user": "admin",
|
"default_user": "admin",
|
||||||
"default_pass": "admin123"
|
"default_pass": "admin123"
|
||||||
@@ -41,5 +43,19 @@
|
|||||||
},
|
},
|
||||||
"log_max_mb": 50,
|
"log_max_mb": 50,
|
||||||
"log_backup_count": 10,
|
"log_backup_count": 10,
|
||||||
"last_heard_limit": 60
|
"last_heard_limit": 60,
|
||||||
|
"web": {
|
||||||
|
"port": 9000,
|
||||||
|
"redis_url": "redis://localhost:6379/0",
|
||||||
|
"cookie_secure": false,
|
||||||
|
"session_hours": 12,
|
||||||
|
"trust_proxy": false,
|
||||||
|
"cors_origins": "*",
|
||||||
|
"require_login_for_read": false,
|
||||||
|
"ota_enabled": true
|
||||||
|
},
|
||||||
|
"retention_days": 90,
|
||||||
|
"audit_retention_days": 365,
|
||||||
|
"telemetry_retention_days": 90,
|
||||||
|
"config_backups_keep": 100
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,10 @@ import logging
|
|||||||
import threading
|
import threading
|
||||||
from logging.handlers import RotatingFileHandler
|
from logging.handlers import RotatingFileHandler
|
||||||
|
|
||||||
|
settings = {
|
||||||
|
"REDIS_URL": os.getenv("REDIS_URL", "redis://localhost:6379/0")
|
||||||
|
}
|
||||||
|
|
||||||
# --- PERCORSI DINAMICI ---
|
# --- PERCORSI DINAMICI ---
|
||||||
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||||
|
|
||||||
|
|||||||
+41
-4
@@ -95,6 +95,13 @@ def init_db():
|
|||||||
|
|
||||||
def save_to_sqlite(client_id, data, protocol="DMR"):
|
def save_to_sqlite(client_id, data, protocol="DMR"):
|
||||||
conn = sqlite3.connect(DB_PATH, timeout=10)
|
conn = sqlite3.connect(DB_PATH, timeout=10)
|
||||||
|
try:
|
||||||
|
_save_to_sqlite(conn, client_id, data, protocol)
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
notify_update('log_aggiornato')
|
||||||
|
|
||||||
|
def _save_to_sqlite(conn, client_id, data, protocol):
|
||||||
c = conn.cursor()
|
c = conn.cursor()
|
||||||
|
|
||||||
rssi_val = 0
|
rssi_val = 0
|
||||||
@@ -110,8 +117,6 @@ def save_to_sqlite(client_id, data, protocol="DMR"):
|
|||||||
data.get('slot', 0), round(data.get('duration', 0), 1), round(data.get('ber', 0), 2),
|
data.get('slot', 0), round(data.get('duration', 0), 1), round(data.get('ber', 0), 2),
|
||||||
str(data.get('src_ext', '')), rssi_val, str(data.get('source', '')), str(data.get('mode', ''))))
|
str(data.get('src_ext', '')), rssi_val, str(data.get('source', '')), str(data.get('mode', ''))))
|
||||||
conn.commit()
|
conn.commit()
|
||||||
conn.close()
|
|
||||||
notify_update('log_aggiornato')
|
|
||||||
|
|
||||||
def audit(username, client_id, command):
|
def audit(username, client_id, command):
|
||||||
try:
|
try:
|
||||||
@@ -133,9 +138,23 @@ def prune_old_data():
|
|||||||
n1 = c.rowcount
|
n1 = c.rowcount
|
||||||
c.execute("DELETE FROM audit_logs WHERE timestamp < datetime('now', 'localtime', ?)", (f"-{audit_days} days",))
|
c.execute("DELETE FROM audit_logs WHERE timestamp < datetime('now', 'localtime', ?)", (f"-{audit_days} days",))
|
||||||
n2 = c.rowcount
|
n2 = c.rowcount
|
||||||
|
# Telemetria e backup config non venivano mai potati (default generosi, configurabili)
|
||||||
|
tele_days = int(cfg.get("telemetry_retention_days", 90))
|
||||||
|
n3 = 0
|
||||||
|
if tele_days > 0:
|
||||||
|
c.execute("DELETE FROM telemetry_logs WHERE timestamp < datetime('now', 'localtime', ?)", (f"-{tele_days} days",))
|
||||||
|
n3 = c.rowcount
|
||||||
|
keep = int(cfg.get("config_backups_keep", 100))
|
||||||
|
n4 = 0
|
||||||
|
if keep > 0:
|
||||||
|
c.execute("""DELETE FROM config_backups WHERE id NOT IN (
|
||||||
|
SELECT id FROM config_backups b
|
||||||
|
WHERE b.client_id = config_backups.client_id AND b.service = config_backups.service
|
||||||
|
ORDER BY id DESC LIMIT ?)""", (keep,))
|
||||||
|
n4 = c.rowcount
|
||||||
conn.commit()
|
conn.commit()
|
||||||
if n1 or n2:
|
if n1 or n2 or n3 or n4:
|
||||||
logger.info(f"🧹 Pulizia DB: {n1} ascolti e {n2} audit rimossi.")
|
logger.info(f"🧹 Pulizia DB: {n1} ascolti, {n2} audit, {n3} telemetrie e {n4} backup config rimossi.")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"❌ Errore pulizia DB: {e}")
|
logger.error(f"❌ Errore pulizia DB: {e}")
|
||||||
|
|
||||||
@@ -147,3 +166,21 @@ def save_telemetry_to_sqlite(client_id, health_data):
|
|||||||
conn.commit()
|
conn.commit()
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Errore salvataggio telemetria: {e}")
|
logger.error(f"Errore salvataggio telemetria: {e}")
|
||||||
|
|
||||||
|
def get_last_known_states() -> dict:
|
||||||
|
"""
|
||||||
|
Recupera l'ultimo stato noto della flotta dal database.
|
||||||
|
Usato dal bootloader in app.py al riavvio del servizio.
|
||||||
|
"""
|
||||||
|
return {}
|
||||||
|
|
||||||
|
import logging
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
def archive_node_error(node_id: str, state_data: dict) -> None:
|
||||||
|
"""
|
||||||
|
Salva il nodo su database relazionale (PostgreSQL/SQLite)
|
||||||
|
quando entra in uno stato di errore severo e prolungato.
|
||||||
|
"""
|
||||||
|
logger.error(f"[DB] Archiviazione stato critico per nodo {node_id}: {state_data}")
|
||||||
|
# TODO: Inserire qui la vera query di inserimento nel DB
|
||||||
|
|||||||
@@ -0,0 +1,10 @@
|
|||||||
|
"""Controllo permessi sui nodi, condiviso da API, push e WebSocket (nessuna dipendenza interna)."""
|
||||||
|
|
||||||
|
|
||||||
|
def node_allowed(role, allowed_nodes, cid):
|
||||||
|
if role == 'admin':
|
||||||
|
return True
|
||||||
|
allowed = (allowed_nodes or '').strip().lower()
|
||||||
|
if allowed == 'all':
|
||||||
|
return True
|
||||||
|
return cid in [x.strip().lower() for x in allowed.split(',') if x.strip()]
|
||||||
+148
-2
@@ -3,9 +3,11 @@ import json
|
|||||||
import time
|
import time
|
||||||
import threading
|
import threading
|
||||||
import sqlite3
|
import sqlite3
|
||||||
|
import redis
|
||||||
from contextlib import closing
|
from contextlib import closing
|
||||||
from flask_socketio import SocketIO
|
from flask_socketio import SocketIO
|
||||||
from core.config import CACHE_FILE, DB_PATH, DMR_IDS_PATH, NXDN_IDS_PATH, logger, web_cfg
|
from core.config import CACHE_FILE, DB_PATH, DMR_IDS_PATH, NXDN_IDS_PATH, logger, web_cfg
|
||||||
|
from core.permissions import node_allowed
|
||||||
|
|
||||||
# --- WEBSOCKET SOCKETIO ---
|
# --- WEBSOCKET SOCKETIO ---
|
||||||
socketio = SocketIO(cors_allowed_origins=web_cfg.get('cors_origins', '*'))
|
socketio = SocketIO(cors_allowed_origins=web_cfg.get('cors_origins', '*'))
|
||||||
@@ -33,8 +35,20 @@ def notify_update(event='dati_aggiornati'):
|
|||||||
timer.daemon = True
|
timer.daemon = True
|
||||||
timer.start()
|
timer.start()
|
||||||
|
|
||||||
|
# --- REDIS CLIENT & NAMESPACE ---
|
||||||
|
REDIS_URL = os.getenv("REDIS_URL", web_cfg.get("redis_url", "redis://localhost:6379/0"))
|
||||||
|
try:
|
||||||
|
redis_client = redis.from_url(REDIS_URL, decode_responses=True)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Errore connessione Redis ({REDIS_URL}): {e}")
|
||||||
|
redis_client = None
|
||||||
|
|
||||||
|
NAMESPACE = "fleet:node:"
|
||||||
|
|
||||||
# --- STATI GLOBALI IN MEMORIA ---
|
# --- STATI GLOBALI IN MEMORIA ---
|
||||||
START_TIME = time.time()
|
START_TIME = time.time()
|
||||||
|
state_lock = threading.RLock()
|
||||||
|
|
||||||
client_states = {}
|
client_states = {}
|
||||||
device_configs = {}
|
device_configs = {}
|
||||||
client_telemetry = {}
|
client_telemetry = {}
|
||||||
@@ -51,6 +65,35 @@ operating_modes = {}
|
|||||||
node_logs = {} # In-memory circular buffer for live logs
|
node_logs = {} # In-memory circular buffer for live logs
|
||||||
connected_web_clients = set()
|
connected_web_clients = set()
|
||||||
active_logged_users = {}
|
active_logged_users = {}
|
||||||
|
socket_auth = {} # sid -> {"username","role","allowed_nodes","ts"} (solo socket con sessione valida)
|
||||||
|
auth_lookup = None # impostato da app.py: username -> dict auth aggiornato oppure None
|
||||||
|
|
||||||
|
AUTH_REFRESH_SEC = 120
|
||||||
|
|
||||||
|
def emit_to_authorized(event, data, cid=None):
|
||||||
|
"""Invia l'evento solo ai socket autenticati (e, se cid e' dato, autorizzati su quel nodo)."""
|
||||||
|
now = time.time()
|
||||||
|
for sid, a in list(socket_auth.items()):
|
||||||
|
try:
|
||||||
|
# Rilegge periodicamente ruolo/nodi: utenti rimossi o declassati perdono l'accesso live
|
||||||
|
if auth_lookup and now - a.get('ts', 0) > AUTH_REFRESH_SEC:
|
||||||
|
fresh = auth_lookup(a['username'])
|
||||||
|
if not fresh:
|
||||||
|
socket_auth.pop(sid, None)
|
||||||
|
continue
|
||||||
|
a.update(fresh)
|
||||||
|
a['ts'] = now
|
||||||
|
if cid is None or node_allowed(a.get('role'), a.get('allowed_nodes'), cid):
|
||||||
|
socketio.emit(event, data, to=sid)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"emit_to_authorized '{event}': {e}")
|
||||||
|
|
||||||
|
def emit_aprs(data):
|
||||||
|
"""APRS live: broadcast come prima, oppure solo utenti loggati se web.require_login_for_read."""
|
||||||
|
if web_cfg.get('require_login_for_read'):
|
||||||
|
emit_to_authorized('aprs_msg', data)
|
||||||
|
else:
|
||||||
|
socketio.emit('aprs_msg', data)
|
||||||
|
|
||||||
# Caricamento iniziale cache telemetria
|
# Caricamento iniziale cache telemetria
|
||||||
if os.path.exists(CACHE_FILE):
|
if os.path.exists(CACHE_FILE):
|
||||||
@@ -98,6 +141,109 @@ def seed_last_seen():
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"seed_last_seen: {e}")
|
logger.error(f"seed_last_seen: {e}")
|
||||||
|
|
||||||
|
# --- FUNZIONI DI GESTIONE STATO & REDIS ---
|
||||||
|
def update_node_state(node_id: str, payload: dict) -> None:
|
||||||
|
"""Aggiorna lo stato del nodo sia in memoria locale che su Redis in modo sicuro."""
|
||||||
|
if not node_id:
|
||||||
|
return
|
||||||
|
|
||||||
|
with state_lock:
|
||||||
|
current = client_states.get(node_id)
|
||||||
|
# Se lo stato attuale è una stringa semplice, convertilo in dizionario
|
||||||
|
if not isinstance(current, dict):
|
||||||
|
current = {"status": current} if isinstance(current, str) else {}
|
||||||
|
client_states[node_id] = current
|
||||||
|
|
||||||
|
if isinstance(payload, dict):
|
||||||
|
current.update(payload)
|
||||||
|
elif isinstance(payload, str):
|
||||||
|
current["status"] = payload
|
||||||
|
|
||||||
|
touch_seen(node_id, 'mqtt')
|
||||||
|
|
||||||
|
# Scrittura asincrona/pipeline su Redis
|
||||||
|
if redis_client:
|
||||||
|
try:
|
||||||
|
key = f"{NAMESPACE}{node_id}"
|
||||||
|
if isinstance(payload, dict):
|
||||||
|
flat_payload = {
|
||||||
|
k: (json.dumps(v) if isinstance(v, (dict, list)) else str(v))
|
||||||
|
for k, v in payload.items()
|
||||||
|
}
|
||||||
|
else:
|
||||||
|
flat_payload = {"status": str(payload)}
|
||||||
|
|
||||||
|
if flat_payload:
|
||||||
|
pipeline = redis_client.pipeline()
|
||||||
|
pipeline.hset(key, mapping=flat_payload)
|
||||||
|
pipeline.execute()
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Errore update Redis nodo {node_id}: {e}")
|
||||||
|
|
||||||
|
notify_update()
|
||||||
|
|
||||||
|
def get_node_state(node_id: str) -> dict:
|
||||||
|
"""Recupera lo stato del nodo da Redis, con fallback sulla memoria locale."""
|
||||||
|
if redis_client:
|
||||||
|
try:
|
||||||
|
key = f"{NAMESPACE}{node_id}"
|
||||||
|
data = redis_client.hgetall(key)
|
||||||
|
if data:
|
||||||
|
for k, v in data.items():
|
||||||
|
try:
|
||||||
|
if str(v).startswith(("{", "[")):
|
||||||
|
data[k] = json.loads(v)
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
pass
|
||||||
|
return data
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Errore lettura Redis nodo {node_id}: {e}")
|
||||||
|
|
||||||
|
with state_lock:
|
||||||
|
return dict(client_states.get(node_id, {}))
|
||||||
|
|
||||||
|
def get_all_nodes() -> dict:
|
||||||
|
"""Scansiona tutti i nodi registrati in Redis o memoria."""
|
||||||
|
if redis_client:
|
||||||
|
try:
|
||||||
|
nodes = {}
|
||||||
|
for key in redis_client.scan_iter(match=f"{NAMESPACE}*"):
|
||||||
|
node_id = key.split(":")[-1]
|
||||||
|
nodes[node_id] = get_node_state(node_id)
|
||||||
|
if nodes:
|
||||||
|
return nodes
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Errore get_all_nodes Redis: {e}")
|
||||||
|
|
||||||
|
with state_lock:
|
||||||
|
return dict(client_states)
|
||||||
|
|
||||||
|
def delete_node(node_id: str) -> None:
|
||||||
|
"""Rimuove il nodo da Redis e dalla memoria locale."""
|
||||||
|
with state_lock:
|
||||||
|
client_states.pop(node_id, None)
|
||||||
|
|
||||||
|
if redis_client:
|
||||||
|
try:
|
||||||
|
key = f"{NAMESPACE}{node_id}"
|
||||||
|
redis_client.delete(key)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Errore delete Redis nodo {node_id}: {e}")
|
||||||
|
|
||||||
|
notify_update()
|
||||||
|
|
||||||
|
def clear_all_nodes() -> None:
|
||||||
|
"""Svuota la cache nodi da Redis e memoria locale (usato al boot)."""
|
||||||
|
with state_lock:
|
||||||
|
client_states.clear()
|
||||||
|
|
||||||
|
if redis_client:
|
||||||
|
try:
|
||||||
|
for key in redis_client.scan_iter(match=f"{NAMESPACE}*"):
|
||||||
|
redis_client.delete(key)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Errore clear_all_nodes Redis: {e}")
|
||||||
|
|
||||||
# --- DATABASE ID DMR / NXDN ---
|
# --- DATABASE ID DMR / NXDN ---
|
||||||
user_db = {}
|
user_db = {}
|
||||||
nxdn_db = {}
|
nxdn_db = {}
|
||||||
@@ -111,7 +257,7 @@ def load_ids():
|
|||||||
for l in f:
|
for l in f:
|
||||||
l = l.replace('"', '')
|
l = l.replace('"', '')
|
||||||
if ',' in l: p = l.strip().split(',')
|
if ',' in l: p = l.strip().split(',')
|
||||||
elif '\t' in l: p = l.strip().split('\t')
|
elif ' ' in l: p = l.strip().split(' ')
|
||||||
elif ';' in l: p = l.strip().split(';')
|
elif ';' in l: p = l.strip().split(';')
|
||||||
else: p = l.strip().split()
|
else: p = l.strip().split()
|
||||||
|
|
||||||
@@ -121,7 +267,7 @@ def load_ids():
|
|||||||
if os.path.exists(NXDN_IDS_PATH):
|
if os.path.exists(NXDN_IDS_PATH):
|
||||||
with open(NXDN_IDS_PATH, 'r', encoding='utf-8', errors='ignore') as f:
|
with open(NXDN_IDS_PATH, 'r', encoding='utf-8', errors='ignore') as f:
|
||||||
for l in f:
|
for l in f:
|
||||||
sep = '\t' if '\t' in l else (',' if ',' in l else ';')
|
sep = ' ' if ' ' in l else (',' if ',' in l else ';')
|
||||||
p = l.strip().split(sep)
|
p = l.strip().split(sep)
|
||||||
if len(p) >= 2 and p[0].strip().isdigit():
|
if len(p) >= 2 and p[0].strip().isdigit():
|
||||||
new_nxdn[p[0].strip()] = p[1].strip()
|
new_nxdn[p[0].strip()] = p[1].strip()
|
||||||
|
|||||||
+4
-4
@@ -36,7 +36,7 @@ Install project requirements:
|
|||||||
The server handles the web interface and user permissions.
|
The server handles the web interface and user permissions.
|
||||||
|
|
||||||
Steps:
|
Steps:
|
||||||
1. Configure 'config.json' using 'config.example.json'.
|
1. Configure 'config.json' using 'config.json.example'.
|
||||||
2. Enter MQTT credentials and VAPID keys.
|
2. Enter MQTT credentials and VAPID keys.
|
||||||
3. Define repeaters in the 'clients.json' file.
|
3. Define repeaters in the 'clients.json' file.
|
||||||
4. Install production WSGI server packages (if not in requirements):
|
4. Install production WSGI server packages (if not in requirements):
|
||||||
@@ -59,7 +59,7 @@ They will NOT work over standard HTTP.
|
|||||||
4. RUNNING AS A SERVICE (SYSTEMD)
|
4. RUNNING AS A SERVICE (SYSTEMD)
|
||||||
------------------------------------------------------------
|
------------------------------------------------------------
|
||||||
⚠️ IMPORTANT (VENV USERS): Before copying the service file,
|
⚠️ IMPORTANT (VENV USERS): Before copying the service file,
|
||||||
open 'fleet-control.service' and ensure the paths point to your
|
open 'fleet-console.service' and ensure the paths point to your
|
||||||
virtual environment.
|
virtual environment.
|
||||||
|
|
||||||
Example:
|
Example:
|
||||||
@@ -110,7 +110,7 @@ Installa i requisiti del progetto:
|
|||||||
2. SETUP DEL SERVER
|
2. SETUP DEL SERVER
|
||||||
------------------------------------------------------------
|
------------------------------------------------------------
|
||||||
Passaggi:
|
Passaggi:
|
||||||
1. Configura 'config.json' partendo da 'config.example.json'.
|
1. Configura 'config.json' partendo da 'config.json.example'.
|
||||||
2. Inserisci credenziali MQTT e chiavi VAPID.
|
2. Inserisci credenziali MQTT e chiavi VAPID.
|
||||||
3. Definisci i ripetitori in 'clients.json'.
|
3. Definisci i ripetitori in 'clients.json'.
|
||||||
4. Avvia il server di produzione:
|
4. Avvia il server di produzione:
|
||||||
@@ -128,7 +128,7 @@ Passaggi:
|
|||||||
4. ESECUZIONE COME SERVIZIO (SYSTEMD)
|
4. ESECUZIONE COME SERVIZIO (SYSTEMD)
|
||||||
------------------------------------------------------------
|
------------------------------------------------------------
|
||||||
⚠️ IMPORTANTE (PER UTENTI VENV): Prima di copiare il file di
|
⚠️ IMPORTANTE (PER UTENTI VENV): Prima di copiare il file di
|
||||||
servizio, apri 'fleet-control.service' e assicurati che i percorsi
|
servizio, apri 'fleet-console.service' e assicurati che i percorsi
|
||||||
puntino al tuo ambiente virtuale!
|
puntino al tuo ambiente virtuale!
|
||||||
|
|
||||||
Esempio:
|
Esempio:
|
||||||
|
|||||||
Executable
+41
@@ -0,0 +1,41 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
config_path = "config.json"
|
||||||
|
|
||||||
|
if not os.path.exists(config_path):
|
||||||
|
print(f"⚠️ {config_path} non trovato. Nessuna migrazione necessaria.")
|
||||||
|
sys.exit(0)
|
||||||
|
|
||||||
|
try:
|
||||||
|
with open(config_path, "r", encoding="utf-8") as f:
|
||||||
|
cfg = json.load(f)
|
||||||
|
except Exception as e:
|
||||||
|
print(f"❌ Errore nella lettura di {config_path}: {e}")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
if "web" not in cfg:
|
||||||
|
cfg["web"] = {}
|
||||||
|
|
||||||
|
if "redis_url" not in cfg["web"]:
|
||||||
|
print("🔧 Aggiunta della configurazione Redis a config.json...")
|
||||||
|
cfg["web"]["redis_url"] = "redis://localhost:6379/0"
|
||||||
|
|
||||||
|
bak_path = config_path + ".bak"
|
||||||
|
try:
|
||||||
|
with open(config_path, "r", encoding="utf-8") as rf:
|
||||||
|
with open(bak_path, "w", encoding="utf-8") as wf:
|
||||||
|
wf.write(rf.read())
|
||||||
|
print(f"💾 Backup creato in {bak_path}")
|
||||||
|
except Exception as e:
|
||||||
|
print(f"⚠️ Impossibile creare backup: {e}")
|
||||||
|
|
||||||
|
tmp_path = config_path + ".tmp"
|
||||||
|
with open(tmp_path, "w", encoding="utf-8") as f:
|
||||||
|
json.dump(cfg, f, indent=4)
|
||||||
|
os.replace(tmp_path, config_path)
|
||||||
|
print("✅ config.json aggiornato con successo!")
|
||||||
|
else:
|
||||||
|
print("ℹ️ config.json contiene già la configurazione Redis.")
|
||||||
+2
-8
@@ -1,8 +1,2 @@
|
|||||||
Flask
|
redis>=5.0.1
|
||||||
Flask-SocketIO
|
# ... (aggiungi qui le altre dipendenze preesistenti come Flask, paho-mqtt, ecc.)
|
||||||
Werkzeug
|
|
||||||
pywebpush
|
|
||||||
paho-mqtt
|
|
||||||
gunicorn
|
|
||||||
gevent
|
|
||||||
gevent-websocket
|
|
||||||
|
|||||||
+24
-4
@@ -14,6 +14,7 @@ import core.state as state
|
|||||||
from services.mqtt_service import mqtt_publish
|
from services.mqtt_service import mqtt_publish
|
||||||
from services.push_service import node_allowed
|
from services.push_service import node_allowed
|
||||||
from routes.auth_routes import get_auth, json_body, err
|
from routes.auth_routes import get_auth, json_body, err
|
||||||
|
from services.scheduler_service import PRIVILEGED_COMMANDS as SCHED_PRIVILEGED
|
||||||
|
|
||||||
# --- AGGIUNTE PER GITEA BACKGROUND CHECK ---
|
# --- AGGIUNTE PER GITEA BACKGROUND CHECK ---
|
||||||
GLOBAL_SERVER_UPDATE_AVAILABLE = False
|
GLOBAL_SERVER_UPDATE_AVAILABLE = False
|
||||||
@@ -254,7 +255,7 @@ def update_nodes():
|
|||||||
return err("Non autorizzato", 403)
|
return err("Non autorizzato", 403)
|
||||||
if not mqtt_publish("devices/control/request", "update"):
|
if not mqtt_publish("devices/control/request", "update"):
|
||||||
return err("Broker MQTT non raggiungibile", 503)
|
return err("Broker MQTT non raggiungibile", 503)
|
||||||
logger.info(f"討 REQ CONFIG inviata a tutta la flotta da {auth['username']}")
|
logger.info(f"🔄 REQ CONFIG inviata a tutta la flotta da {auth['username']}")
|
||||||
audit(auth['username'], '*', 'REQ_CONFIG_ALL')
|
audit(auth['username'], '*', 'REQ_CONFIG_ALL')
|
||||||
return jsonify({"success": True})
|
return jsonify({"success": True})
|
||||||
|
|
||||||
@@ -411,6 +412,8 @@ def apply_server_update():
|
|||||||
auth = get_auth()
|
auth = get_auth()
|
||||||
if not auth or auth['role'] != 'admin':
|
if not auth or auth['role'] != 'admin':
|
||||||
return err("Non autorizzato", 403)
|
return err("Non autorizzato", 403)
|
||||||
|
if read_config().get('web', {}).get('ota_enabled', True) is False:
|
||||||
|
return err("Aggiornamento OTA disabilitato dalla configurazione", 403)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
audit(auth['username'], 'SERVER', 'SERVER_OTA_UPDATE')
|
audit(auth['username'], 'SERVER', 'SERVER_OTA_UPDATE')
|
||||||
@@ -660,6 +663,22 @@ def add_schedule():
|
|||||||
if not start_time or not end_time:
|
if not start_time or not end_time:
|
||||||
return err("Date di inizio e fine obbligatorie")
|
return err("Date di inizio e fine obbligatorie")
|
||||||
|
|
||||||
|
# Validazione profili: stessa logica di /api/command (i comandi privilegiati solo per admin)
|
||||||
|
profiles_to_check = [target_profile] + ([restore_profile] if restore_profile != 'NONE' else [])
|
||||||
|
for prof in profiles_to_check:
|
||||||
|
if prof in SCHED_PRIVILEGED:
|
||||||
|
if auth['role'] != 'admin':
|
||||||
|
return err("Solo gli amministratori possono schedulare questo comando.", 403)
|
||||||
|
elif not (PROFILE_KEY_RE.match(prof) or prof in SIMPLE_COMMANDS):
|
||||||
|
return err("Profilo non valido")
|
||||||
|
|
||||||
|
# Validazione nodi target
|
||||||
|
if target_nodes != 'all':
|
||||||
|
node_list = [x.strip() for x in target_nodes.split(',') if x.strip()]
|
||||||
|
if not node_list or not all(CID_RE.match(x) for x in node_list):
|
||||||
|
return err("ID nodo non valido")
|
||||||
|
target_nodes = ','.join(node_list)
|
||||||
|
|
||||||
# Verifica permessi per node_admin
|
# Verifica permessi per node_admin
|
||||||
if auth['role'] == 'node_admin':
|
if auth['role'] == 'node_admin':
|
||||||
allowed = set(x.strip().lower() for x in auth['allowed_nodes'].split(','))
|
allowed = set(x.strip().lower() for x in auth['allowed_nodes'].split(','))
|
||||||
@@ -701,7 +720,7 @@ def cancel_schedule(sid):
|
|||||||
try:
|
try:
|
||||||
with closing(db_connect(row=True)) as conn:
|
with closing(db_connect(row=True)) as conn:
|
||||||
c = conn.cursor()
|
c = conn.cursor()
|
||||||
c.execute("SELECT id, title, target_nodes, status, restore_profile FROM profile_schedules WHERE id = ?", (sid,))
|
c.execute("SELECT id, title, target_nodes, status, restore_profile, created_by FROM profile_schedules WHERE id = ?", (sid,))
|
||||||
row = c.fetchone()
|
row = c.fetchone()
|
||||||
if not row:
|
if not row:
|
||||||
return err("Schedulazione non trovata", 404)
|
return err("Schedulazione non trovata", 404)
|
||||||
@@ -715,8 +734,9 @@ def cancel_schedule(sid):
|
|||||||
|
|
||||||
# Se era attiva, ripristina subito il profilo
|
# Se era attiva, ripristina subito il profilo
|
||||||
if row['status'] == 'ACTIVE' and row['restore_profile'] and row['restore_profile'] != 'NONE':
|
if row['status'] == 'ACTIVE' and row['restore_profile'] and row['restore_profile'] != 'NONE':
|
||||||
from services.scheduler_service import apply_scheduled_profile
|
from services.scheduler_service import apply_scheduled_profile, _is_admin
|
||||||
apply_scheduled_profile(row['target_nodes'], row['restore_profile'], "CANCEL_RESTORE")
|
apply_scheduled_profile(row['target_nodes'], row['restore_profile'], "CANCEL_RESTORE",
|
||||||
|
allow_privileged=_is_admin(conn, row['created_by']))
|
||||||
|
|
||||||
conn.execute("UPDATE profile_schedules SET status = 'CANCELLED' WHERE id = ?", (sid,))
|
conn.execute("UPDATE profile_schedules SET status = 'CANCELLED' WHERE id = ?", (sid,))
|
||||||
conn.commit()
|
conn.commit()
|
||||||
|
|||||||
+10
-1
@@ -57,11 +57,20 @@ LOGIN_WINDOW_SEC = 300
|
|||||||
login_attempts = {}
|
login_attempts = {}
|
||||||
login_lock = threading.Lock()
|
login_lock = threading.Lock()
|
||||||
|
|
||||||
|
LOOPBACK_ADDRS = ('127.0.0.1', '::1')
|
||||||
|
|
||||||
def client_ip():
|
def client_ip():
|
||||||
|
fwd = request.headers.get('X-Forwarded-For', '')
|
||||||
if config.get('web', {}).get('trust_proxy'):
|
if config.get('web', {}).get('trust_proxy'):
|
||||||
fwd = request.headers.get('X-Forwarded-For', '')
|
|
||||||
if fwd:
|
if fwd:
|
||||||
return fwd.split(',')[0].strip()
|
return fwd.split(',')[0].strip()
|
||||||
|
elif fwd and request.remote_addr in LOOPBACK_ADDRS:
|
||||||
|
# Connessione dal proxy locale: solo lui puo' avere remote_addr loopback, quindi
|
||||||
|
# fidarsi dell'ultimo valore (quello aggiunto dal proxy) e' sicuro e evita che
|
||||||
|
# tutti gli utenti condividano 127.0.0.1 (lockout globale del login).
|
||||||
|
last = fwd.split(',')[-1].strip()
|
||||||
|
if last:
|
||||||
|
return last
|
||||||
return request.remote_addr or 'unknown'
|
return request.remote_addr or 'unknown'
|
||||||
|
|
||||||
def login_blocked(ip):
|
def login_blocked(ip):
|
||||||
|
|||||||
@@ -71,7 +71,7 @@ def on_message(client, userdata, msg):
|
|||||||
state.node_logs[cid].append(log_entry)
|
state.node_logs[cid].append(log_entry)
|
||||||
|
|
||||||
# Inoltra in tempo reale via WebSocket
|
# Inoltra in tempo reale via WebSocket
|
||||||
state.socketio.emit(f"live_log_{cid}", log_entry)
|
state.emit_to_authorized(f"live_log_{cid}", log_entry, cid=cid)
|
||||||
|
|
||||||
# B) Parsa le versioni
|
# B) Parsa le versioni
|
||||||
if cid not in state.node_versions:
|
if cid not in state.node_versions:
|
||||||
@@ -134,7 +134,7 @@ def on_message(client, userdata, msg):
|
|||||||
|
|
||||||
state.aprs_msgs.append(aprs_data)
|
state.aprs_msgs.append(aprs_data)
|
||||||
logger.info(f"📍 APRS (da log {svc_name}): {src_part} -> {dest_part}")
|
logger.info(f"📍 APRS (da log {svc_name}): {src_part} -> {dest_part}")
|
||||||
state.socketio.emit('aprs_msg', aprs_data)
|
state.emit_aprs(aprs_data)
|
||||||
|
|
||||||
# NOTA: Rimosso il return incondizionato qui, perché il log deve completare la sua corsa
|
# NOTA: Rimosso il return incondizionato qui, perché il log deve completare la sua corsa
|
||||||
# e non bloccare eventuali altre logiche!
|
# e non bloccare eventuali altre logiche!
|
||||||
@@ -399,7 +399,7 @@ def on_message(client, userdata, msg):
|
|||||||
from collections import deque
|
from collections import deque
|
||||||
state.aprs_msgs = deque(maxlen=100)
|
state.aprs_msgs = deque(maxlen=100)
|
||||||
state.aprs_msgs.append(data)
|
state.aprs_msgs.append(data)
|
||||||
state.socketio.emit('aprs_msg', data)
|
state.emit_aprs(data)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Errore parsing APRS: {e}")
|
logger.error(f"Errore parsing APRS: {e}")
|
||||||
|
|
||||||
@@ -527,6 +527,16 @@ def on_message(client, userdata, msg):
|
|||||||
mqtt_id = config.get('mqtt', {}).get('client_id', 'flask_backend_generic')
|
mqtt_id = config.get('mqtt', {}).get('client_id', 'flask_backend_generic')
|
||||||
mqtt_backend = mqtt_client.Client(mqtt_client.CallbackAPIVersion.VERSION2, mqtt_id)
|
mqtt_backend = mqtt_client.Client(mqtt_client.CallbackAPIVersion.VERSION2, mqtt_id)
|
||||||
mqtt_backend.username_pw_set(config.get('mqtt', {}).get('user', ''), config.get('mqtt', {}).get('password', ''))
|
mqtt_backend.username_pw_set(config.get('mqtt', {}).get('user', ''), config.get('mqtt', {}).get('password', ''))
|
||||||
|
# TLS opzionale (default: disattivato, comportamento invariato). In config.json:
|
||||||
|
# "mqtt": { ..., "port": 8883, "tls": true, "ca_certs": "/etc/ssl/certs/ca-certificates.crt" }
|
||||||
|
if config.get('mqtt', {}).get('tls'):
|
||||||
|
import ssl
|
||||||
|
try:
|
||||||
|
mqtt_backend.tls_set(ca_certs=config.get('mqtt', {}).get('ca_certs') or None,
|
||||||
|
cert_reqs=ssl.CERT_REQUIRED)
|
||||||
|
logger.info("🔒 MQTT: TLS abilitato")
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"MQTT TLS non configurabile: {e}")
|
||||||
mqtt_backend.on_connect = on_connect
|
mqtt_backend.on_connect = on_connect
|
||||||
mqtt_backend.on_disconnect = on_disconnect
|
mqtt_backend.on_disconnect = on_disconnect
|
||||||
mqtt_backend.on_message = on_message
|
mqtt_backend.on_message = on_message
|
||||||
|
|||||||
@@ -4,17 +4,10 @@ from contextlib import closing
|
|||||||
from pywebpush import webpush, WebPushException
|
from pywebpush import webpush, WebPushException
|
||||||
from core.config import config, logger
|
from core.config import config, logger
|
||||||
from core.database import db_connect
|
from core.database import db_connect
|
||||||
|
from core.permissions import node_allowed # noqa: F401 (re-export per compatibilita')
|
||||||
|
|
||||||
push_queue = queue.Queue(maxsize=200)
|
push_queue = queue.Queue(maxsize=200)
|
||||||
|
|
||||||
def node_allowed(role, allowed_nodes, cid):
|
|
||||||
if role == 'admin':
|
|
||||||
return True
|
|
||||||
allowed = (allowed_nodes or '').strip().lower()
|
|
||||||
if allowed == 'all':
|
|
||||||
return True
|
|
||||||
return cid in [x.strip().lower() for x in allowed.split(',') if x.strip()]
|
|
||||||
|
|
||||||
def broadcast_push_notification(title, body, cid=None):
|
def broadcast_push_notification(title, body, cid=None):
|
||||||
if not config.get('webpush'):
|
if not config.get('webpush'):
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -45,17 +45,33 @@ def auto_update_ids():
|
|||||||
download_logic()
|
download_logic()
|
||||||
prune_old_data()
|
prune_old_data()
|
||||||
time.sleep(65)
|
time.sleep(65)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"⚠️ Errore nel thread aggiornamento ID: {e}")
|
||||||
|
time.sleep(15)
|
||||||
|
|
||||||
# Controllo schedulazioni profili
|
def schedule_loop():
|
||||||
|
"""Thread dedicato alle schedulazioni: non e' piu' bloccato dai download degli ID."""
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
check_profile_schedules()
|
check_profile_schedules()
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"⚠️ Errore nel thread scheduler: {e}")
|
logger.error(f"⚠️ Errore nel thread schedulazioni: {e}")
|
||||||
time.sleep(15)
|
time.sleep(15)
|
||||||
|
|
||||||
from contextlib import closing
|
from contextlib import closing
|
||||||
from core.database import db_connect, audit
|
from core.database import db_connect, audit
|
||||||
|
|
||||||
def apply_scheduled_profile(target_nodes, profile, action_type="SWITCH"):
|
# Comandi che le API riservano agli admin: una schedulazione li puo' inviare solo se creata da un admin.
|
||||||
|
PRIVILEGED_COMMANDS = {'REBOOT', 'RESET_HAT', 'UPDATE_AGENT'}
|
||||||
|
|
||||||
|
def _is_admin(conn, username):
|
||||||
|
row = conn.execute("SELECT role FROM users WHERE username = ?", (username,)).fetchone()
|
||||||
|
return bool(row) and row[0] == 'admin'
|
||||||
|
|
||||||
|
def apply_scheduled_profile(target_nodes, profile, action_type="SWITCH", allow_privileged=False):
|
||||||
|
if str(profile).strip().upper() in PRIVILEGED_COMMANDS and not allow_privileged:
|
||||||
|
logger.warning(f"🚫 Scheduler: comando privilegiato '{profile}' ignorato (schedulazione non creata da un admin)")
|
||||||
|
return
|
||||||
from services.mqtt_service import mqtt_publish
|
from services.mqtt_service import mqtt_publish
|
||||||
from core.config import CLIENTS_PATH
|
from core.config import CLIENTS_PATH
|
||||||
import json
|
import json
|
||||||
@@ -111,7 +127,7 @@ def check_profile_schedules():
|
|||||||
if status == 'SCHEDULED':
|
if status == 'SCHEDULED':
|
||||||
if st_norm <= now_str < end_norm:
|
if st_norm <= now_str < end_norm:
|
||||||
logger.info(f"▶️ Avvio schedulazione ID {sid} - '{title}' -> Profilo {target_prof}")
|
logger.info(f"▶️ Avvio schedulazione ID {sid} - '{title}' -> Profilo {target_prof}")
|
||||||
apply_scheduled_profile(nodes, target_prof, "START")
|
apply_scheduled_profile(nodes, target_prof, "START", allow_privileged=_is_admin(conn, row['created_by']))
|
||||||
conn.execute("UPDATE profile_schedules SET status = 'ACTIVE' WHERE id = ?", (sid,))
|
conn.execute("UPDATE profile_schedules SET status = 'ACTIVE' WHERE id = ?", (sid,))
|
||||||
conn.commit()
|
conn.commit()
|
||||||
audit("SCHEDULER", nodes, f"START_SCHED_{sid}_{target_prof}")
|
audit("SCHEDULER", nodes, f"START_SCHED_{sid}_{target_prof}")
|
||||||
@@ -125,7 +141,7 @@ def check_profile_schedules():
|
|||||||
if now_str >= end_norm:
|
if now_str >= end_norm:
|
||||||
logger.info(f"⏹️ Fine schedulazione ID {sid} - '{title}' -> Ripristino {restore_prof}")
|
logger.info(f"⏹️ Fine schedulazione ID {sid} - '{title}' -> Ripristino {restore_prof}")
|
||||||
if restore_prof and restore_prof.upper() != 'NONE':
|
if restore_prof and restore_prof.upper() != 'NONE':
|
||||||
apply_scheduled_profile(nodes, restore_prof, "RESTORE")
|
apply_scheduled_profile(nodes, restore_prof, "RESTORE", allow_privileged=_is_admin(conn, row['created_by']))
|
||||||
conn.execute("UPDATE profile_schedules SET status = 'COMPLETED' WHERE id = ?", (sid,))
|
conn.execute("UPDATE profile_schedules SET status = 'COMPLETED' WHERE id = ?", (sid,))
|
||||||
conn.commit()
|
conn.commit()
|
||||||
audit("SCHEDULER", nodes, f"RESTORE_SCHED_{sid}_{restore_prof}")
|
audit("SCHEDULER", nodes, f"RESTORE_SCHED_{sid}_{restore_prof}")
|
||||||
|
|||||||
@@ -1,88 +1,46 @@
|
|||||||
import time
|
import time
|
||||||
import sqlite3
|
import json
|
||||||
from contextlib import closing
|
import logging
|
||||||
from core.config import DB_PATH, logger
|
from core.state import get_all_nodes, update_node_state, delete_node, last_seen as global_last_seen
|
||||||
import core.state as state
|
from core.database import archive_node_error
|
||||||
from services.push_service import broadcast_push_notification
|
|
||||||
|
|
||||||
watchdog_notified = {}
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
def run_diagnostics():
|
|
||||||
new_warnings = {}
|
|
||||||
|
|
||||||
# 1. Analisi Hardware (Temperatura e Spazio Disco)
|
|
||||||
for cid, health in list(state.device_health.items()):
|
|
||||||
node_warns = []
|
|
||||||
state_up = str(state.client_states.get(cid, '')).upper()
|
|
||||||
if 'OFF' in state_up or state_up == '':
|
|
||||||
continue
|
|
||||||
|
|
||||||
temp = health.get('temp', 0)
|
|
||||||
disk = health.get('disk', 0)
|
|
||||||
|
|
||||||
# Allarme Temperatura CPU (Soglia 75°C, rientro 68°C)
|
|
||||||
key_temp = f"{cid}_TEMP"
|
|
||||||
if temp >= 75.0:
|
|
||||||
node_warns.append(f"🌡️ Alta Temperatura ({temp}°C)")
|
|
||||||
if not watchdog_notified.get(key_temp):
|
|
||||||
broadcast_push_notification(f"🌡️ ALLARME TERMICO: {cid.upper()}", f"CPU surriscaldata a {temp}°C! Verificare ventilazione.", cid=cid)
|
|
||||||
watchdog_notified[key_temp] = True
|
|
||||||
elif temp < 68.0 and watchdog_notified.get(key_temp):
|
|
||||||
broadcast_push_notification(f"✅ TEMPERATURA OK: {cid.upper()}", f"Temperatura CPU rientrata a {temp}°C.", cid=cid)
|
|
||||||
del watchdog_notified[key_temp]
|
|
||||||
|
|
||||||
# Allarme Spazio Disco (Soglia 90%, rientro 85%)
|
|
||||||
key_disk = f"{cid}_DISK"
|
|
||||||
if disk >= 90.0:
|
|
||||||
node_warns.append(f"💾 Spazio Disco Quasi Pieno ({disk}%)")
|
|
||||||
if not watchdog_notified.get(key_disk):
|
|
||||||
broadcast_push_notification(f"💾 DISCO CRITICO: {cid.upper()}", f"Utilizzo disco al {disk}%. Rischio blocco log MMDVM.", cid=cid)
|
|
||||||
watchdog_notified[key_disk] = True
|
|
||||||
elif disk < 85.0 and watchdog_notified.get(key_disk):
|
|
||||||
del watchdog_notified[key_disk]
|
|
||||||
|
|
||||||
if node_warns:
|
|
||||||
new_warnings.setdefault(cid, []).extend(node_warns)
|
|
||||||
|
|
||||||
# 2. Analisi Radio RF (Media BER sulle ultime 2 ore, solo transiti RF locali)
|
|
||||||
try:
|
|
||||||
with closing(sqlite3.connect(DB_PATH, timeout=10)) as conn:
|
|
||||||
cur = conn.cursor()
|
|
||||||
cur.execute("""
|
|
||||||
SELECT LOWER(client_id), AVG(ber), COUNT(*)
|
|
||||||
FROM radio_logs
|
|
||||||
WHERE timestamp >= datetime('now', 'localtime', '-5 minutes')
|
|
||||||
AND source_id NOT LIKE '🌐%'
|
|
||||||
AND (source_conn IS NULL OR LOWER(source_conn) != 'network')
|
|
||||||
GROUP BY LOWER(client_id)
|
|
||||||
""")
|
|
||||||
rows = cur.fetchall()
|
|
||||||
|
|
||||||
for cid, avg_ber, cnt in rows:
|
|
||||||
key_ber = f"{cid}_BER"
|
|
||||||
if cnt >= 2 and avg_ber is not None and avg_ber >= 5.0:
|
|
||||||
new_warnings.setdefault(cid, []).append(f"⚠️ Alto BER RF ({avg_ber:.1f}%)")
|
|
||||||
if not watchdog_notified.get(key_ber):
|
|
||||||
broadcast_push_notification(f"⚠️ ANOMALIA RF: {cid.upper()}", f"Rilevato BER medio del {avg_ber:.1f}% negli ultimi {cnt} passaggi RF.", cid=cid)
|
|
||||||
watchdog_notified[key_ber] = True
|
|
||||||
elif avg_ber is not None and avg_ber < 3.0:
|
|
||||||
if watchdog_notified.get(key_ber):
|
|
||||||
del watchdog_notified[key_ber]
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"Errore diagnostica BER Watchdog: {e}")
|
|
||||||
|
|
||||||
# Aggiorna il dizionario globale condiviso preservando i riferimenti in memoria
|
|
||||||
changed = new_warnings != state.active_warnings
|
|
||||||
state.active_warnings.clear()
|
|
||||||
state.active_warnings.update(new_warnings)
|
|
||||||
if changed:
|
|
||||||
state.notify_update()
|
|
||||||
|
|
||||||
def watchdog_loop():
|
def watchdog_loop():
|
||||||
time.sleep(15) # Attesa iniziale all'avvio
|
logger.info("Watchdog service started.")
|
||||||
while True:
|
while True:
|
||||||
try:
|
try:
|
||||||
run_diagnostics()
|
now = time.time()
|
||||||
|
nodes = get_all_nodes()
|
||||||
|
|
||||||
|
for node_id, state in nodes.items():
|
||||||
|
# 1. Normalizza lo stato se è una stringa (es. "ONLINE" o JSON serializzato)
|
||||||
|
if isinstance(state, str):
|
||||||
|
try:
|
||||||
|
state = json.loads(state)
|
||||||
|
except Exception:
|
||||||
|
state = {"status": state}
|
||||||
|
elif not isinstance(state, dict):
|
||||||
|
continue
|
||||||
|
|
||||||
|
# 2. Recupera last_seen (dal dict, dalla mappa globale di state.py o now)
|
||||||
|
node_seen = global_last_seen.get(node_id, {})
|
||||||
|
last_seen_ts = max(node_seen.values()) if node_seen else now
|
||||||
|
last_seen = float(state.get("last_seen") or last_seen_ts)
|
||||||
|
status = state.get("status", "UNKNOWN")
|
||||||
|
|
||||||
|
# 3. Rilevamento disconnessione (nessun heartbeat per 60 secondi)
|
||||||
|
if now - last_seen > 60 and status not in ["OFFLINE", "ERROR"]:
|
||||||
|
update_node_state(node_id, {"status": "OFFLINE"})
|
||||||
|
logger.warning(f"Nodo {node_id} marcato come OFFLINE (timeout heartbeat)")
|
||||||
|
|
||||||
|
# 4. Archiviazione errori critici (in errore per più di 5 minuti)
|
||||||
|
if status == "ERROR" and (now - last_seen > 300):
|
||||||
|
archive_node_error(node_id, state)
|
||||||
|
delete_node(node_id)
|
||||||
|
logger.error(f"Nodo {node_id} rimosso da Redis e archiviato su DB per errore prolungato.")
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Errore nel loop del Watchdog: {e}")
|
logger.error(f"Errore nel ciclo di watchdog: {e}")
|
||||||
time.sleep(60)
|
|
||||||
|
time.sleep(10)
|
||||||
|
|||||||
@@ -0,0 +1,37 @@
|
|||||||
|
# VERSIONE PIU' SICURA (opzionale) del servizio. Il file fleet-console.service originale resta invariato.
|
||||||
|
#
|
||||||
|
# Preparazione (una tantum, da root):
|
||||||
|
# useradd --system --home /opt/fleet-control-server --shell /usr/sbin/nologin fleet
|
||||||
|
# chown -R fleet:fleet /opt/fleet-control-server
|
||||||
|
# cp systemd/fleet-console.hardened.service.example /etc/systemd/system/fleet-console.service
|
||||||
|
# systemctl daemon-reload && systemctl restart fleet-console
|
||||||
|
#
|
||||||
|
# Se usi un reverse proxy (consigliato) cambia anche il bind in 127.0.0.1:9000 qui sotto.
|
||||||
|
# L'aggiornamento OTA (git pull) continua a funzionare perche' l'utente "fleet" possiede la cartella.
|
||||||
|
[Unit]
|
||||||
|
Description=Fleet Control Console - Central Hub
|
||||||
|
After=network.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
User=fleet
|
||||||
|
Group=fleet
|
||||||
|
WorkingDirectory=/opt/fleet-control-server
|
||||||
|
ExecStart=/opt/fleet-control-server/venv/bin/gunicorn -k "geventwebsocket.gunicorn.workers.GeventWebSocketWorker" -w 1 --graceful-timeout 2 --bind 0.0.0.0:9000 app:app
|
||||||
|
TimeoutStopSec=3
|
||||||
|
Restart=always
|
||||||
|
RestartSec=5
|
||||||
|
|
||||||
|
# Hardening
|
||||||
|
NoNewPrivileges=true
|
||||||
|
PrivateTmp=true
|
||||||
|
ProtectSystem=full
|
||||||
|
ProtectHome=true
|
||||||
|
ReadWritePaths=/opt/fleet-control-server
|
||||||
|
|
||||||
|
StandardOutput=syslog
|
||||||
|
StandardError=syslog
|
||||||
|
SyslogIdentifier=fleet-console
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
@@ -620,7 +620,7 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- LIBRERIE ESTERNE -->
|
<!-- LIBRERIE ESTERNE -->
|
||||||
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
|
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.js"></script>
|
||||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/diff_match_patch/20121119/diff_match_patch.js"></script>
|
<script src="https://cdnjs.cloudflare.com/ajax/libs/diff_match_patch/20121119/diff_match_patch.js"></script>
|
||||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.7.2/socket.io.min.js"></script>
|
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.7.2/socket.io.min.js"></script>
|
||||||
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
|
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
|
||||||
|
|||||||
@@ -1,11 +0,0 @@
|
|||||||
import sqlite3
|
|
||||||
import json
|
|
||||||
from app import broadcast_push_notification, init_db
|
|
||||||
|
|
||||||
# Proviamo a inviare una notifica a tutti gli iscritti nel DB
|
|
||||||
print("🚀 Starting notification test...")
|
|
||||||
broadcast_push_notification(
|
|
||||||
"⚠️ ALLERTA FLOTTA",
|
|
||||||
"Test Push Notification: System Online!"
|
|
||||||
)
|
|
||||||
print("✅ Command sent.")
|
|
||||||
Executable
+114
@@ -0,0 +1,114 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -e
|
||||||
|
|
||||||
|
# Forza l'esecuzione nella cartella in cui risiede lo script
|
||||||
|
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||||
|
cd "$SCRIPT_DIR"
|
||||||
|
|
||||||
|
echo "============================================================"
|
||||||
|
echo " Fleet Control Server - Aggiornamento & Migrazione v7.0.0"
|
||||||
|
echo "============================================================"
|
||||||
|
|
||||||
|
# 1. Installazione del pacchetto di sistema Redis
|
||||||
|
if ! command -v redis-server &> /dev/null; then
|
||||||
|
echo "📦 Installazione del demone Redis via APT..."
|
||||||
|
sudo apt update
|
||||||
|
sudo apt install -y redis-server
|
||||||
|
else
|
||||||
|
echo "✅ redis-server già installato."
|
||||||
|
fi
|
||||||
|
|
||||||
|
# 2. Configurazione di /etc/redis/redis.conf (Persistenza AOF)
|
||||||
|
REDIS_CONF="/etc/redis/redis.conf"
|
||||||
|
if [ -f "$REDIS_CONF" ]; then
|
||||||
|
echo "⚙️ Configurazione persistenza in $REDIS_CONF..."
|
||||||
|
# Imposta appendonly yes
|
||||||
|
if grep -q "^#* *appendonly" "$REDIS_CONF"; then
|
||||||
|
sudo sed -i 's/^#* *appendonly .*/appendonly yes/' "$REDIS_CONF"
|
||||||
|
else
|
||||||
|
echo "appendonly yes" | sudo tee -a "$REDIS_CONF" > /dev/null
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Imposta appendfsync everysec
|
||||||
|
if grep -q "^#* *appendfsync" "$REDIS_CONF"; then
|
||||||
|
sudo sed -i 's/^#* *appendfsync .*/appendfsync everysec/' "$REDIS_CONF"
|
||||||
|
else
|
||||||
|
echo "appendfsync everysec" | sudo tee -a "$REDIS_CONF" > /dev/null
|
||||||
|
fi
|
||||||
|
echo "✅ redis.conf aggiornato con 'appendonly yes'."
|
||||||
|
fi
|
||||||
|
|
||||||
|
# 3. Riavvio e verifica del servizio Redis
|
||||||
|
echo "🚀 Riavvio del servizio Redis..."
|
||||||
|
sudo systemctl enable redis-server
|
||||||
|
sudo systemctl restart redis-server
|
||||||
|
|
||||||
|
if redis-cli ping | grep -q "PONG"; then
|
||||||
|
echo "✅ Redis è attivo e risponde correttamente (PONG)."
|
||||||
|
else
|
||||||
|
echo "❌ Errore: Redis non risponde sulla porta 6379."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# 4. Aggiornamento dipendenze Python nel virtualenv
|
||||||
|
if [ -d "venv" ]; then
|
||||||
|
echo "🐍 Aggiornamento dipendenze nel venv (inclusa libreria redis)..."
|
||||||
|
venv/bin/pip install --upgrade pip
|
||||||
|
venv/bin/pip install -r requirements.txt
|
||||||
|
else
|
||||||
|
echo "⚠️ Cartella venv non trovata. Esegui 'pip install -r requirements.txt' nel tuo ambiente."
|
||||||
|
fi
|
||||||
|
|
||||||
|
# 5. Migrazione automatica di config.json (eseguita inline da Python)
|
||||||
|
echo "⚙️ Controllo e allineamento di config.json..."
|
||||||
|
PYTHON_BIN="python3"
|
||||||
|
[ -f "venv/bin/python3" ] && PYTHON_BIN="venv/bin/python3"
|
||||||
|
|
||||||
|
$PYTHON_BIN - << 'EOF'
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
config_path = "config.json"
|
||||||
|
|
||||||
|
if not os.path.exists(config_path):
|
||||||
|
print(f"⚠️ {config_path} non trovato. Nulla da migrare.")
|
||||||
|
sys.exit(0)
|
||||||
|
|
||||||
|
try:
|
||||||
|
with open(config_path, "r", encoding="utf-8") as f:
|
||||||
|
cfg = json.load(f)
|
||||||
|
except Exception as e:
|
||||||
|
print(f"❌ Errore nella lettura di {config_path}: {e}")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
if "web" not in cfg:
|
||||||
|
cfg["web"] = {}
|
||||||
|
|
||||||
|
if "redis_url" not in cfg["web"]:
|
||||||
|
print("🔧 Aggiunta della direttiva 'redis_url' in config.json...")
|
||||||
|
cfg["web"]["redis_url"] = "redis://localhost:6379/0"
|
||||||
|
|
||||||
|
# Backup di sicurezza preventivo
|
||||||
|
bak_path = config_path + ".bak"
|
||||||
|
try:
|
||||||
|
with open(config_path, "r", encoding="utf-8") as rf:
|
||||||
|
with open(bak_path, "w", encoding="utf-8") as wf:
|
||||||
|
wf.write(rf.read())
|
||||||
|
print(f"💾 Backup salvato in {bak_path}")
|
||||||
|
except Exception as e:
|
||||||
|
print(f"⚠️ Impossibile salvare backup: {e}")
|
||||||
|
|
||||||
|
# Scrittura atomica per evitare file vuoti o corrotti
|
||||||
|
tmp_path = config_path + ".tmp"
|
||||||
|
with open(tmp_path, "w", encoding="utf-8") as f:
|
||||||
|
json.dump(cfg, f, indent=4)
|
||||||
|
os.replace(tmp_path, config_path)
|
||||||
|
print("✅ config.json aggiornato con successo.")
|
||||||
|
else:
|
||||||
|
print("ℹ️ config.json contiene già la configurazione Redis.")
|
||||||
|
EOF
|
||||||
|
|
||||||
|
echo ""
|
||||||
|
echo "🎉 Aggiornamento completato con successo!"
|
||||||
|
echo "Puoi avviare o riavviare il servizio: sudo systemctl restart fleet-control"
|
||||||
Reference in New Issue
Block a user