-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
153 lines (128 loc) · 4.87 KB
/
index.js
File metadata and controls
153 lines (128 loc) · 4.87 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
require('dotenv').config();
const express = require('express');
const http = require('http');
const WebSocket = require('ws');
const { exec } = require('child_process');
const os = require('os');
const si = require('systeminformation');
const app = express();
const server = http.createServer(app);
const PORT = process.env.PORT || 7787;
const STATS_INTERVAL = process.env.STATS_INTERVAL || 1000;
const HISTORY_LENGTH = process.env.HISTORY_LENGTH || 60;
const NETWORK_INTERFACE = process.env.NETWORK_INTERFACE || null;
const PROCESSES_LIMIT = process.env.PROCESSES_LIMIT || 4;
const WS_PATH = process.env.WS_PATH || null;
let statsHistory = {
cpu: [],
memory: [],
network: { rx: [], tx: [] }
};
let prevNetworkStats = { rx_bytes: 0, tx_bytes: 0 };
app.use(express.static('public'));
async function collectStats() {
try {
const cpuUsage = await new Promise(resolve => {
exec("grep 'cpu ' /proc/stat", (err, stdout) => {
if (err) return resolve(0);
const values = stdout.split(/\s+/).slice(1).map(Number);
const total = values.reduce((a, b) => a + b, 0);
const idle = values[3];
resolve(Math.round((100 - (idle / total * 100)) * 10) / 10);
});
});
const memTotal = os.totalmem();
const memFree = os.freemem();
const memUsed = memTotal - memFree;
const memUsage = Math.round((memUsed / memTotal) * 100);
const topProcesses = await new Promise(resolve => {
exec(`ps -eo pid,comm,%cpu --sort=-%cpu | head -n ${PROCESSES_LIMIT}`, (err, stdout) => {
if (err) return resolve([]);
const processes = stdout.trim().split('\n').slice(1).map(line => {
const [pid, comm, cpu] = line.trim().split(/\s+/);
return { pid, name: comm, cpu: parseFloat(cpu) };
});
resolve(processes);
});
});
const netStats = await si.networkStats();
let currentInterface;
if (NETWORK_INTERFACE) {
currentInterface = netStats.find(intf => intf.iface === NETWORK_INTERFACE);
}
if (!currentInterface) {
currentInterface = netStats.find(intf => !intf.iface.startsWith('lo')) || netStats[0];
}
let rx_speed = 0;
let tx_speed = 0;
if (prevNetworkStats.rx_bytes > 0) {
const timeDiff = STATS_INTERVAL / 1000;
rx_speed = Math.round((currentInterface.rx_bytes - prevNetworkStats.rx_bytes) / timeDiff);
tx_speed = Math.round((currentInterface.tx_bytes - prevNetworkStats.tx_bytes) / timeDiff);
}
prevNetworkStats = {
rx_bytes: currentInterface.rx_bytes,
tx_bytes: currentInterface.tx_bytes
};
return {
timestamp: Date.now(),
cpu: cpuUsage,
memory: {
total: Math.round(memTotal / 1024 / 1024),
used: Math.round(memUsed / 1024 / 1024),
free: Math.round(memFree / 1024 / 1024),
usage: memUsage
},
processes: topProcesses,
network: {
rx: rx_speed,
tx: tx_speed
}
};
} catch (error) {
console.error('Error collecting stats:', error);
return null;
}
}
function updateHistory(stats) {
statsHistory.cpu.push(stats.cpu);
if (statsHistory.cpu.length > HISTORY_LENGTH) statsHistory.cpu.shift();
statsHistory.memory.push(stats.memory.usage);
if (statsHistory.memory.length > HISTORY_LENGTH) statsHistory.memory.shift();
statsHistory.network.rx.push(stats.network.rx);
statsHistory.network.tx.push(stats.network.tx);
if (statsHistory.network.rx.length > HISTORY_LENGTH) {
statsHistory.network.rx.shift();
statsHistory.network.tx.shift();
}
}
const wsOptions = WS_PATH ? { server, path: WS_PATH } : { server };
const wss = new WebSocket.Server(wsOptions);
wss.on('connection', (ws) => {
ws.send(JSON.stringify({
type: 'init',
history: statsHistory
}));
});
setInterval(async () => {
const stats = await collectStats();
if (!stats) return;
updateHistory(stats);
wss.clients.forEach(client => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify({
type: 'update',
stats: stats,
history: statsHistory
}));
}
});
}, STATS_INTERVAL);
server.listen(PORT, () => {
console.log(`Сервер запущен на http://localhost:${PORT}`);
if (WS_PATH) {
console.log(`Эндпоинт вебсокета: ws://localhost:${PORT}${WS_PATH}`);
} else {
console.log(`Эндпоинт вебсокета: ws://localhost:${PORT}`);
}
});