yumechi-no-kuni/src/daemons/server-stats.ts

80 lines
1.6 KiB
TypeScript
Raw Normal View History

import * as si from 'systeminformation';
2017-06-08 11:03:54 -05:00
import Xev from 'xev';
import * as osUtils from 'os-utils';
2017-06-08 11:03:54 -05:00
const ev = new Xev();
const interval = 2000;
2018-06-10 16:48:25 -05:00
2021-01-03 07:38:32 -06:00
const roundCpu = (num: number) => Math.round(num * 1000) / 1000;
const round = (num: number) => Math.round(num * 10) / 10;
2017-06-08 11:03:54 -05:00
/**
2018-06-08 14:14:26 -05:00
* Report server stats regularly
2017-06-08 11:03:54 -05:00
*/
export default function() {
const log = [] as any[];
ev.on('requestServerStatsLog', x => {
ev.emit(`serverStatsLog:${x.id}`, log.slice(0, x.length || 50));
});
2018-06-10 16:48:25 -05:00
async function tick() {
2018-07-27 03:43:04 -05:00
const cpu = await cpuUsage();
const memStats = await mem();
const netStats = await net();
const fsStats = await fs();
const stats = {
2021-01-03 07:38:32 -06:00
cpu: roundCpu(cpu),
mem: {
2021-01-03 07:38:32 -06:00
used: round(memStats.used),
active: round(memStats.active),
},
net: {
2021-01-03 07:38:32 -06:00
rx: round(Math.max(0, netStats.rx_sec)),
tx: round(Math.max(0, netStats.tx_sec)),
},
fs: {
2021-01-03 07:38:32 -06:00
r: round(Math.max(0, fsStats.rIO_sec)),
w: round(Math.max(0, fsStats.wIO_sec)),
}
};
ev.emit('serverStats', stats);
log.unshift(stats);
if (log.length > 200) log.pop();
2018-06-10 16:48:25 -05:00
}
tick();
setInterval(tick, interval);
2017-06-08 11:03:54 -05:00
}
// CPU STAT
2018-07-27 04:42:58 -05:00
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;
2018-07-27 03:43:04 -05:00
}