-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.mjs
249 lines (208 loc) · 6.59 KB
/
server.mjs
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
import fs from 'fs';
import http from 'http';
import { exec } from 'child_process';
import { EventEmitter } from 'events';
import express from 'express';
import { Server as SocketIOServer } from 'socket.io';
import osUtils from 'node-os-utils';
const PORT = process.env.PORT || 3000;
class Server {
constructor() {
this.app = express();
this.app.use(express.static('public'));
this.server = http.createServer(this.app);
this.server.listen(PORT, () => {
console.log(`Server listening on http://0.0.0.0:${PORT}`);
});
this.io = new SocketIOServer(this.server);
this.io.on('connection', () => {
this.networkMonitor.logNetworkStats();
this.storageMonitor.logStorageStats();
this.systemMonitor.logSystemStats();
});
this.networkMonitor = new NetworkMonitor('eth0', 1000 / 60); // 60fps
this.networkMonitor.start();
this.networkMonitor.on('stats', ({ rxSpeed, txSpeed }) => {
// console.log(`RX Speed: ${rxSpeed.toFixed(2)} Mbps | TX Speed: ${txSpeed.toFixed(2)} Mbps`);
this.io.emit('network', { rxSpeed, txSpeed });
});
this.storageMonitor = new StorageMonitor();
this.storageMonitor.start();
this.storageMonitor.on('stats', ({ disks }) => {
this.io.emit('storage', { disks });
});
this.systemMonitor = new SystemMonitor();
this.systemMonitor.start();
this.systemMonitor.on('cpu', ({ percentage }) => {
this.io.emit('cpu', { percentage });
});
this.systemMonitor.on('mem', ({ total, used, percentage }) => {
this.io.emit('mem', { total, used, percentage });
});
this.systemMonitor.on('temperature', ({ temperature }) => {
this.io.emit('temperature', { temperature });
});
this.systemMonitor.on('frequency', ({ frequency }) => {
this.io.emit('frequency', { frequency });
});
}
}
class NetworkMonitor extends EventEmitter {
constructor(interfaceName, intervalMs = 100) {
super();
this.interfaceName = interfaceName;
this.intervalMs = intervalMs;
this.previousStats = null;
this.intervalId = null;
}
// Helper function to read network stats from /proc/net/dev
readNetworkStats() {
return new Promise((resolve, reject) => {
fs.readFile('/proc/net/dev', 'utf8', (err, data) => {
if (err) {
reject(`Error reading /proc/net/dev: ${err}`);
return;
}
const lines = data.trim().split('\n');
const stats = {};
// Parse each network interface
lines.slice(2).forEach((line) => {
const [interfaceName, statsData] = line.trim().split(/:(.+)/);
const statsArray = statsData.trim().split(/\s+/);
const rxBytes = parseInt(statsArray[0]);
const txBytes = parseInt(statsArray[8]);
stats[interfaceName.trim()] = { rxBytes, txBytes };
});
resolve(stats);
});
});
}
// Method to calculate and emit network speed events
async logNetworkStats() {
try {
const currentStats = await this.readNetworkStats();
const iface = this.interfaceName;
if (this.previousStats && this.previousStats[iface] && currentStats[iface]) {
const rxDiff = currentStats[iface].rxBytes - this.previousStats[iface].rxBytes;
const txDiff = currentStats[iface].txBytes - this.previousStats[iface].txBytes;
// Calculate speed in Mbps, accounting for the interval
const rxSpeedMbps = (rxDiff * 8) / (1024 * 1024) * (1000 / this.intervalMs);
const txSpeedMbps = (txDiff * 8) / (1024 * 1024) * (1000 / this.intervalMs);
// Emit events with speed data
this.emit('stats', {
rxSpeed: rxSpeedMbps,
txSpeed: txSpeedMbps,
});
}
this.previousStats = currentStats;
} catch (error) {
console.error(error);
}
}
// Method to start monitoring
start() {
if (!this.intervalId) {
this.intervalId = setInterval(() => this.logNetworkStats(), this.intervalMs);
}
}
// Method to stop monitoring
stop() {
if (this.intervalId) {
clearInterval(this.intervalId);
this.intervalId = null;
}
}
}
class StorageMonitor extends EventEmitter {
constructor() {
super();
this.intervalId = null;
this.intervalMs = 1000 * 60;
}
// Method to start monitoring
start() {
if (!this.intervalId) {
this.intervalId = setInterval(() => this.logStorageStats(), this.intervalMs);
}
}
// Method to stop monitoring
stop() {
if (this.intervalId) {
clearInterval(this.intervalId);
this.intervalId = null;
}
}
logStorageStats() {
Promise.resolve().then(async () => {
const disks = await new Promise((resolve, reject) => {
exec('df -h', (err, stdout, stderr) => {
if (err) {
return reject(err);
}
const lines = stdout.trim().split('\n');
const headers = lines[0].split(/\s+/);
const disks = lines.slice(1).map(line => {
const parts = line.split(/\s+/);
return {
filesystem: parts[0],
size: parts[1],
used: parts[2],
available: parts[3],
usePercent: parts[4],
mountedOn: parts[5]
};
});
resolve(disks);
});
});
this.emit('stats', { disks });
});
}
}
class SystemMonitor extends EventEmitter {
constructor() {
super();
this.intervalId = null;
this.intervalMs = 1000;
}
start() {
if (!this.intervalId) {
this.intervalId = setInterval(() => this.logSystemStats(), this.intervalMs);
}
}
stop() {
if (this.intervalId) {
clearInterval(this.intervalId);
this.intervalId = null;
}
}
logSystemStats() {
osUtils.cpu.usage(this.intervalMs).then(percentage => {
this.emit('cpu', { percentage });
});
osUtils.mem.info().then(info => {
this.emit('mem', {
total: info.totalMemMb,
used: info.usedMemMb,
percentage: info.usedMemPercentage,
});
});
exec('vcgencmd measure_temp', (err, stdout, stderr) => {
if (err) {
console.error(`Error getting CPU temperature: ${err}`);
return;
}
const temperature = parseFloat(stdout.split('=')[1]); // in Celsius
this.emit('temperature', { temperature });
});
exec('vcgencmd measure_clock arm', (err, stdout, stderr) => {
if (err) {
console.error(`Error getting CPU frequency: ${err}`);
return;
}
const frequency = parseFloat(stdout.split('=')[1]); // in Hz
this.emit('frequency', { frequency });
});
}
}
export default new Server();