Dashboard Proxmox (Node.js) : CPU, RAM, température, VM/LXC, stockage

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-01 19:07:18 +01:00
co-authored by Claude Sonnet 5.5
Unverified
commit 40382c50fd
6 changed files with 560 additions and 0 deletions
+23
View File
@@ -0,0 +1,23 @@
# IP:port d'un ou plusieurs nodes du cluster (le premier qui répond est utilisé)
PVE_HOSTS=192.168.1.10:8006,192.168.1.11:8006,192.168.1.12:8006,192.168.1.13:8006
# Token API Proxmox (rôle PVEAuditor suffisant)
PVE_TOKEN=dashboard@pve!dash=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
# Certificat auto-signé de Proxmox -> false
PVE_VERIFY_TLS=false
# node_exporter pour la température (port 9100 sur chaque node)
NODE_EXPORTER_PORT=9100
# Optionnel : forcer l'IP d'un node pour node_exporter (nom=ip, séparés par des virgules)
# NODE_ADDRS=pve1=192.168.1.10,pve2=192.168.1.11
# Optionnel : protège le dashboard par mot de passe (login: admin)
# DASHBOARD_PASSWORD=change-me
# Intervalle de rafraîchissement côté serveur (secondes)
POLL_INTERVAL=10
# Port (Pelican fournit SERVER_PORT automatiquement)
# PORT=3000
+4
View File
@@ -0,0 +1,4 @@
.env
data/
node_modules/
.DS_Store
+43
View File
@@ -0,0 +1,43 @@
# Proxmox Dashboard
Dashboard Node.js (zéro dépendance) pour un cluster Proxmox VE : CPU, RAM, disque, swap, température, VM/LXC, stockage, historique 1h/24h/48h.
## 1. Token API Proxmox
Datacenter → Permissions → **API Tokens** → Add
- User : `root@pam` (ou un user dédié), Token ID : `dash`
- Décoche **Privilege Separation** (ou donne le rôle `PVEAuditor` au token)
- Si user dédié : Datacenter → Permissions → Add → User Permission → path `/`, rôle `PVEAuditor`
Copie le secret → `PVE_TOKEN=user@realm!dash=<secret>`
## 2. Température : node_exporter sur chaque node
```bash
apt update && apt install -y prometheus-node-exporter lm-sensors
systemctl enable --now prometheus-node-exporter
curl -s localhost:9100/metrics | grep hwmon_temp # doit afficher des valeurs
```
Si rien ne s'affiche : `sensors-detect --auto` puis redémarre le service.
Le port 9100 n'est nécessaire que depuis l'IP du dashboard (pare-feu Proxmox).
## 3. Lancer en local
```bash
cp .env.example .env # puis édite
node server.js # http://localhost:3000
```
## 4. Pelican Panel
1. Crée un serveur avec un egg **Node.js générique** (ou « Generic Node.js »), image Node 20+.
2. Upload ces fichiers (`server.js`, `package.json`, `public/`) dans le gestionnaire de fichiers, + un fichier `.env`.
(Ou variables d'environnement du serveur : `PVE_HOSTS`, `PVE_TOKEN`, …)
3. Startup command : `node server.js` (pas de `npm install` nécessaire).
4. Alloue un port ; Pelican injecte `SERVER_PORT`, le dashboard l'utilise automatiquement.
5. Le conteneur doit pouvoir joindre les nodes sur `:8006` et `:9100`.
6. Mets un reverse proxy (Caddy/Cloudflare Access) devant, ou définis `DASHBOARD_PASSWORD` (login quelconque, mot de passe = valeur).
## API interne
- `GET /api/overview` : état actuel
- `GET /api/history?range=3600` : historique (secondes)
+13
View File
@@ -0,0 +1,13 @@
{
"name": "proxmox-dashboard",
"version": "1.0.0",
"description": "Dashboard pour cluster Proxmox VE (CPU, RAM, disque, température, VM/LXC)",
"main": "server.js",
"scripts": {
"start": "node server.js"
},
"engines": {
"node": ">=18"
},
"license": "MIT"
}
+231
View File
@@ -0,0 +1,231 @@
<!doctype html>
<html lang="fr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Proxmox Dashboard</title>
<style>
:root {
--bg: #07070a; --card: #101015; --card2: #16161d; --line: #23232d;
--text: #f2f2f5; --muted: #8a8a98; --pink: #ff2e93; --pink2: #ff7ac0;
--ok: #34d399; --warn: #fbbf24; --bad: #f87171;
--r: 18px;
}
* { box-sizing: border-box; margin: 0; }
body { background: var(--bg); color: var(--text); font: 14px/1.4 -apple-system, "Inter", "Segoe UI", sans-serif; padding: 24px 16px 48px; }
.wrap { max-width: 1400px; margin: 0 auto; }
header { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; margin-bottom: 20px; }
h1 { font-size: 20px; font-weight: 700; letter-spacing: -.02em; }
.pill { font-size: 12px; padding: 3px 10px; border-radius: 99px; background: rgba(52,211,153,.12); color: var(--ok); border: 1px solid rgba(52,211,153,.3); }
.pill.bad { background: rgba(248,113,113,.12); color: var(--bad); border-color: rgba(248,113,113,.3); }
.spacer { flex: 1; }
.clock { color: var(--muted); font-variant-numeric: tabular-nums; }
.seg { display: inline-flex; background: var(--card2); border: 1px solid var(--line); border-radius: 10px; padding: 2px; }
.seg button { background: none; border: 0; color: var(--muted); padding: 4px 12px; border-radius: 8px; cursor: pointer; font: inherit; }
.seg button.on { background: #2a2a35; color: var(--text); }
h2 { font-size: 12px; text-transform: uppercase; letter-spacing: .08em; color: var(--muted); margin: 28px 0 10px; font-weight: 600; }
.totals { display: grid; grid-template-columns: repeat(auto-fit, minmax(190px, 1fr)); gap: 12px; }
.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(420px, 1fr)); gap: 14px; }
@media (max-width: 480px) { .grid { grid-template-columns: 1fr; } }
.card { background: var(--card); border: 1px solid var(--line); border-radius: var(--r); padding: 16px 18px; box-shadow: 0 0 0 1px rgba(255,255,255,.02) inset; }
.card.off { opacity: .55; }
.label { font-size: 11px; color: var(--muted); text-transform: uppercase; letter-spacing: .06em; }
.big { font-size: 26px; font-weight: 700; font-variant-numeric: tabular-nums; letter-spacing: -.02em; }
.big small { font-size: 13px; color: var(--muted); font-weight: 500; margin-left: 4px; }
.sub { color: var(--muted); font-size: 12px; margin-top: 2px; }
.nodehead { display: flex; align-items: center; gap: 8px; margin-bottom: 12px; }
.dot { width: 8px; height: 8px; border-radius: 50%; background: var(--ok); box-shadow: 0 0 8px var(--ok); }
.off .dot { background: var(--bad); box-shadow: 0 0 8px var(--bad); }
.nodename { font-weight: 700; font-size: 16px; }
.ip { color: var(--muted); font-size: 12px; margin-left: auto; font-variant-numeric: tabular-nums; }
.nodebody { display: grid; grid-template-columns: 150px 1fr; gap: 18px; }
@media (max-width: 480px) { .nodebody { grid-template-columns: 1fr; } }
.temp { font-size: 34px; font-weight: 800; font-variant-numeric: tabular-nums; letter-spacing: -.03em; }
.temp small { font-size: 14px; color: var(--muted); font-weight: 500; }
.spark { width: 100%; height: 56px; margin-top: 8px; display: block; }
.bar { margin-bottom: 9px; }
.bar .row { display: flex; justify-content: space-between; font-size: 12px; margin-bottom: 4px; }
.bar .row b { font-weight: 500; color: var(--muted); }
.bar .row span { font-variant-numeric: tabular-nums; }
.track { height: 5px; background: #24242e; border-radius: 9px; overflow: hidden; }
.fill { height: 100%; background: linear-gradient(90deg, var(--pink), var(--pink2)); border-radius: 9px; transition: width .6s; }
.fill.warn { background: var(--warn); } .fill.bad { background: var(--bad); }
.foot { display: flex; gap: 14px; flex-wrap: wrap; margin-top: 10px; padding-top: 10px; border-top: 1px solid var(--line); color: var(--muted); font-size: 12px; font-variant-numeric: tabular-nums; }
table { width: 100%; border-collapse: collapse; font-size: 13px; }
th { text-align: left; font-size: 11px; color: var(--muted); font-weight: 600; text-transform: uppercase; letter-spacing: .06em; padding: 6px 10px; }
td { padding: 8px 10px; border-top: 1px solid var(--line); font-variant-numeric: tabular-nums; }
.tablecard { padding: 8px 8px; overflow-x: auto; }
.tag { font-size: 11px; padding: 1px 8px; border-radius: 6px; background: #22222c; color: var(--muted); }
.st { display: inline-block; width: 7px; height: 7px; border-radius: 50%; background: var(--muted); margin-right: 6px; }
.st.running { background: var(--ok); } .st.stopped { background: var(--bad); }
.mini { width: 70px; display: inline-block; vertical-align: middle; }
#err { display: none; margin-bottom: 14px; padding: 10px 14px; border-radius: 12px; background: rgba(248,113,113,.1); border: 1px solid rgba(248,113,113,.3); color: var(--bad); }
</style>
</head>
<body>
<div class="wrap">
<header>
<h1>proxmox</h1>
<span class="pill" id="clusterPill">…</span>
<span class="spacer"></span>
<div class="seg" id="range">
<button data-r="3600" class="on">1h</button>
<button data-r="86400">24h</button>
<button data-r="172800">48h</button>
</div>
<span class="clock" id="clock"></span>
</header>
<div id="err"></div>
<div class="totals" id="totals"></div>
<h2>Nodes</h2>
<div class="grid" id="nodes"></div>
<h2>VM &amp; conteneurs</h2>
<div class="card tablecard"><table id="guests"></table></div>
<h2>Stockage</h2>
<div class="card tablecard"><table id="storage"></table></div>
</div>
<script>
const $ = (id) => document.getElementById(id);
let range = 3600, data = null, hist = {};
const fmtBytes = (b) => {
if (b == null) return '–';
const u = ['o', 'Ko', 'Mo', 'Go', 'To']; let i = 0;
while (b >= 1024 && i < u.length - 1) { b /= 1024; i++; }
return b.toFixed(b >= 100 || i < 2 ? 0 : 1) + ' ' + u[i];
};
const fmtUp = (s) => {
if (!s) return '–';
const d = Math.floor(s / 86400), h = Math.floor(s % 86400 / 3600), m = Math.floor(s % 3600 / 60);
return d ? `${d}j ${h}h` : h ? `${h}h ${m}m` : `${m}m`;
};
const pct = (a, b) => (a == null || !b ? 0 : a / b * 100);
const cls = (p) => p >= 90 ? 'bad' : p >= 75 ? 'warn' : '';
const esc = (s) => String(s ?? '').replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
function bar(label, p, text) {
return `<div class="bar"><div class="row"><b>${label}</b><span>${text}</span></div>
<div class="track"><div class="fill ${cls(p)}" style="width:${Math.min(100, p).toFixed(1)}%"></div></div></div>`;
}
function spark(points, idx, min, max) {
const pts = points.filter((p) => p[idx] != null);
if (pts.length < 2) return '<svg class="spark"></svg>';
const t0 = pts[0][0], t1 = pts[pts.length - 1][0] || t0 + 1;
const vals = pts.map((p) => p[idx]);
const lo = min ?? Math.min(...vals) - 2, hi = max ?? Math.max(...vals) + 2;
const W = 300, H = 56;
const xy = pts.map((p) => `${((p[0] - t0) / (t1 - t0 || 1) * W).toFixed(1)},${(H - (p[idx] - lo) / (hi - lo || 1) * (H - 4) - 2).toFixed(1)}`);
const id = 'g' + idx + Math.random().toString(36).slice(2, 6);
return `<svg class="spark" viewBox="0 0 ${W} ${H}" preserveAspectRatio="none">
<defs><linearGradient id="${id}" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#ff2e93" stop-opacity=".35"/><stop offset="1" stop-color="#ff2e93" stop-opacity="0"/></linearGradient></defs>
<polygon points="0,${H} ${xy.join(' ')} ${W},${H}" fill="url(#${id})"/>
<polyline points="${xy.join(' ')}" fill="none" stroke="#ff2e93" stroke-width="1.8" vector-effect="non-scaling-stroke" stroke-linejoin="round"/></svg>`;
}
function render() {
if (!data) return;
$('err').style.display = data.ok ? 'none' : 'block';
if (!data.ok) $('err').textContent = 'Erreur API Proxmox : ' + (data.error || 'inconnue');
if (!data.nodes) return;
const c = data.cluster;
const online = data.nodes.filter((n) => n.online).length;
const pill = $('clusterPill');
pill.textContent = `${c.name || 'cluster'} · ${online}/${data.nodes.length} en ligne`;
pill.className = 'pill' + (online < data.nodes.length || c.quorate === false ? ' bad' : '');
// totaux
const on = data.nodes.filter((n) => n.online);
const sum = (k) => on.reduce((a, n) => a + (n[k] || 0), 0);
const cpuAvg = on.length ? on.reduce((a, n) => a + (n.cpu || 0), 0) / on.length * 100 : 0;
const temps = on.map((n) => n.temp).filter((t) => t != null);
const running = data.guests.filter((g) => g.status === 'running').length;
$('totals').innerHTML = [
['CPU moyen', cpuAvg.toFixed(1) + '<small>%</small>', `${sum('maxcpu')} cœurs au total`],
['RAM', fmtBytes(sum('mem')), `sur ${fmtBytes(sum('maxmem'))} · ${pct(sum('mem'), sum('maxmem')).toFixed(0)}%`],
['Temp. max', temps.length ? Math.max(...temps).toFixed(1) + '<small>°C</small>' : '–', temps.length ? `moy. ${(temps.reduce((a, b) => a + b, 0) / temps.length).toFixed(1)}°C` : 'node_exporter ?'],
['Invités actifs', `${running}<small>/ ${data.guests.length}</small>`, `${data.guests.filter((g) => g.type === 'qemu').length} VM · ${data.guests.filter((g) => g.type === 'lxc').length} LXC`],
].map(([l, v, s]) => `<div class="card"><div class="label">${l}</div><div class="big">${v}</div><div class="sub">${s}</div></div>`).join('');
// nodes
$('nodes').innerHTML = data.nodes.map((n) => {
const h = hist[n.name] || [];
const cpuP = (n.cpu || 0) * 100, memP = pct(n.mem, n.maxmem), diskP = pct(n.disk, n.maxdisk);
const guests = data.guests.filter((g) => g.node === n.name && g.status === 'running').length;
return `<div class="card ${n.online ? '' : 'off'}">
<div class="nodehead"><span class="dot"></span><span class="nodename">${esc(n.name)}</span>
<span class="ip">${esc(n.ip || '')}</span></div>
<div class="nodebody">
<div>
<div class="label">Température</div>
<div class="temp">${n.temp != null ? n.temp.toFixed(1) + '<small> °C</small>' : '<small>n/a</small>'}</div>
${spark(h, 3)}
</div>
<div>
${bar('CPU' + (n.maxcpu ? ` · ${n.maxcpu} cœurs` : ''), cpuP, cpuP.toFixed(1) + ' %')}
${bar('RAM', memP, `${fmtBytes(n.mem)} / ${fmtBytes(n.maxmem)}`)}
${bar('Disque', diskP, `${fmtBytes(n.disk)} / ${fmtBytes(n.maxdisk)}`)}
${n.swapMax ? bar('Swap', pct(n.swap, n.swapMax), `${fmtBytes(n.swap)} / ${fmtBytes(n.swapMax)}`) : ''}
</div>
</div>
<div class="foot">
<span>up ${fmtUp(n.uptime)}</span>
<span>load ${n.load ? n.load.map((x) => x.toFixed(2)).join(' ') : '–'}</span>
<span>${guests} invité(s) actif(s)</span>
${n.pveVersion ? `<span>${esc(n.pveVersion.replace('pve-manager/', 'PVE ').split('/')[0])}</span>` : ''}
</div>
${n.cpuModel ? `<div class="sub" style="margin-top:6px">${esc(n.cpuModel)}</div>` : ''}
</div>`;
}).join('');
// invités
$('guests').innerHTML = `<tr><th>ID</th><th>Nom</th><th>Type</th><th>Node</th><th>État</th><th>CPU</th><th>RAM</th><th>Uptime</th></tr>` +
data.guests.map((g) => `<tr><td>${g.vmid}</td><td>${esc(g.name)}</td><td><span class="tag">${g.type === 'qemu' ? 'VM' : 'LXC'}</span></td>
<td>${esc(g.node)}</td><td><span class="st ${g.status}"></span>${esc(g.status)}</td>
<td>${g.status === 'running' ? (g.cpu * 100).toFixed(1) + ' %' : '–'}</td>
<td>${g.status === 'running' ? `${fmtBytes(g.mem)} / ${fmtBytes(g.maxmem)}` : fmtBytes(g.maxmem)}</td>
<td>${g.status === 'running' ? fmtUp(g.uptime) : '–'}</td></tr>`).join('');
// stockage
$('storage').innerHTML = `<tr><th>Nom</th><th>Node</th><th>Type</th><th>Usage</th><th></th></tr>` +
data.storage.sort((a, b) => a.id.localeCompare(b.id) || a.node.localeCompare(b.node)).map((s) => {
const p = pct(s.disk, s.maxdisk);
return `<tr><td>${esc(s.id)}</td><td>${s.shared ? '<span class="tag">partagé</span>' : esc(s.node)}</td><td>${esc(s.plugintype || '')}</td>
<td>${fmtBytes(s.disk)} / ${fmtBytes(s.maxdisk)} · ${p.toFixed(0)}%</td>
<td><div class="track mini"><div class="fill ${cls(p)}" style="width:${p}%"></div></div></td></tr>`;
}).join('');
}
async function loadOverview() {
try { data = await (await fetch('/api/overview', { cache: 'no-store' })).json(); }
catch { data = { ok: false, error: 'dashboard injoignable', nodes: data?.nodes, guests: data?.guests, storage: data?.storage, cluster: data?.cluster }; }
render();
}
async function loadHistory() {
try { hist = await (await fetch('/api/history?range=' + range, { cache: 'no-store' })).json(); render(); } catch {}
}
$('range').addEventListener('click', (e) => {
if (!e.target.dataset.r) return;
range = +e.target.dataset.r;
[...$('range').children].forEach((b) => b.classList.toggle('on', b === e.target));
loadHistory();
});
setInterval(() => { $('clock').textContent = new Date().toLocaleString('fr-FR', { weekday: 'short', day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit', second: '2-digit' }); }, 1000);
loadOverview(); loadHistory();
setInterval(loadOverview, 5000);
setInterval(loadHistory, 30000);
</script>
</body>
</html>
+246
View File
@@ -0,0 +1,246 @@
'use strict';
/**
* Dashboard Proxmox — backend Node.js sans dépendances.
* - interroge l'API Proxmox (/cluster/status, /cluster/resources, /nodes/:n/status)
* - interroge node_exporter (température) sur chaque node
* - garde un historique en mémoire (persisté sur disque)
*/
const http = require('http');
const https = require('https');
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
// ---------- .env minimal ----------
try {
for (const line of fs.readFileSync(path.join(__dirname, '.env'), 'utf8').split(/\r?\n/)) {
const m = line.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/);
if (m && !line.trim().startsWith('#') && process.env[m[1]] === undefined) {
process.env[m[1]] = m[2].replace(/^["']|["']$/g, '');
}
}
} catch { /* pas de .env, on utilise les variables d'environnement */ }
const env = process.env;
const PORT = Number(env.SERVER_PORT || env.PORT || 3000);
const HOSTS = (env.PVE_HOSTS || '').split(',').map((s) => s.trim()).filter(Boolean)
.map((h) => (h.includes(':') ? h : `${h}:8006`));
const TOKEN = env.PVE_TOKEN || '';
const VERIFY_TLS = String(env.PVE_VERIFY_TLS || 'false').toLowerCase() === 'true';
const NE_PORT = Number(env.NODE_EXPORTER_PORT || 9100);
const POLL_MS = Math.max(3, Number(env.POLL_INTERVAL || 10)) * 1000;
const PASSWORD = env.DASHBOARD_PASSWORD || '';
const NODE_ADDRS = Object.fromEntries(
(env.NODE_ADDRS || '').split(',').map((s) => s.trim().split('=')).filter((p) => p.length === 2)
);
const HISTORY_FILE = path.join(__dirname, 'data', 'history.json');
const HISTORY_STEP_MS = 30_000; // 1 point / 30 s
const HISTORY_MAX = 2880 * 2; // 48 h
if (!HOSTS.length || !TOKEN) {
console.error('PVE_HOSTS et PVE_TOKEN sont requis (voir .env.example).');
}
// ---------- HTTP helper ----------
function httpGet(url, { headers = {}, insecure = false, timeout = 6000 } = {}) {
return new Promise((resolve, reject) => {
const u = new URL(url);
const lib = u.protocol === 'https:' ? https : http;
const req = lib.request(u, {
method: 'GET', headers, timeout,
...(u.protocol === 'https:' ? { rejectUnauthorized: !insecure } : {}),
}, (res) => {
let body = '';
res.setEncoding('utf8');
res.on('data', (c) => (body += c));
res.on('end', () => (res.statusCode >= 200 && res.statusCode < 300
? resolve(body) : reject(new Error(`HTTP ${res.statusCode} ${u.host}${u.pathname}`))));
});
req.on('timeout', () => req.destroy(new Error(`timeout ${u.host}`)));
req.on('error', reject);
req.end();
});
}
// ---------- Proxmox ----------
let activeHost = 0;
async function pve(apiPath) {
let lastErr;
for (let i = 0; i < HOSTS.length; i++) {
const idx = (activeHost + i) % HOSTS.length;
try {
const body = await httpGet(`https://${HOSTS[idx]}/api2/json${apiPath}`, {
headers: { Authorization: `PVEAPIToken=${TOKEN}` }, insecure: !VERIFY_TLS,
});
activeHost = idx;
return JSON.parse(body).data;
} catch (e) { lastErr = e; }
}
throw lastErr || new Error('aucun host Proxmox configuré');
}
// ---------- node_exporter (température) ----------
function parseTemp(text) {
const cpuTemps = [], allTemps = [], zones = [];
for (const line of text.split('\n')) {
if (line.startsWith('#')) continue;
let m = line.match(/^node_hwmon_temp_celsius\{([^}]*)\}\s+([-\d.eE+]+)/);
if (m) {
const v = parseFloat(m[2]);
if (!isFinite(v) || v <= 0 || v > 150) continue;
allTemps.push(v);
if (/chip="[^"]*(coretemp|k10temp|zenpower|cpu|soc)[^"]*"/i.test(m[1])) cpuTemps.push(v);
continue;
}
m = line.match(/^node_thermal_zone_temp\{[^}]*\}\s+([-\d.eE+]+)/);
if (m) zones.push(parseFloat(m[1]));
}
const pick = cpuTemps.length ? cpuTemps : allTemps.length ? allTemps : zones;
return pick.length ? Math.max(...pick) : null;
}
async function fetchTemp(ip) {
try { return parseTemp(await httpGet(`http://${ip}:${NE_PORT}/metrics`, { timeout: 3000 })); }
catch { return null; }
}
// ---------- état ----------
let snapshot = { ok: false, error: 'pas encore de données', updated: 0 };
let history = {}; // { node: [[t, cpu%, mem%, temp|null], ...] }
let lastHistoryPush = 0;
try { history = JSON.parse(fs.readFileSync(HISTORY_FILE, 'utf8')); } catch { history = {}; }
function saveHistory() {
try {
fs.mkdirSync(path.dirname(HISTORY_FILE), { recursive: true });
fs.writeFileSync(HISTORY_FILE, JSON.stringify(history));
} catch (e) { console.error('save history:', e.message); }
}
async function poll() {
try {
const [clusterStatus, resources] = await Promise.all([
pve('/cluster/status'), pve('/cluster/resources'),
]);
const nodeInfo = clusterStatus.filter((x) => x.type === 'node');
const quorum = clusterStatus.find((x) => x.type === 'cluster');
const resNodes = resources.filter((r) => r.type === 'node');
const nodes = await Promise.all(nodeInfo.map(async (ni) => {
const r = resNodes.find((x) => x.node === ni.name) || {};
const ip = NODE_ADDRS[ni.name] || ni.ip;
const online = ni.online === 1;
const n = {
name: ni.name, ip, online,
cpu: r.cpu ?? null, maxcpu: r.maxcpu ?? null,
mem: r.mem ?? null, maxmem: r.maxmem ?? null,
disk: r.disk ?? null, maxdisk: r.maxdisk ?? null,
uptime: r.uptime ?? 0,
temp: null, load: null, swap: null, swapMax: null, cpuModel: null, kernel: null, pveVersion: null,
};
if (!online) return n;
const [st, temp] = await Promise.all([
pve(`/nodes/${encodeURIComponent(ni.name)}/status`).catch(() => null),
ip ? fetchTemp(ip) : null,
]);
n.temp = temp;
if (st) {
n.load = st.loadavg ? st.loadavg.map(Number) : null;
n.swap = st.swap?.used ?? null; n.swapMax = st.swap?.total ?? null;
n.cpuModel = st.cpuinfo?.model ?? null;
n.kernel = st.kversion ?? null; n.pveVersion = st.pveversion ?? null;
n.ioWait = st.wait ?? null;
}
return n;
}));
const guests = resources.filter((r) => r.type === 'qemu' || r.type === 'lxc').map((g) => ({
vmid: g.vmid, name: g.name, type: g.type, node: g.node, status: g.status,
cpu: g.cpu, maxcpu: g.maxcpu, mem: g.mem, maxmem: g.maxmem, uptime: g.uptime,
template: !!g.template,
})).filter((g) => !g.template).sort((a, b) => a.vmid - b.vmid);
const storage = resources.filter((r) => r.type === 'storage').map((s) => ({
id: s.storage, node: s.node, status: s.status, shared: !!s.shared,
disk: s.disk, maxdisk: s.maxdisk, content: s.content, plugintype: s.plugintype,
}));
snapshot = {
ok: true, updated: Date.now(), host: HOSTS[activeHost],
cluster: { name: quorum?.name ?? null, quorate: quorum ? quorum.quorate === 1 : null, nodes: nodes.length },
nodes, guests, storage,
};
// historique
const now = Date.now();
if (now - lastHistoryPush >= HISTORY_STEP_MS) {
lastHistoryPush = now;
for (const n of nodes) {
if (!n.online) continue;
(history[n.name] ||= []).push([
Math.floor(now / 1000),
n.cpu != null ? +(n.cpu * 100).toFixed(1) : null,
n.maxmem ? +((n.mem / n.maxmem) * 100).toFixed(1) : null,
n.temp != null ? +n.temp.toFixed(1) : null,
]);
if (history[n.name].length > HISTORY_MAX) history[n.name].splice(0, history[n.name].length - HISTORY_MAX);
}
}
} catch (e) {
snapshot = { ...snapshot, ok: false, error: e.message, updated: snapshot.updated };
console.error('poll:', e.message);
}
}
// ---------- serveur web ----------
const PUBLIC = path.join(__dirname, 'public');
const MIME = { '.html': 'text/html; charset=utf-8', '.css': 'text/css', '.js': 'text/javascript', '.svg': 'image/svg+xml', '.ico': 'image/x-icon' };
function authorized(req) {
if (!PASSWORD) return true;
const h = req.headers.authorization || '';
if (!h.startsWith('Basic ')) return false;
const [, pass = ''] = Buffer.from(h.slice(6), 'base64').toString().split(/:(.*)/s);
const a = Buffer.from(pass), b = Buffer.from(PASSWORD);
return a.length === b.length && crypto.timingSafeEqual(a, b);
}
const server = http.createServer((req, res) => {
if (!authorized(req)) {
res.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Dashboard"' });
return res.end('Authentification requise');
}
const url = new URL(req.url, 'http://x');
const json = (obj) => {
res.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
res.end(JSON.stringify(obj));
};
if (url.pathname === '/api/overview') return json(snapshot);
if (url.pathname === '/api/history') {
const range = Math.min(Number(url.searchParams.get('range')) || 3600, 172800);
const since = Math.floor(Date.now() / 1000) - range;
const out = {};
for (const [node, pts] of Object.entries(history)) out[node] = pts.filter((p) => p[0] >= since);
return json(out);
}
let file = url.pathname === '/' ? '/index.html' : url.pathname;
file = path.normalize(path.join(PUBLIC, file));
if (!file.startsWith(PUBLIC)) { res.writeHead(403); return res.end(); }
fs.readFile(file, (err, data) => {
if (err) { res.writeHead(404); return res.end('Not found'); }
res.writeHead(200, { 'Content-Type': MIME[path.extname(file)] || 'application/octet-stream' });
res.end(data);
});
});
server.listen(PORT, '0.0.0.0', () => {
console.log(`Dashboard Proxmox sur le port ${PORT} (hosts: ${HOSTS.join(', ') || 'aucun'})`);
});
poll();
setInterval(poll, POLL_MS);
setInterval(saveHistory, 5 * 60_000);
for (const sig of ['SIGINT', 'SIGTERM']) process.on(sig, () => { saveHistory(); process.exit(0); });