15 Commits
Author SHA1 Message Date
Gilles Soulier e65770407c chore(agent): bump version 0.1.2 → 0.1.3 2026-05-22 22:35:05 +02:00
Gilles SoulierandClaude Sonnet 4.6 9e77d961f5 feat(agent): déconnexion propre sur SIGTERM/SIGINT
- Capture SIGTERM et SIGINT via libc::signal → AtomicBool RUNNING
- La boucle principale s'arrête proprement à la prochaine itération
- Envoi d'un paquet status:offline via UDP avant de quitter
- MQTT : publish status offline + disconnect() pour déconnexion gracieuse
  (le last_will reste actif pour les déconnexions brutales)
- payload.rs: #[serde(default)] sur version pour compatibilité descendante

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-22 22:34:55 +02:00
Gilles SoulierandClaude Sonnet 4.6 3933301cff fix(db): GetLastMetrics retourne la dernière valeur non-nulle par colonne
La requête précédente prenait la dernière ligne (paquet rapide, 2s) qui
a hdd_*/smart_* à NULL. Chaque sous-requête cible maintenant la dernière
valeur non-nulle indépendamment, ce qui restitue les données disque/smart
au rechargement même si le dernier paquet ne les contenait pas.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-22 22:29:06 +02:00
Gilles SoulierandClaude Sonnet 4.6 9f87c9294d revert(docker): retour au multi-stage, docker login requis pour le pull
Dockerfile multi-stage (golang:1.22-alpine → scratch) pour un build
autonome. docker-compose sans version obsolète, pull:false pour le
builder, pull_policy:if_not_present pour nginx.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-22 22:12:56 +02:00
Gilles SoulierandClaude Sonnet 4.6 638d347bb0 fix(docker): évite les pulls Docker Hub inutiles (rate limit 429)
- Retire l'attribut version obsolète
- build.pull: false — BuildKit ne vérifie plus le manifest pour golang:1.22-alpine
- pull_policy: if_not_present — nginx:alpine n'est tiré que si absent du cache

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-22 22:06:41 +02:00
Gilles Soulier 8f3dbd0532 3 2026-05-22 22:06:12 +02:00
Gilles SoulierandClaude Sonnet 4.6 99bdf79a63 fix(docker): remplace alpine:3.19 par scratch pour éviter le rate limit
Le binaire est statique (CGO_ENABLED=0) — scratch suffit. Seuls les
certificats TLS sont copiés depuis le builder golang:1.22-alpine.
Élimine le pull de docker.io/library/alpine qui déclenche le 429.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-22 22:03:51 +02:00
Gilles SoulierandClaude Sonnet 4.6 a22d1f4cd2 fix(tile): icône personnalisée masque le fallback FA au chargement
Le span de fallback (fa-server) démarrait en display:flex — visible en
permanence derrière l'image. Il passe à display:none et n'est affiché
que si l'img déclenche onerror (pas d'icône).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-22 22:02:11 +02:00
Gilles SoulierandClaude Sonnet 4.6 d8f395cb53 feat(dashboard): métriques chargées immédiatement au rechargement de page
GET /api/agents inclut désormais last_metrics (dernière ligne de la table
metrics) pour chaque agent. grid.js l'utilise lors du refresh initial, ce
qui peuple les tuiles sans attendre le prochain message WebSocket.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-22 22:00:33 +02:00
Gilles SoulierandClaude Sonnet 4.6 f69c22039b fix(icon): upload d'icône — retour d'erreur, WEBP, limite Nginx
- nginx: client_max_body_size 10m (limite par défaut 1 Mo bloquait les images)
- icons.go: import _ golang.org/x/image/webp et image/gif pour décoder WEBP/GIF
- index.html: retire SVG de l'accept (serveur le rejette) et corrige le hint
- popups.js: try/catch autour de uploadIcon → message d'erreur visible dans le hint
  pendant 4s si l'upload échoue ; reset du file input pour re-sélectionner le même
  fichier ; rafraîchit l'img de la tuile avec cache-busting après succès

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-22 21:58:46 +02:00
Gilles SoulierandClaude Sonnet 4.6 2bda420728 feat(dashboard): affichage disque en Go utilisé/total comme la RAM
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-22 21:51:17 +02:00
Gilles SoulierandClaude Sonnet 4.6 f604e22f6e fix(deploy): permissions config et prompt d'écrasement au réinstall
- ConfigurationDirectoryMode 0750→0755 : le DynamicUser (sans groupe root)
  peut maintenant traverser /etc/nanometrics et lire config.toml
