1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071 |
- var os = require('os');
- (function () {
- // vars
- stats_data = {};
- stats_request_ip_list = [];
- stats_request_count = 0;
- stats_hw_cpu_last = 0;
- stats_hw_ram_last = 0;
- // methods
- stats_start = function() {
- setInterval( () => {
- // get cpu results for next tick
- stats_cpuUsage( ( cpu_perc ) =>
- {
- var ram_total = os.totalmem();
- var ram_free = os.freemem();
- stats_hw_cpu_last = cpu_perc;
- stats_hw_ram_last = ( ram_total - ram_free ) / ram_total;
- } );
- // save state
- stats_data = {
- time : Date.now() ,
- cpu : Math.round( stats_hw_cpu_last * 10 ) / 10,
- ram : Math.round( stats_hw_ram_last * 1000 ) / 10,
- connections : stats_request_ip_list.length,
- requestsCount : stats_request_count
- };
- } , 1000 );
- };
- stats_reset = function() {
- stats_request_ip_list = [];
- stats_request_count = 0;
- };
- //
- stats_RecordRequest = function( req ) {
- stats_request_count ++ ;
- if( stats_request_ip_list.indexOf( req.ip ) == -1 ) stats_request_ip_list.push( req.ip );
- }
- /**
- * @description Measure the CPU usage calculated between two different CPU usage samples
- * @param {function} cb A callback function the result is passed to
- * @param {number} [core=-1] The CPU core index to measure. When is not greater than -1 then it is "averaged" for all CPU cores.
- * @param {number} [sampleMs=1000] The number of milliseconds between the CPU usage samples
- */
- stats_cpuUsage = function(cb, core, sampleMs) {
- // https://stackoverflow.com/a/65952194/2496170
- var deltaUsed;
- var deltaIdle;
- var timesKeys = ["user", "nice", "sys", "irq"];
- var allCores = null === core || !(core > -1);
- var byCore = (cpu, i) => allCores || core === i;
- var bySampleKey = (sample, key) => sample.filter(byCore).reduce((sum, cpu) => sum + cpu.times[key], 0);
- var sample0 = os.cpus();
- setTimeout(function() {
- var sample1 = os.cpus();
- deltaUsed = timesKeys.reduce(
- (diff, key) => diff + bySampleKey(sample1, key) - bySampleKey(sample0, key), 0);
- deltaIdle = bySampleKey(sample1, "idle") - bySampleKey(sample0, "idle");
- if ("function" === typeof cb) cb(100 * (deltaUsed / (deltaUsed + deltaIdle)));
- }, sampleMs || 1000);
- }
- //
- })();
|