commit 40382c50fdf914cc2bc19f41ca838fb080f4766f Author: Ethan Sun Date: Sun Nov 1 19:07:18 2026 +0100 Dashboard Proxmox (Node.js) : CPU, RAM, température, VM/LXC, stockage Co-Authored-By: Claude Sonnet 5.5 diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..e3a379c --- /dev/null +++ b/.env.example @@ -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 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4bd39b3 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +.env +data/ +node_modules/ +.DS_Store diff --git a/README.md b/README.md new file mode 100644 index 0000000..8d86ae2 --- /dev/null +++ b/README.md @@ -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=` + +## 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) diff --git a/package.json b/package.json new file mode 100644 index 0000000..d7ccc07 --- /dev/null +++ b/package.json @@ -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" +} diff --git a/public/index.html b/public/index.html new file mode 100644 index 0000000..ae11e12 --- /dev/null +++ b/public/index.html @@ -0,0 +1,231 @@ + + + + + +Proxmox Dashboard + + + +
+
+

proxmox

+ … + +
+ + + +
+ +
+
+ +
+ +

Nodes

+
+ +

VM & conteneurs

+
+ +

Stockage

+
+
+ + + + diff --git a/server.js b/server.js new file mode 100644 index 0000000..5114cbd --- /dev/null +++ b/server.js @@ -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); });