Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 'strict';
- var os = require('os');
- var spawn = require("child_process").spawn;
- var cpuStats = require('cpu-stats');
- var async = require('async');
- module.exports = function(socketManager, config)
- {
- return new betterOS(socketManager, config);
- }
- function betterOS(socketManager, config)
- {
- var self = this;
- self.sender = socketManager.sender;
- self.config = config;
- self.usageHistories = {
- mem: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
- cpu: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
- };
- socketManager.receiver.registerHandler('getUsageHistory', function (data)
- {
- this.reply('usageHistory', {
- mem: self.usageHistories.mem.reverse(),
- cpu: self.usageHistories.cpu.reverse()
- });
- });
- self.runUsages();
- }
- betterOS.prototype.runUsages = function()
- {
- var self = this;
- async.parallel([
- function (callback)
- {
- self.usedMem(function (usedmem)
- {
- if (self.usageHistories.mem.unshift(usedmem) > 20)
- {
- self.usageHistories.mem.splice(20);
- }
- callback();
- });
- },
- function (callback)
- {
- self.usedCpu(function (usage)
- {
- if (self.usageHistories.cpu.unshift(usage) > 20)
- {
- self.usageHistories.cpu.splice(20);
- }
- callback();
- });
- }
- ], function (err)
- {
- setTimeout(function() { self.runUsages() }, 5000);
- if (err)
- {
- console.log(err);
- return;
- }
- self.sender.broadcast('memoryUsage', {used: self.usageHistories.mem[0]}, 'usages');
- self.sender.broadcast('cpuUsage', {usage: self.usageHistories.cpu[0]}, 'usages');
- });
- }
- betterOS.prototype.usedMem = function(callback)
- {
- if (process.platform === "linux")
- {
- var prc = spawn("free", []);
- prc.stdout.on("data", function (data)
- {
- var lines = data.toString().split(/\n/g),
- line = lines[1].split(/\s+/),
- total = parseInt(line[1], 10),
- used = parseInt(line[2], 10);
- callback(used / total);
- });
- }
- else
- {
- var totalmem = os.totalmem();
- var freemem = os.freemem();
- callback((totalmem - freemem) / totalmem);
- }
- };
- betterOS.prototype.usedCpu = function(callback)
- {
- cpuStats(500, function (err, result)
- {
- var usages = [];
- for (var i in result)
- {
- //noinspection JSUnfilteredForInLoop
- var t = result[i];
- usages.push(t.cpu / 100);
- }
- callback(usages.reduce(function (a, b)
- {
- return a + b;
- }) / usages.length);
- })
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement