jormungandr-bite/src/daemons/server-stats.ts

78 lines
1.5 KiB
TypeScript
Raw Normal View History

2017-06-08 10:03:54 -06:00
import * as os from 'os';
2018-07-27 02:58:19 -06:00
import * as sysUtils from 'systeminformation';
2017-06-08 10:03:54 -06:00
import * as diskusage from 'diskusage';
2018-08-13 17:21:25 -06:00
import * as Deque from 'double-ended-queue';
2017-06-08 10:03:54 -06:00
import Xev from 'xev';
2018-07-27 03:42:58 -06:00
const osUtils = require('os-utils');
2017-06-08 10:03:54 -06:00
const ev = new Xev();
2018-06-10 15:48:25 -06:00
const interval = 1000;
2017-06-08 10:03:54 -06:00
/**
2018-06-08 13:14:26 -06:00
* Report server stats regularly
2017-06-08 10:03:54 -06:00
*/
export default function() {
2018-08-13 17:21:25 -06:00
const log = new Deque<any>();
ev.on('requestServerStatsLog', id => {
2018-08-13 16:49:59 -06:00
ev.emit('serverStatsLog:' + id, log.toArray());
});
2018-06-10 15:48:25 -06:00
async function tick() {
2018-07-27 02:43:04 -06:00
const cpu = await cpuUsage();
2018-07-27 03:18:05 -06:00
const usedmem = await usedMem();
const totalmem = await totalMem();
2018-07-27 02:43:04 -06:00
const disk = diskusage.checkSync(os.platform() == 'win32' ? 'c:' : '/');
const stats = {
cpu_usage: cpu,
mem: {
total: totalmem,
2018-07-27 03:18:05 -06:00
used: usedmem
},
disk,
os_uptime: os.uptime(),
process_uptime: process.uptime()
};
ev.emit('serverStats', stats);
log.push(stats);
2018-08-15 05:20:46 -06:00
if (log.length > 50) log.shift();
2018-06-10 15:48:25 -06:00
}
tick();
setInterval(tick, interval);
2017-06-08 10:03:54 -06:00
}
// CPU STAT
2018-07-27 03:42:58 -06:00
function cpuUsage() {
return new Promise((res, rej) => {
osUtils.cpuUsage((cpuUsage: number) => {
res(cpuUsage);
});
});
}
2018-07-27 02:43:04 -06:00
// MEMORY(excl buffer + cache) STAT
2018-07-27 03:18:05 -06:00
async function usedMem() {
2018-07-27 02:43:04 -06:00
try {
const data = await sysUtils.mem();
return data.active;
} catch (error) {
console.error(error);
2018-07-27 02:51:40 -06:00
throw error;
2018-07-27 02:43:04 -06:00
}
}
// TOTAL MEMORY STAT
async function totalMem() {
2018-07-27 02:43:04 -06:00
try {
const data = await sysUtils.mem();
return data.total;
} catch (error) {
console.error(error);
2018-07-27 02:51:40 -06:00
throw error;
2018-07-27 02:43:04 -06:00
}
}