- chmod 644 systématique sur config.toml même si conservé (corrige les
  anciennes installs en 640 qui causent un PermissionDenied au démarrage)
- Prompt interactif si config existe : o=écraser, N=conserver ; variable
  OVERWRITE_CONFIG=true pour forcer sans interaction (curl|bash)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-22 21:49:13 +02:00
Gilles SoulierandClaude Sonnet 4.6 8d4dc0e853 fix(deploy): arrêt du service avant remplacement du binaire
Évite l'erreur "Fichier texte occupé" lors d'une mise à jour à chaud.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-22 20:32:17 +02:00
Gilles Soulier 311bdbc66d chore: version agent 0.1.2 2026-05-22 20:28:30 +02:00
Gilles SoulierandClaude Sonnet 4.6 0df716b8b0 feat: version agent remontée au serveur et affichée dans la popup
- payload.rs : champ version (env!("CARGO_PKG_VERSION"))
- models.go  : Version dans AgentMetrics et Agent
- db.go      : colonne version dans agents + migration ALTER TABLE
- popups.js  : badge version dans la section INFORMATIONS

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-22 20:27:26 +02:00
24 changed files with 211 additions and 32 deletions
+1 -1
View File
@@ -248,7 +248,7 @@ dependencies = [
[[package]] [[package]]
name = "nanometrics-agent" name = "nanometrics-agent"
version = "0.1.0" version = "0.1.2"
dependencies = [ dependencies = [
"libc", "libc",
"rumqttc", "rumqttc",
+1 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "nanometrics-agent" name = "nanometrics-agent"
version = "0.1.0" version = "0.1.3"
edition = "2021" edition = "2021"
[lib] [lib]
+34 -1
View File
@@ -2,6 +2,13 @@ use nanometrics_agent::{config, metrics, payload, transport};
use sysinfo::{Components, Networks, System}; use sysinfo::{Components, Networks, System};
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
use std::sync::mpsc; use std::sync::mpsc;
use std::sync::atomic::{AtomicBool, Ordering};
static RUNNING: AtomicBool = AtomicBool::new(true);
extern "C" fn handle_signal(_: libc::c_int) {
RUNNING.store(false, Ordering::Relaxed);
}
fn get_local_ip() -> String { fn get_local_ip() -> String {
use std::net::UdpSocket; use std::net::UdpSocket;
@@ -49,12 +56,17 @@ fn main() {
None None
}; };
unsafe {
libc::signal(libc::SIGTERM, handle_signal as libc::sighandler_t);
libc::signal(libc::SIGINT, handle_signal as libc::sighandler_t);
}
let mut last_slow = Instant::now(); let mut last_slow = Instant::now();
let mut last_medium = Instant::now(); let mut last_medium = Instant::now();
let mut first_medium = true; let mut first_medium = true;
let mut first_slow = true; let mut first_slow = true;
loop { while RUNNING.load(Ordering::Relaxed) {
let now = Instant::now(); let now = Instant::now();
while let Ok(transport::mqtt::MqttIncoming::ConfigUpdate(data)) = incoming_rx.try_recv() { while let Ok(transport::mqtt::MqttIncoming::ConfigUpdate(data)) = incoming_rx.try_recv() {
@@ -68,6 +80,7 @@ fn main() {
hostname: hostname.clone(), hostname: hostname.clone(),
ip: ip.clone(), ip: ip.clone(),
status: "online".to_string(), status: "online".to_string(),
version: env!("CARGO_PKG_VERSION").to_string(),
..Default::default() ..Default::default()
}; };
@@ -133,4 +146,24 @@ fn main() {
std::thread::sleep(Duration::from_secs(2)); std::thread::sleep(Duration::from_secs(2));
} }
// Déconnexion propre : notifier le serveur avant de quitter
let offline = serde_json::to_string(&payload::AgentMetrics {
hostname: hostname.clone(),
ip: ip.clone(),
status: "offline".to_string(),
version: env!("CARGO_PKG_VERSION").to_string(),
..Default::default()
}).unwrap_or_default();
if let Some(ref udp) = udp_sender {
udp.send(&offline);
}
if let Some(ref client) = mqtt_client {
transport::mqtt::publish_status(
client, &cfg.protocols.mqtt.topic_base, &hostname, "offline",
);
std::thread::sleep(Duration::from_millis(200)); // laisser le temps au broker de recevoir
let _ = client.disconnect();
}
} }
+2
View File
@@ -5,6 +5,8 @@ pub struct AgentMetrics {
pub hostname: String, pub hostname: String,
pub ip: String, pub ip: String,
pub status: String, pub status: String,
#[serde(default)]
pub version: String,
pub cpu_percent: Option<f32>, pub cpu_percent: Option<f32>,
pub memory_used: Option<u64>, pub memory_used: Option<u64>,
pub memory_free: Option<u64>, pub memory_free: Option<u64>,
+5
View File
@@ -78,3 +78,8 @@ pub fn publish_metrics(client: &Client, topic_base: &str, hostname: &str, json:
let topic = format!("{}/{}/metrics", topic_base, hostname); let topic = format!("{}/{}/metrics", topic_base, hostname);
let _ = client.publish(topic, QoS::AtMostOnce, false, json); let _ = client.publish(topic, QoS::AtMostOnce, false, json);
} }
pub fn publish_status(client: &Client, topic_base: &str, hostname: &str, status: &str) {
let topic = format!("{}/{}/status", topic_base, hostname);
let _ = client.publish(topic, QoS::AtLeastOnce, true, status);
}
+1
View File
@@ -18,6 +18,7 @@ fn test_serialize_json_complet() {
temperature: None, temperature: None,
smart: None, smart: None,
status: "online".to_string(), status: "online".to_string(),
version: "0.0.0".to_string(),
}; };
let json = serde_json::to_string(&m).unwrap(); let json = serde_json::to_string(&m).unwrap();
assert!(json.contains("\"hostname\":\"srv-01\"")); assert!(json.contains("\"hostname\":\"srv-01\""));
Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

+3 -3
View File
@@ -73,12 +73,12 @@
<img id="pop-icon-img" src="" alt="" style="display:none"> <img id="pop-icon-img" src="" alt="" style="display:none">
<div class="agent-icon-overlay"><i class="fa-solid fa-camera"></i><span>Changer</span></div> <div class="agent-icon-overlay"><i class="fa-solid fa-camera"></i><span>Changer</span></div>
</div> </div>
<input type="file" id="icon-upload" accept=".svg,.jpg,.jpeg,.png,.webp" style="display:none"> <input type="file" id="icon-upload" accept=".jpg,.jpeg,.png,.webp" style="display:none">
<div style="flex:1"> <div style="flex:1">
<div class="pop-host" id="pop-host"></div> <div class="pop-host" id="pop-host"></div>
<div class="pop-ip" id="pop-ip"></div> <div class="pop-ip" id="pop-ip"></div>
<div style="font-size:10px;color:var(--ink-4);font-family:var(--font-terminal);margin-top:2px"> <div id="icon-hint" style="font-size:10px;color:var(--ink-4);font-family:var(--font-terminal);margin-top:2px">
Cliquer sur l'icône pour personnaliser · SVG JPG PNG WEBP · max 128×128 px Cliquer sur l'icône pour personnaliser · JPG PNG WEBP · max 128×128 px
</div> </div>
</div> </div>
<div class="pop-led" id="pop-led"></div> <div class="pop-led" id="pop-led"></div>
+3 -3
View File
@@ -58,7 +58,7 @@ const Grid = (() => {
const iconContent = `<img src="${API.iconUrl(id)}" alt="" const iconContent = `<img src="${API.iconUrl(id)}" alt=""
style="width:100%;height:100%;object-fit:cover;border-radius:7px" style="width:100%;height:100%;object-fit:cover;border-radius:7px"
onerror="this.style.display='none';this.nextSibling.style.display='flex'"> onerror="this.style.display='none';this.nextSibling.style.display='flex'">
<span style="display:flex;align-items:center;justify-content:center;width:100%;height:100%;color:var(--accent)"> <span style="display:none;align-items:center;justify-content:center;width:100%;height:100%;color:var(--accent)">
<i class="fa-solid fa-server"></i></span>`; <i class="fa-solid fa-server"></i></span>`;
return `<div class="tile ${sc}" id="tile-${id}" onclick="Popups.showDetail('${esc(id)}')"> return `<div class="tile ${sc}" id="tile-${id}" onclick="Popups.showDetail('${esc(id)}')">
@@ -87,7 +87,7 @@ const Grid = (() => {
<div class="g-ico" data-tip="Disque"><i class="fa-solid fa-hard-drive"></i></div> <div class="g-ico" data-tip="Disque"><i class="fa-solid fa-hard-drive"></i></div>
<div class="g-bar"><div class="g-fill ${offline ? '' : (diskPct >= (App.serverConfig?.warn_disk ?? 75) ? 'w' : '')}" <div class="g-bar"><div class="g-fill ${offline ? '' : (diskPct >= (App.serverConfig?.warn_disk ?? 75) ? 'w' : '')}"
style="width:${offline ? 0 : (diskPct ?? 0).toFixed(0)}%"></div></div> style="width:${offline ? 0 : (diskPct ?? 0).toFixed(0)}%"></div></div>
<span class="g-val">${offline ? '—' : fmtPct(diskPct)}</span> <span class="g-val">${offline ? '—' : (metrics?.hdd_used && metrics?.hdd_total ? fmt(metrics.hdd_used) + '/' + fmt(metrics.hdd_total) : '—')}</span>
</div> </div>
</div> </div>
<div class="tile-foot"> <div class="tile-foot">
@@ -124,7 +124,7 @@ const Grid = (() => {
function refresh(agents) { function refresh(agents) {
agents.forEach(a => { agents.forEach(a => {
if (!_agents.has(a.id)) { if (!_agents.has(a.id)) {
_agents.set(a.id, { agent: a, metrics: null }); _agents.set(a.id, { agent: a, metrics: a.last_metrics || null });
} else { } else {
_agents.get(a.id).agent = a; _agents.get(a.id).agent = a;
} }
+24 -2
View File
@@ -30,8 +30,27 @@ const Popups = (() => {
document.getElementById('icon-upload').onchange = async (e) => { document.getElementById('icon-upload').onchange = async (e) => {
const file = e.target.files[0]; const file = e.target.files[0];
if (!file) return; if (!file) return;
await API.uploadIcon(agentId, file); const hint = document.getElementById('icon-hint');
img.src = API.iconUrl(agentId) + '?t=' + Date.now(); try {
await API.uploadIcon(agentId, file);
const ts = '?t=' + Date.now();
img.src = API.iconUrl(agentId) + ts;
img.style.display = 'block';
document.getElementById('pop-icon-fa').style.display = 'none';
const tileImg = document.querySelector(`#tile-${CSS.escape(agentId)} .t-icon img`);
if (tileImg) tileImg.src = API.iconUrl(agentId) + ts;
} catch (err) {
if (hint) {
hint.style.color = 'var(--err)';
hint.textContent = 'Erreur : ' + (err.message || 'téléversement échoué');
setTimeout(() => {
hint.style.color = '';
hint.textContent = 'Cliquer sur l\'icône pour personnaliser · JPG PNG WEBP · max 128×128 px';
}, 4000);
}
} finally {
e.target.value = '';
}
}; };
// Uptime // Uptime
@@ -119,6 +138,9 @@ const Popups = (() => {
<div class="meta-grid"> <div class="meta-grid">
<div class="meta"><div class="meta-lbl">HOSTNAME</div><div class="meta-val">${esc(agent.hostname)}</div></div> <div class="meta"><div class="meta-lbl">HOSTNAME</div><div class="meta-val">${esc(agent.hostname)}</div></div>
<div class="meta"><div class="meta-lbl">ADRESSE IP</div><div class="meta-val">${esc(agent.ip) || '—'}</div></div> <div class="meta"><div class="meta-lbl">ADRESSE IP</div><div class="meta-val">${esc(agent.ip) || '—'}</div></div>
<div class="meta"><div class="meta-lbl">VERSION AGENT</div><div class="meta-val" style="display:flex;align-items:center;gap:6px">
${agent.version ? `<span style="font-family:var(--font-mono);background:var(--bg-1);border:1px solid var(--border-2);border-radius:5px;padding:1px 7px;font-size:11px;color:var(--accent)">v${esc(agent.version)}</span>` : '<span style="color:var(--ink-4)">—</span>'}
</div></div>
<div class="meta"><div class="meta-lbl">PROTOCOLES ACTIFS</div><div style="display:flex;gap:5px;margin-top:4px">${protos || '—'}</div></div> <div class="meta"><div class="meta-lbl">PROTOCOLES ACTIFS</div><div style="display:flex;gap:5px;margin-top:4px">${protos || '—'}</div></div>
<div class="meta"><div class="meta-lbl">DERNIER CONTACT</div><div class="meta-val">${new Date(agent.last_seen * 1000).toLocaleTimeString('fr-FR')}</div></div> <div class="meta"><div class="meta-lbl">DERNIER CONTACT</div><div class="meta-val">${new Date(agent.last_seen * 1000).toLocaleTimeString('fr-FR')}</div></div>
</div> </div>
+37 -3
View File
@@ -92,6 +92,13 @@ ok "Serveur : $SERVER_IP:$SERVER_PORT | MQTT broker : $MQTT_HOST"
# ── 5. Installer le binaire ──────────────────────────────────────────────────── # ── 5. Installer le binaire ────────────────────────────────────────────────────
echo "" echo ""
echo "[1/5] Installation du binaire dans /usr/local/bin/" echo "[1/5] Installation du binaire dans /usr/local/bin/"
# Arrêter le service si en cours (le binaire ne peut pas être écrasé à chaud)
if systemctl is-active --quiet nanometrics-agent 2>/dev/null; then
warn "Service en cours — arrêt temporaire..."
systemctl stop nanometrics-agent
fi
cp "$TMP_BIN" "$INSTALL_BIN" cp "$TMP_BIN" "$INSTALL_BIN"
chmod 755 "$INSTALL_BIN" chmod 755 "$INSTALL_BIN"
ok "Binaire installé" ok "Binaire installé"
@@ -105,10 +112,33 @@ ok "Répertoire créé"
# ── 7. Écrire config.toml ───────────────────────────────────────────────────── # ── 7. Écrire config.toml ─────────────────────────────────────────────────────
echo "[3/5] Écriture de $CONFIG_FILE" echo "[3/5] Écriture de $CONFIG_FILE"
# Ne pas écraser une config existante (upgrade) OVERWRITE_CONFIG="${OVERWRITE_CONFIG:-}"
WRITE_CONFIG=true
if [ -f "$CONFIG_FILE" ]; then if [ -f "$CONFIG_FILE" ]; then
warn "config.toml déjà présent — conservé tel quel" if [ "${OVERWRITE_CONFIG}" = "true" ]; then
else warn "OVERWRITE_CONFIG=true — config.toml sera écrasé"
WRITE_CONFIG=true
elif [ -t 0 ]; then
# Mode interactif (bash local, pas curl | bash)
echo ""
warn "Un config.toml existe déjà :"
echo " $CONFIG_FILE"
printf " Écraser la configuration existante ? [o/N] : "
read -r _ANS
if [[ "$_ANS" =~ ^[Oo]$ ]]; then
WRITE_CONFIG=true
else
ok "config.toml conservé"
WRITE_CONFIG=false
fi
else
warn "config.toml déjà présent — conservé (relancez avec OVERWRITE_CONFIG=true pour écraser)"
WRITE_CONFIG=false
fi
fi
if [ "$WRITE_CONFIG" = "true" ]; then
cat > "$CONFIG_FILE" << TOML cat > "$CONFIG_FILE" << TOML
[server] [server]
ip = "$SERVER_IP" ip = "$SERVER_IP"
@@ -158,6 +188,10 @@ TOML
ok "config.toml créé" ok "config.toml créé"
fi fi
# S'assurer que le fichier est toujours lisible (cas d'un config existant en 640)
chmod 644 "$CONFIG_FILE" 2>/dev/null || true
chmod 755 "$CONFIG_DIR"
# ── 8. Installer le fichier service ────────────────────────────────────────── # ── 8. Installer le fichier service ──────────────────────────────────────────
echo "[4/5] Installation du service systemd" echo "[4/5] Installation du service systemd"
curl -fsSL -o "$SERVICE_FILE" "$SERVICE_URL" curl -fsSL -o "$SERVICE_FILE" "$SERVICE_URL"
+1 -1
View File
@@ -11,7 +11,7 @@ RestartSec=5
DynamicUser=yes DynamicUser=yes
ConfigurationDirectory=nanometrics ConfigurationDirectory=nanometrics
ConfigurationDirectoryMode=0750 ConfigurationDirectoryMode=0755
ProtectSystem=strict ProtectSystem=strict
ProtectHome=read-only ProtectHome=read-only
+3 -1
View File
@@ -25,7 +25,9 @@ DESCRIPTION="${2:-Release $TAG}"
ROOT="$(cd "$(dirname "$0")/.." && pwd)" ROOT="$(cd "$(dirname "$0")/.." && pwd)"
CARGO_TOML="$ROOT/agent/Cargo.toml" CARGO_TOML="$ROOT/agent/Cargo.toml"
# ── 1. Compiler pour toutes les cibles supportées ────────────────────────── mkdir -p "$ROOT/dist"
# ── 1. Compiler l'agent pour toutes les cibles supportées ────────────────
echo "=== Compilation de l'agent ===" echo "=== Compilation de l'agent ==="
TARGETS=("x86_64-unknown-linux-musl" "aarch64-unknown-linux-musl") TARGETS=("x86_64-unknown-linux-musl" "aarch64-unknown-linux-musl")
LABELS=("linux-amd64" "linux-arm64") LABELS=("linux-amd64" "linux-arm64")
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
+4 -5
View File
@@ -5,10 +5,9 @@ RUN go mod download
COPY . . COPY . .
RUN CGO_ENABLED=0 go build -ldflags="-s -w" -o nanometrics-server . RUN CGO_ENABLED=0 go build -ldflags="-s -w" -o nanometrics-server .
FROM alpine:3.19 FROM scratch
RUN apk add --no-cache ca-certificates COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
WORKDIR /app COPY --from=builder /app/nanometrics-server /nanometrics-server
COPY --from=builder /app/nanometrics-server .
VOLUME /data VOLUME /data
EXPOSE 8080 9999/udp EXPOSE 8080 9999/udp
CMD ["./nanometrics-server"] CMD ["/nanometrics-server"]
+80 -9
View File
@@ -20,7 +20,7 @@ const schema = `
CREATE TABLE IF NOT EXISTS agents ( CREATE TABLE IF NOT EXISTS agents (
id TEXT PRIMARY KEY, hostname TEXT NOT NULL, id TEXT PRIMARY KEY, hostname TEXT NOT NULL,
ip TEXT NOT NULL DEFAULT '', status TEXT NOT NULL DEFAULT 'offline', ip TEXT NOT NULL DEFAULT '', status TEXT NOT NULL DEFAULT 'offline',
last_seen INTEGER NOT NULL DEFAULT 0 last_seen INTEGER NOT NULL DEFAULT 0, version TEXT NOT NULL DEFAULT ''
); );
CREATE TABLE IF NOT EXISTS metrics ( CREATE TABLE IF NOT EXISTS metrics (
id INTEGER PRIMARY KEY AUTOINCREMENT, agent_id TEXT NOT NULL, ts INTEGER NOT NULL, id INTEGER PRIMARY KEY AUTOINCREMENT, agent_id TEXT NOT NULL, ts INTEGER NOT NULL,
@@ -57,8 +57,12 @@ func Open(path string) (*DB, error) {
} }
func (d *DB) migrate() error { func (d *DB) migrate() error {
_, err := d.conn.Exec(schema) if _, err := d.conn.Exec(schema); err != nil {
return err return err
}
// Migrations additives pour les colonnes ajoutées après la création initiale
_, _ = d.conn.Exec(`ALTER TABLE agents ADD COLUMN version TEXT NOT NULL DEFAULT ''`)
return nil
} }
func (d *DB) Close() { _ = d.conn.Close() } func (d *DB) Close() { _ = d.conn.Close() }
@@ -66,11 +70,12 @@ func (d *DB) Close() { _ = d.conn.Close() }
func (d *DB) UpsertAgent(m *models.AgentMetrics) error { func (d *DB) UpsertAgent(m *models.AgentMetrics) error {
ts := time.Now().Unix() ts := time.Now().Unix()
_, err := d.conn.Exec(` _, err := d.conn.Exec(`
INSERT INTO agents (id, hostname, ip, status, last_seen) INSERT INTO agents (id, hostname, ip, status, last_seen, version)
VALUES (?, ?, ?, ?, ?) VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET ON CONFLICT(id) DO UPDATE SET
ip=excluded.ip, status=excluded.status, last_seen=excluded.last_seen`, ip=excluded.ip, status=excluded.status, last_seen=excluded.last_seen,
m.Hostname, m.Hostname, m.IP, m.Status, ts) version=CASE WHEN excluded.version != '' THEN excluded.version ELSE version END`,
m.Hostname, m.Hostname, m.IP, m.Status, ts, m.Version)
return err return err
} }
@@ -104,7 +109,7 @@ func (d *DB) InsertMetrics(m *models.AgentMetrics) error {
} }
func (d *DB) GetAgents() ([]models.Agent, error) { func (d *DB) GetAgents() ([]models.Agent, error) {
rows, err := d.conn.Query(`SELECT id, hostname, ip, status, last_seen FROM agents`) rows, err := d.conn.Query(`SELECT id, hostname, ip, status, last_seen, version FROM agents`)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -112,7 +117,7 @@ func (d *DB) GetAgents() ([]models.Agent, error) {
var agents []models.Agent var agents []models.Agent
for rows.Next() { for rows.Next() {
var a models.Agent var a models.Agent
if err := rows.Scan(&a.ID, &a.Hostname, &a.IP, &a.Status, &a.LastSeen); err != nil { if err := rows.Scan(&a.ID, &a.Hostname, &a.IP, &a.Status, &a.LastSeen, &a.Version); err != nil {
return nil, err return nil, err
} }
agents = append(agents, a) agents = append(agents, a)
@@ -123,6 +128,72 @@ func (d *DB) GetAgents() ([]models.Agent, error) {
return agents, nil return agents, nil
} }
func (d *DB) GetLastMetrics(agentID string) (*models.AgentMetrics, error) {
var cpu, temperature *float64
var memUsed, memFree, memTotal, hddUsed, hddFree, hddTotal *int64
var uptime, netRX, netTX *int64
var smartPassed, smartTemp, smartRealloc, smartHours, smartWear *int64
// Chaque sous-requête prend la dernière valeur NON NULL de sa colonne.
// Nécessaire car les paquets rapides (2s) ne contiennent pas les métriques
// lentes (disque, smart) qui sont envoyées toutes les 60s.
err := d.conn.QueryRow(`
SELECT
(SELECT cpu_percent FROM metrics WHERE agent_id=? AND cpu_percent IS NOT NULL ORDER BY ts DESC LIMIT 1),
(SELECT memory_used FROM metrics WHERE agent_id=? AND memory_used IS NOT NULL ORDER BY ts DESC LIMIT 1),
(SELECT memory_free FROM metrics WHERE agent_id=? AND memory_free IS NOT NULL ORDER BY ts DESC LIMIT 1),
(SELECT memory_total FROM metrics WHERE agent_id=? AND memory_total IS NOT NULL ORDER BY ts DESC LIMIT 1),
(SELECT hdd_used FROM metrics WHERE agent_id=? AND hdd_used IS NOT NULL ORDER BY ts DESC LIMIT 1),
(SELECT hdd_free FROM metrics WHERE agent_id=? AND hdd_free IS NOT NULL ORDER BY ts DESC LIMIT 1),
(SELECT hdd_total FROM metrics WHERE agent_id=? AND hdd_total IS NOT NULL ORDER BY ts DESC LIMIT 1),
(SELECT uptime FROM metrics WHERE agent_id=? AND uptime IS NOT NULL ORDER BY ts DESC LIMIT 1),
(SELECT network_rx FROM metrics WHERE agent_id=? AND network_rx IS NOT NULL ORDER BY ts DESC LIMIT 1),
(SELECT network_tx FROM metrics WHERE agent_id=? AND network_tx IS NOT NULL ORDER BY ts DESC LIMIT 1),
(SELECT temperature FROM metrics WHERE agent_id=? AND temperature IS NOT NULL ORDER BY ts DESC LIMIT 1),
(SELECT smart_passed FROM metrics WHERE agent_id=? AND smart_passed IS NOT NULL ORDER BY ts DESC LIMIT 1),
(SELECT smart_temp FROM metrics WHERE agent_id=? AND smart_passed IS NOT NULL ORDER BY ts DESC LIMIT 1),
(SELECT smart_realloc FROM metrics WHERE agent_id=? AND smart_passed IS NOT NULL ORDER BY ts DESC LIMIT 1),
(SELECT smart_hours FROM metrics WHERE agent_id=? AND smart_passed IS NOT NULL ORDER BY ts DESC LIMIT 1),
(SELECT smart_wear FROM metrics WHERE agent_id=? AND smart_passed IS NOT NULL ORDER BY ts DESC LIMIT 1)`,
agentID, agentID, agentID, agentID,
agentID, agentID, agentID,
agentID, agentID, agentID, agentID,
agentID, agentID, agentID, agentID, agentID).
Scan(&cpu, &memUsed, &memFree, &memTotal,
&hddUsed, &hddFree, &hddTotal,
&uptime, &netRX, &netTX, &temperature,
&smartPassed, &smartTemp, &smartRealloc, &smartHours, &smartWear)
if err == sql.ErrNoRows {
return nil, nil
}
if err != nil {
return nil, err
}
m := &models.AgentMetrics{
CPUPercent: cpu,
MemoryUsed: memUsed,
MemoryFree: memFree,
MemoryTotal: memTotal,
HDDUsed: hddUsed,
HDDFree: hddFree,
HDDTotal: hddTotal,
Uptime: uptime,
NetworkRX: netRX,
NetworkTX: netTX,
Temperature: temperature,
}
if smartPassed != nil {
m.Smart = &models.SmartMetrics{
Passed: *smartPassed == 1,
Temperature: smartTemp,
ReallocatedSectors: smartRealloc,
PowerOnHours: smartHours,
WearLevel: smartWear,
}
}
return m, nil
}
func (d *DB) GetMetricsHistory(agentID string, from, to int64) ([]map[string]interface{}, error) { func (d *DB) GetMetricsHistory(agentID string, from, to int64) ([]map[string]interface{}, error) {
rows, err := d.conn.Query(` rows, err := d.conn.Query(`
SELECT ts, cpu_percent, memory_used, memory_total, hdd_used, hdd_total SELECT ts, cpu_percent, memory_used, memory_total, hdd_used, hdd_total
+4 -2
View File
@@ -1,7 +1,8 @@
version: '3.8'
services: services:
server: server:
build: . build:
context: .
pull: false
restart: unless-stopped restart: unless-stopped
environment: environment:
UDP_ADDR: "0.0.0.0:9999" UDP_ADDR: "0.0.0.0:9999"
@@ -16,6 +17,7 @@ services:
dashboard: dashboard:
image: nginx:alpine image: nginx:alpine
pull_policy: if_not_present
restart: unless-stopped restart: unless-stopped
volumes: volumes:
- ./nginx/nginx.conf:/etc/nginx/conf.d/default.conf:ro - ./nginx/nginx.conf:/etc/nginx/conf.d/default.conf:ro
+3
View File
@@ -15,6 +15,9 @@ func AgentsHandler(database *db.DB) http.HandlerFunc {
http.Error(w, err.Error(), 500) http.Error(w, err.Error(), 500)
return return
} }
for i := range agents {
agents[i].LastMetrics, _ = database.GetLastMetrics(agents[i].ID)
}
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(agents) json.NewEncoder(w).Encode(agents)
} }
+2
View File
@@ -3,6 +3,7 @@ package handlers
import ( import (
"bytes" "bytes"
"image" "image"
_ "image/gif"
_ "image/jpeg" _ "image/jpeg"
"image/png" "image/png"
"io" "io"
@@ -11,6 +12,7 @@ import (
"github.com/disintegration/imaging" "github.com/disintegration/imaging"
"github.com/user/nanometrics/server/db" "github.com/user/nanometrics/server/db"
_ "golang.org/x/image/webp"
) )
const maxIconSize = 128 const maxIconSize = 128
+2
View File
@@ -4,6 +4,7 @@ type AgentMetrics struct {
Hostname string `json:"hostname"` Hostname string `json:"hostname"`
IP string `json:"ip"` IP string `json:"ip"`
Status string `json:"status"` Status string `json:"status"`
Version string `json:"version"`
CPUPercent *float64 `json:"cpu_percent"` CPUPercent *float64 `json:"cpu_percent"`
MemoryUsed *int64 `json:"memory_used"` MemoryUsed *int64 `json:"memory_used"`
MemoryFree *int64 `json:"memory_free"` MemoryFree *int64 `json:"memory_free"`
@@ -32,6 +33,7 @@ type Agent struct {
IP string `json:"ip"` IP string `json:"ip"`
Status string `json:"status"` Status string `json:"status"`
LastSeen int64 `json:"last_seen"` LastSeen int64 `json:"last_seen"`
Version string `json:"version,omitempty"`
LastMetrics *AgentMetrics `json:"last_metrics,omitempty"` LastMetrics *AgentMetrics `json:"last_metrics,omitempty"`
} }
BIN
View File
Binary file not shown.
+1
View File
@@ -2,6 +2,7 @@ server {
listen 80; listen 80;
root /usr/share/nginx/html; root /usr/share/nginx/html;
index index.html; index index.html;
client_max_body_size 10m;
location /api/ { location /api/ {
proxy_pass http://server:8080; proxy_pass http://server:8080;