summaryrefslogtreecommitdiff
path: root/src/daemons/server-stats.ts
blob: 88df421ba007033cf0f9157896873c67f3748176 (plain)
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
import * as si from 'systeminformation';
import Xev from 'xev';
import * as osUtils from 'os-utils';

const ev = new Xev();

const interval = 2000;

/**
 * Report server stats regularly
 */
export default function() {
	const log = [] as any[];

	ev.on('requestServerStatsLog', x => {
		ev.emit(`serverStatsLog:${x.id}`, log.slice(0, x.length || 50));
	});

	async function tick() {
		const cpu = await cpuUsage();
		const memStats = await mem();
		const netStats = await net();
		const fsStats = await fs();

		const stats = {
			cpu: cpu,
			mem: {
				used: memStats.used,
				active: memStats.active,
			},
			net: {
				rx: Math.max(0, netStats.rx_sec),
				tx: Math.max(0, netStats.tx_sec),
			},
			fs: {
				r: Math.max(0, fsStats.rIO_sec),
				w: Math.max(0, fsStats.wIO_sec),
			}
		};
		ev.emit('serverStats', stats);
		log.unshift(stats);
		if (log.length > 200) log.pop();
	}

	tick();

	setInterval(tick, interval);
}

// CPU STAT
function cpuUsage() {
	return new Promise((res, rej) => {
		osUtils.cpuUsage((cpuUsage: number) => {
			res(cpuUsage);
		});
	});
}

// MEMORY STAT
async function mem() {
	const data = await si.mem();
	return data;
}

// NETWORK STAT
async function net() {
	const iface = await si.networkInterfaceDefault();
	const data = await si.networkStats(iface);
	return data[0];
}

// FS STAT
async function fs() {
	const data = await si.disksIO().catch(() => ({ rIO_sec: 0, wIO_sec: 0 }));
	return data;
}