Monitoring / server.js
citedd's picture
Fix CPU usage, disk usage, and UI
54dc52b verified
Raw History Blame Contribute Delete
5 kB
const express = require('express');
const fs = require('fs');
const path = require('path');
const os = require('os');
const { execSync } = require('child_process');
const app = express();
const PORT = process.env.PORT || 7860;
app.use(express.static(path.join(__dirname, 'public')));
// Cache for CPU tracking
let lastCpu = null;
let lastCpuTime = null;
function getFirstLine(path) {
try {
const data = fs.readFileSync(path, 'utf-8');
const line = data.split('\n').find(l => l.trim().length > 0);
return line ? line.trim() : null;
} catch { return null; }
}
function getCpuUsage() {
try {
const statLine = getFirstLine('/proc/stat');
if (!statLine) return { usage: 'N/A', loadAvg: ['N/A'], cpuCount: os.cpus().length, freq: 'N/A' };
const parts = statLine.split(/\s+/).slice(1).map(Number);
// parts: [user, nice, system, idle, iowait, irq, softirq, steal]
const idle = parts[3] + (parts[4] || 0);
const total = parts.slice(0, 8).reduce((a, b) => a + b, 0);
const active = total - idle;
const loadAvg = getFirstLine('/proc/loadavg');
const loadArr = loadAvg ? loadAvg.split(/\s+/).slice(0, 3) : ['N/A', 'N/A', 'N/A'];
const cpuCount = os.cpus().length;
if (lastCpu && lastCpu.total && total > lastCpu.total) {
const diffTotal = total - lastCpu.total;
const diffActive = active - lastCpu.active;
const usage = diffTotal > 0 ? Math.round((diffActive / diffTotal) * 100) : 0;
lastCpu = { total, active, idle };
lastCpuTime = Date.now();
return {
usage,
loadAvg: loadArr,
cpuCount,
loadPercent: cpuCount > 0 ? ((parseFloat(loadAvg.split(/\s+/)[0]) / cpuCount) * 100).toFixed(0) : 'N/A'
};
}
// First call — store baseline, return load avg based
lastCpu = { total, active, idle };
lastCpuTime = Date.now();
// Use load average as instant estimate
const load = parseFloat(loadAvg.split(/\s+/)[0]);
const instantUsage = cpuCount > 0 ? Math.min(100, Math.round((load / cpuCount) * 100)) : 0;
return {
usage: instantUsage,
loadAvg: loadArr,
cpuCount,
loadPercent: cpuCount > 0 ? ((load / cpuCount) * 100).toFixed(0) : 'N/A'
};
} catch (e) {
return { usage: 'N/A', loadAvg: ['N/A'], cpuCount: 1, freq: 'N/A' };
}
}
function getMemUsage() {
try {
const meminfo = fs.readFileSync('/proc/meminfo', 'utf-8');
const getVal = (key) => {
const line = meminfo.split('\n').find(l => l.startsWith(key));
return line ? parseInt(line.split(/\s+/)[1]) * 1024 : 0;
};
const total = getVal('MemTotal:');
const available = getVal('MemAvailable:');
const buffers = getVal('Buffers:');
const cached = getVal('Cached:');
const used = total - available;
return {
total: (total / (1024 * 1024 * 1024)).toFixed(1),
used: (used / (1024 * 1024 * 1024)).toFixed(1),
available: (available / (1024 * 1024 * 1024)).toFixed(1),
buffers: (buffers / (1024 * 1024 * 1024)).toFixed(1),
cached: (cached / (1024 * 1024 * 1024)).toFixed(1),
percent: total > 0 ? Math.round((used / total) * 100) : 0
};
} catch {
return { total: 0, used: 0, available: 0, percent: 0 };
}
}
function getDiskUsage() {
try {
// Parse df output since statfs is not available
const df = execSync('df -B1 /', { encoding: 'utf-8' });
const lines = df.trim().split('\n');
if (lines.length >= 2) {
const parts = lines[1].split(/\s+/);
const total = parseInt(parts[1]);
const used = parseInt(parts[2]);
const free = parseInt(parts[3]);
return {
total: (total / (1024 * 1024 * 1024)).toFixed(1),
used: (used / (1024 * 1024 * 1024)).toFixed(1),
free: (free / (1024 * 1024 * 1024)).toFixed(1),
percent: total > 0 ? Math.round((used / total) * 100) : 0,
device: parts[0]
};
}
} catch {}
return { total: 0, used: 0, free: 0, percent: 0 };
}
function getUptime() {
try {
const raw = fs.readFileSync('/proc/uptime', 'utf-8');
const seconds = parseFloat(raw.split(' ')[0]);
const days = Math.floor(seconds / 86400);
const hours = Math.floor((seconds % 86400) / 3600);
const mins = Math.floor((seconds % 3600) / 60);
return `${days}d ${hours}h ${mins}m`;
} catch {
return 'N/A';
}
}
function getKernel() {
try {
return os.release() + ' (' + os.type() + ')';
} catch {
return 'N/A';
}
}
app.get('/api/stats', (req, res) => {
res.json({
cpu: getCpuUsage(),
mem: getMemUsage(),
disk: getDiskUsage(),
uptime: getUptime(),
kernel: getKernel(),
hostname: os.hostname(),
processes: (() => { try { return fs.readdirSync('/proc').filter(f => /^\d+$/.test(f)).length; } catch { return 0; } })(),
os: os.type() + ' ' + os.release(),
node: process.version,
timestamp: Date.now()
});
});
app.listen(PORT, () => {
console.log(`Server Dashboard running on port ${PORT}`);
});