1
0
mirror of https://github.com/yldio/copilot.git synced 2024-12-01 23:50:06 +02:00
copilot/spikes/graphs-matrix/chartjs/server/metric.js

68 lines
1.2 KiB
JavaScript
Raw Normal View History

2016-11-11 19:56:42 +02:00
const async = require('async');
const disk = require('diskusage');
const os = require('os');
2016-11-09 15:58:10 +02:00
const cdm = {};
2016-11-11 19:56:42 +02:00
const getCPU = (fn) => {
return fn(null, {
user: os.cpus().reduce((sum, cpu) => sum + cpu.times.user, 0),
sys: os.cpus().reduce((sum, cpu) => sum + cpu.times.sys, 0)
});
};
const getMem = (fn) => {
const free = os.freemem();
const total = os.totalmem();
const using = total - free;
const perc = (using / total) * 100;
return fn(null, {
used: perc
});
};
const getDisk = (fn) => {
disk.check('/', fn);
};
const getStats = (fn) => {
async.parallel({
cpu: getCPU,
mem: getMem,
disk: getDisk
}, fn);
};
2016-11-09 15:58:10 +02:00
module.exports = (server) => ({
on: (id) => {
console.log('on', cdm[id]);
if (cdm[id] && (cdm[id].sockets > 0)) {
cdm[id].sockets +=1;
return;
}
let messageId = 0;
const interval = setInterval(() => {
console.log(`publishing /stats/${id}`);
2016-11-11 19:56:42 +02:00
getStats((err, stats) => {
server.publish(`/stats/${id}`, {
when: new Date().getTime(),
stats
});
2016-11-09 15:58:10 +02:00
});
2016-11-11 19:56:42 +02:00
}, 1000);
2016-11-09 15:58:10 +02:00
cdm[id] = {
interval,
sockets: 1
};
},
off: (id) => {
if (!(cdm[id].sockets -= 1)) {
clearInterval(cdm[id].interval);
}
}
});