statistics.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. var os = require('os');
  2. (function () {
  3. // vars
  4. stats_data = {};
  5. stats_request_ip_list = [];
  6. stats_request_count = 0;
  7. stats_hw_cpu_last = 0;
  8. stats_hw_ram_last = 0;
  9. // methods
  10. stats_start = function() {
  11. setInterval( () => {
  12. // get cpu results for next tick
  13. stats_cpuUsage( ( cpu_perc ) =>
  14. {
  15. var ram_total = os.totalmem();
  16. var ram_free = os.freemem();
  17. stats_hw_cpu_last = cpu_perc;
  18. stats_hw_ram_last = ( ram_total - ram_free ) / ram_total;
  19. } );
  20. // save state
  21. stats_data = {
  22. time : Date.now() ,
  23. cpu : Math.round( stats_hw_cpu_last * 10 ) / 10,
  24. ram : Math.round( stats_hw_ram_last * 1000 ) / 10,
  25. connections : stats_request_ip_list.length,
  26. requestsCount : stats_request_count
  27. };
  28. } , 1000 );
  29. };
  30. stats_reset = function() {
  31. stats_request_ip_list = [];
  32. stats_request_count = 0;
  33. };
  34. //
  35. stats_RecordRequest = function( req ) {
  36. stats_request_count ++ ;
  37. if( stats_request_ip_list.indexOf( req.ip ) == -1 ) stats_request_ip_list.push( req.ip );
  38. }
  39. /**
  40. * @description Measure the CPU usage calculated between two different CPU usage samples
  41. * @param {function} cb A callback function the result is passed to
  42. * @param {number} [core=-1] The CPU core index to measure. When is not greater than -1 then it is "averaged" for all CPU cores.
  43. * @param {number} [sampleMs=1000] The number of milliseconds between the CPU usage samples
  44. */
  45. stats_cpuUsage = function(cb, core, sampleMs) {
  46. // https://stackoverflow.com/a/65952194/2496170
  47. var deltaUsed;
  48. var deltaIdle;
  49. var timesKeys = ["user", "nice", "sys", "irq"];
  50. var allCores = null === core || !(core > -1);
  51. var byCore = (cpu, i) => allCores || core === i;
  52. var bySampleKey = (sample, key) => sample.filter(byCore).reduce((sum, cpu) => sum + cpu.times[key], 0);
  53. var sample0 = os.cpus();
  54. setTimeout(function() {
  55. var sample1 = os.cpus();
  56. deltaUsed = timesKeys.reduce(
  57. (diff, key) => diff + bySampleKey(sample1, key) - bySampleKey(sample0, key), 0);
  58. deltaIdle = bySampleKey(sample1, "idle") - bySampleKey(sample0, "idle");
  59. if ("function" === typeof cb) cb(100 * (deltaUsed / (deltaUsed + deltaIdle)));
  60. }, sampleMs || 1000);
  61. }
  62. //
  63. })();