'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 DISK_STORAGE = env.DISK_STORAGE || 'local-lvm'; 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, }; // Barre "Disque" = stockage choisi (local-lvm par défaut), sinon disque système const sto = resources.find((x) => x.type === 'storage' && x.storage === DISK_STORAGE && x.node === ni.name); n.diskLabel = 'Disque'; if (sto && sto.maxdisk) { n.diskLabel = DISK_STORAGE; n.disk = sto.disk; n.maxdisk = sto.maxdisk; } 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; })); // ordre stable : proxmox, pve, pve2, pve3, pve4... nodes.sort((a, b) => a.name.localeCompare(b.name, 'fr', { numeric: true })); 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); // Stockages réseau = identiques sur tous les nodes -> une seule ligne const NET_TYPES = new Set(['cifs', 'nfs', 'pbs', 'glusterfs', 'cephfs', 'rbd', 'iscsi', 'iscsidirect', 'zfs']); const storageMap = new Map(); for (const s of resources.filter((r) => r.type === 'storage')) { const shared = NET_TYPES.has(s.plugintype); const entry = { id: s.storage, node: s.node, status: s.status, shared, disk: s.disk, maxdisk: s.maxdisk, content: s.content, plugintype: s.plugintype, }; const key = shared ? s.storage : `${s.storage}@${s.node}`; const prev = storageMap.get(key); // pour un stockage partagé, on garde l'entrée qui a des données (node joignable) if (!prev || (!prev.maxdisk && entry.maxdisk)) storageMap.set(key, entry); } const storage = [...storageMap.values()]; 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); });