-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsystem_monitor.js
More file actions
280 lines (251 loc) Β· 8.2 KB
/
system_monitor.js
File metadata and controls
280 lines (251 loc) Β· 8.2 KB
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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
const express = require('express');
const { exec } = require('child_process');
const { promisify } = require('util');
const os = require('os');
const execAsync = promisify(exec);
const app = express();
const PORT = process.env.PORT || 8081;
// Get system RAM usage
async function getRamUsage() {
try {
const totalMem = os.totalmem();
const freeMem = os.freemem();
const usedMem = totalMem - freeMem;
const percentage = ((usedMem / totalMem) * 100).toFixed(1);
return {
success: true,
total: `${(totalMem / 1024 / 1024 / 1024).toFixed(1)}GB`,
used: `${(usedMem / 1024 / 1024 / 1024).toFixed(1)}GB`,
available: `${(freeMem / 1024 / 1024 / 1024).toFixed(1)}GB`,
percentage: percentage,
};
} catch (error) {
return { success: false, error: error.message };
}
}
// Get disk usage
async function getDiskUsage() {
try {
const result = await execAsync('df -h .');
const lines = result.stdout.trim().split('\n');
if (lines.length >= 2) {
const parts = lines[1].split(/\s+/);
if (parts.length >= 5) {
return {
success: true,
total: parts[1],
used: parts[2],
available: parts[3],
usage_percent: parts[4].replace('%', ''),
};
}
}
return { success: false, error: 'Could not parse disk usage' };
} catch (error) {
return { success: false, error: error.message };
}
}
// Get CPU usage
async function getCpuUsage() {
try {
const platform = os.platform();
console.log(`π System Monitor - Detected platform: ${platform}`);
let cpuUsage;
if (platform === 'darwin') {
// macOS
console.log('π System Monitor - Using macOS CPU monitoring...');
try {
const result = await execAsync(
"top -l 1 | grep 'CPU usage' | awk '{print $3}' | sed 's/%//'"
);
cpuUsage = parseFloat(result.stdout.trim());
console.log(
`π macOS top command result: ${result.stdout.trim()} -> ${cpuUsage}`
);
if (!isNaN(cpuUsage) && cpuUsage >= 0 && cpuUsage <= 100) {
return {
success: true,
usage: cpuUsage.toFixed(1),
usageType: 'percentage',
cores: os.cpus().length,
model: os.cpus()[0].model,
platform: platform,
};
}
} catch (error) {
console.log('β οΈ macOS CPU monitoring failed:', error.message);
}
} else if (platform === 'linux') {
// Linux/Ubuntu
console.log('π§ System Monitor - Using Linux CPU monitoring...');
// Method 1: Try using /proc/loadavg (most reliable)
try {
const loadAvgResult = await execAsync('cat /proc/loadavg');
const loadAvg = loadAvgResult.stdout.trim().split(' ')[0];
const cpuCount = os.cpus().length;
// Convert load average to CPU percentage (rough approximation)
// Load average of 1.0 = 100% CPU usage for a single core
const loadPercentage = (parseFloat(loadAvg) / cpuCount) * 100;
cpuUsage = Math.min(loadPercentage, 100); // Cap at 100%
console.log(
`π Load average: ${loadAvg}, CPU cores: ${cpuCount}, Estimated CPU: ${cpuUsage.toFixed(
1
)}%`
);
return {
success: true,
usage: cpuUsage.toFixed(1),
usageType: 'percentage',
cores: cpuCount,
model: os.cpus()[0].model,
platform: platform,
};
} catch (loadError) {
console.log(
'β οΈ Load average method failed, trying vmstat...',
loadError.message
);
// Method 2: Try vmstat
try {
const vmstatResult = await execAsync('vmstat 1 2 | tail -1');
const vmstatParts = vmstatResult.stdout.trim().split(/\s+/);
if (vmstatParts.length >= 15) {
const idle = parseFloat(vmstatParts[14]);
cpuUsage = 100 - idle;
console.log(
`π vmstat result: idle=${idle}%, cpu=${cpuUsage.toFixed(1)}%`
);
return {
success: true,
usage: cpuUsage.toFixed(1),
usageType: 'percentage',
cores: os.cpus().length,
model: os.cpus()[0].model,
platform: platform,
};
} else {
throw new Error('vmstat output format not recognized');
}
} catch (vmstatError) {
console.log(
'β οΈ vmstat method failed, trying top...',
vmstatError.message
);
// Method 3: Try top (if available)
try {
const topResult = await execAsync(
"top -bn1 | grep 'Cpu(s)' | awk '{print $2}' | sed 's/%us,//'"
);
cpuUsage = parseFloat(topResult.stdout.trim());
console.log(
`π top command result: ${topResult.stdout.trim()} -> ${cpuUsage}`
);
if (!isNaN(cpuUsage) && cpuUsage >= 0 && cpuUsage <= 100) {
return {
success: true,
usage: cpuUsage.toFixed(1),
usageType: 'percentage',
cores: os.cpus().length,
model: os.cpus()[0].model,
platform: platform,
};
}
} catch (topError) {
console.log(
'β οΈ top method failed, trying mpstat...',
topError.message
);
// Method 4: Try mpstat (if available)
try {
const mpstatResult = await execAsync(
"mpstat 1 1 | tail -1 | awk '{print 100-$NF}'"
);
cpuUsage = parseFloat(mpstatResult.stdout.trim());
console.log(
`π mpstat result: ${mpstatResult.stdout.trim()} -> ${cpuUsage}`
);
if (!isNaN(cpuUsage) && cpuUsage >= 0 && cpuUsage <= 100) {
return {
success: true,
usage: cpuUsage.toFixed(1),
usageType: 'percentage',
cores: os.cpus().length,
model: os.cpus()[0].model,
platform: platform,
};
}
} catch (mpstatError) {
console.log(
'β οΈ All CPU monitoring methods failed, using load average fallback',
mpstatError.message
);
}
}
}
}
} else {
// Other platforms - fallback to load average
console.log(
'π System Monitor - Using load average fallback for platform:',
platform
);
}
// Final fallback to os.loadavg() if all methods fail
console.log('π System Monitor - Using final load average fallback...');
const loadAvg = os.loadavg();
const cpuCount = os.cpus().length;
const loadPercentage = (loadAvg[0] / cpuCount) * 100;
cpuUsage = Math.min(loadPercentage, 100);
console.log(
`π Load average fallback: ${
loadAvg[0]
} / ${cpuCount} cores = ${cpuUsage.toFixed(1)}%`
);
return {
success: true,
usage: cpuUsage.toFixed(1),
usageType: 'percentage',
cores: cpuCount,
model: os.cpus()[0].model,
platform: platform,
};
} catch (error) {
console.log(`π₯ System Monitor - CPU usage error:`, error);
return { success: false, error: error.message };
}
}
// Main system resources endpoint
app.get('/system', async (req, res) => {
try {
const ram = await getRamUsage();
const disk = await getDiskUsage();
const cpu = await getCpuUsage();
res.json({
success: true,
timestamp: new Date().toISOString(),
ram,
disk,
cpu,
});
} catch (error) {
res.status(500).json({
success: false,
error: error.message,
});
}
});
// Health check endpoint
app.get('/health', (req, res) => {
res.json({
status: 'ok',
timestamp: new Date().toISOString(),
});
});
// Start server
app.listen(PORT, '0.0.0.0', () => {
console.log(`π§ System Monitor running on port ${PORT}`);
console.log(
`π System resources available at: http://localhost:${PORT}/system`
);
});
module.exports = { getRamUsage, getDiskUsage, getCpuUsage };