File size: 4,998 Bytes
b841799
 
 
 
54dc52b
b841799
 
 
 
 
 
54dc52b
 
 
 
 
 
 
 
 
 
 
 
b841799
 
54dc52b
 
 
 
 
 
b841799
 
54dc52b
 
 
b841799
54dc52b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b841799
54dc52b
 
b841799
54dc52b
b841799
54dc52b
 
b841799
 
 
 
 
 
 
 
54dc52b
b841799
 
 
54dc52b
 
b841799
54dc52b
b841799
54dc52b
 
 
 
 
 
b841799
 
 
 
 
 
54dc52b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b841799
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54dc52b
b841799
54dc52b
b841799
 
 
 
 
 
 
 
 
 
 
54dc52b
 
b841799
 
 
 
 
 
54dc52b
b841799
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
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}`);
});