firefish/packages/backend/src/daemons/server-stats.ts

85 lines
1.8 KiB
TypeScript
Raw Normal View History

2023-01-13 04:40:33 +00:00
import si from "systeminformation";
import Xev from "xev";
import * as osUtils from "os-utils";
import { fetchMeta } from "backend-rs";
2017-06-08 16:03:54 +00:00
2022-04-17 05:42:13 +00:00
const ev = new Xev();
2017-06-08 16:03:54 +00:00
const interval = 2000;
2018-06-10 21:48:25 +00:00
2021-01-03 13:38:32 +00:00
const roundCpu = (num: number) => Math.round(num * 1000) / 1000;
const round = (num: number) => Math.round(num * 10) / 10;
2017-06-08 16:03:54 +00:00
/**
2018-06-08 19:14:26 +00:00
* Report server stats regularly
2017-06-08 16:03:54 +00:00
*/
export default async function () {
const log = [] as any[];
2023-01-13 04:40:33 +00:00
ev.on("requestServerStatsLog", (x) => {
ev.emit(`serverStatsLog:${x.id}`, log.slice(0, x.length || 50));
});
const meta = await fetchMeta(true);
if (!meta.enableServerMachineStats) return;
2018-06-10 21:48:25 +00:00
async function tick() {
2018-07-27 08:43:04 +00:00
const cpu = await cpuUsage();
const memStats = await mem();
const netStats = await net();
const fsStats = await fs();
const stats = {
2021-01-03 13:38:32 +00:00
cpu: roundCpu(cpu),
mem: {
2021-02-26 16:29:29 +00:00
used: round(memStats.used - memStats.buffers - memStats.cached),
2021-01-03 13:38:32 +00:00
active: round(memStats.active),
2023-07-23 10:14:33 +00:00
total: round(memStats.total),
},
net: {
2021-01-03 13:38:32 +00:00
rx: round(Math.max(0, netStats.rx_sec)),
tx: round(Math.max(0, netStats.tx_sec)),
},
fs: {
2022-02-19 05:28:08 +00:00
r: round(Math.max(0, fsStats.rIO_sec ?? 0)),
w: round(Math.max(0, fsStats.wIO_sec ?? 0)),
2021-12-09 14:58:30 +00:00
},
};
2023-01-13 04:40:33 +00:00
ev.emit("serverStats", stats);
log.unshift(stats);
if (log.length > 200) log.pop();
2018-06-10 21:48:25 +00:00
}
tick();
setInterval(tick, interval);
2017-06-08 16:03:54 +00:00
}
// CPU STAT
2022-02-19 05:28:08 +00:00
function cpuUsage(): Promise<number> {
2018-07-27 09:42:58 +00:00
return new Promise((res, rej) => {
2022-02-19 05:28:08 +00:00
osUtils.cpuUsage((cpuUsage) => {
2018-07-27 09:42:58 +00:00
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 }));
2021-03-19 14:26:44 +00:00
return data || { rIO_sec: 0, wIO_sec: 0 };
2018-07-27 08:43:04 +00:00
}