Example #1
0
module.exports.getSystemInfo = function (callback) {
  var sysInfo = {
    arch: os.arch(),
    cpus: os.cpus(),
    freemem: os.freemem(),
    loadavg: os.loadavg(),
    platform: os.platform(),
    release: os.release(),
    totalmem: os.totalmem(),
    type: os.type(),
    uptime: os.uptime()
  }
  callback(sysInfo)
}
Example #2
0
 setInterval(function() {
     
     //returns [0,0,0] on windows
     var load = os.loadavg();
     load1minGauge.set(load[0]);
     load5minGauge.set(load[1]);
     load15minGauge.set(load[2]);
     
     var free = os.freemem();
     var usedMem = os.totalmem() - free; 
     usedMemoryBytesGauge.set(usedMem);
     freeMemoryBytesGauge.set(free);
             
 }, 60000); //every 60 secs
Example #3
0
client.on('message', function(user, userID, channelID, message, rawEvent) {
	if (message === '!info.y') {
		var start = process.hrtime();
    var load = os.loadavg()
    var mem = os.freemem()
    var plat = os.platform()
    var totmem = os.totalmem()
    var sysup = os.uptime()
    var memfix = bytes(mem);

    var totmemfix = bytes(totmem);
    var child = require('child_process');
    child.exec('expr ' + '"' + "scale=0; " + sysup + "*1000" + '"' + ' | bc -l', function(error, stdout, stderr) {
    setTimeout(function() {
    var calcul = stdout.replace(/\\/g, '');
    var sysupfix = prettyMs(parseInt(calcul));
    var currentTime = Date.now();
	  var uptime = currentTime - startTime;
	  var upfinal = prettyMs(parseInt(uptime));
		var end = process.hrtime(start);
		var timee = prettyHrtime(end);
    client.sendMessage({
       to: channelID,
       message: '------------------' +
                '\n' + '## Uptime ## :' +
                '\n' + '------------------' +
                '\n' + '`> ' + upfinal + '`' +
                '\n' + '-------------------------' +
                '\n' + '## Load average ## :' +
                '\n' + '-------------------------' +
                '\n' + '`> ' + load + '`' +
                '\n' + '------------------------------' +
                '\n' + '## Total memory use ## :' +
                '\n' + '------------------------------' +
                '\n' + '`> ' + memfix + " / " + totmemfix + '`' +
                '\n' + "------------------" +
                '\n' + '## Platform ## :' +
                '\n' + '-------------------' +
                '\n' + '`> ' + plat + '`' +
                '\n' + '--------------------------' +
                '\n' + '## Uptime server ## :' +
                '\n' + '--------------------------' +
                '\n' + '`> ' + sysupfix + '`' +
								'\n' + '---------------------' +
								'\n' + '`>  Elapsed time : ' + timee + '`'
    });
    }, 200);
    });
  };
});
    return new Promise(function(resolve, reject) {

      const totalMemory = os.totalmem();

      if (totalMemory) {
        self.convertToGB(totalMemory)
          .then(result => resolve(result))
          .catch(err => reject(err));

      } else {
        reject(new Error('No valid total RAM data found!'));
      }

    });
    res.end = function () {
      res.end = end;

      end.apply(res, arguments);

      request.response = {};
      request.duration = Date.now() - start;

      if (req.route && req.route.path) {
        request.request.route = {
          path: req.route.path
        };
      }

      if (res.error) {
        request.error = {};

        Object.getOwnPropertyNames(res.error).forEach(function (key) {
          request.error[key] = res.error[key];
        });
      }

      request.os = {
        totalmem: os.totalmem(), // bytes
        freemem: os.freemem(), // bytes
        loadavg: os.loadavg() // array of 5, 10, and 15 min averages
      };

      request.process = {
        memory: process.memoryUsage() // bytes
      };

      config.whitelist.response.forEach(function (key) {
        request.response[key] = res[key];
      });

      if (client.indexExists) {
        log(request, config, client);
      } else {
        ensureIndexExists(config, client, function (error) {
          if (error) {
            return console.error(error);
          }

          client.indexExists = true;

          log(request, config, client);
        });
      }
    };
Example #6
0
 async.parallel(tasks, function (err, results) {
   if (err) return console.log(err);
   if (results.battery) clauses.push('battery: ' + results.battery.trim() + '%');
   if (results.temperature) clauses.push('CPU temperature: ' +
     (results.temperature.trim() / 1000) + '° C');
   var cpuLoad = os.loadavg()[1].toFixed(2);
   var memUse = (process.memoryUsage().rss / Math.pow(1000, 2)).toFixed(1) + ' MB';
   var memFree = (os.freemem() * 100 / os.totalmem()).toFixed(1) + '%';
   var nodeUptimeMs = Date.now() - self.bootTime;
   var nodeUptime = (nodeUptimeMs / 3600000).toFixed(2) + 'h';
   var osUptime = (os.uptime() / 3600).toFixed(2) + 'h';
   var format = clauses.join(', ');
   console.log(format, cpuLoad, memUse, memFree, nodeUptime, osUptime);
 });
function calculate() {
  const data = {};

  data.cpus = os.cpus();
  data.memory = os.freemem() / os.totalmem();
  data.type = os.type();
  data.platform = os.platform();
  data.uptime = uptime();
  data.release = os.release();
  data.hostname = os.hostname();
  data.port = global.__port;

  return data;
}
Example #8
0
	app.get('/api/info/os', auth.dev, function (req, res) {
		res.json({

			type: os.type(),
			platform: os.platform(),
			arch: os.arch(),
			release: os.release(),
			uptime: os.uptime(),
			loadavg: os.loadavg(),
			totalmem: os.totalmem(),
			freemem: os.freemem(),
			cpus: os.cpus()
		});
	});
Example #9
0
 process: (bot, msg) => {
   var memUsed = Math.round(process.memoryUsage().rss / 1024 / 1024);
   var totalMem = Math.round(os.totalmem() / 1024 / 1024);
   var percentUsed = Math.round((memUsed / totalMem) * 100);
   var toSend = [];
   toSend.push("```xl");
   toSend.push("Uptime: " + moment().fromNow(Math.round(bot.uptime / 1000)) + ".");
   toSend.push("Connected to " + bot.servers.length + " servers with " + bot.channels.length + " channels and " + bot.users.length + " users.");
   toSend.push("Memory Usage: " + memUsed + " MB (" + percentUsed + "%)");
   toSend.push("Running RuneCord v" + version);
   toSend.push("Commands this session: " + commandsProcessed + " (avg " + (commandsProcessed / (bot.uptime / (1000 * 60))).toFixed(2) + "/min)");
   toSend.push("```");
   bot.sendMessage(msg, toSend);
 }
Example #10
0
    function collector (err, data) {
        if (err) {
            return callback(err);
        }

        var statuses = JSON.parse(data.toString());
        response_obj.hostname = os.hostname();
        response_obj.node_version = process.version;
        response_obj.os_type = os.type();
        response_obj.os_release = os.release();
        response_obj.currentTime = Date.now();
        if (process.clusterStartTime) {
            //Show Restart Time only if Process has the field clusterStartTime
            //this attribute should be set by the cluster master process
            response_obj.cluster_start_time = process.clusterStartTime.getTime();
            response_obj.cluster_uptime = Math.round((new Date().getTime() - process.clusterStartTime.getTime()) / 1000);
        }
        response_obj.total_memory = os.totalmem();
        response_obj.free_memory = os.freemem();
        response_obj.os_loadavg = os.loadavg();
        response_obj.worker = [];

        response_obj.total_requests = 0;
        response_obj.total_kbs_transferred = 0;
        response_obj.total_kbs_out = 0;
        response_obj.total_rps = 0;
        Object.keys(statuses).forEach(function(pid) {
            response_obj.worker.push({
                "pid" : pid,
                "cpu" : statuses[pid].curr.cpu,
                "mem" : statuses[pid].curr.mem,
                "cpu_per_req" : statuses[pid].curr.cpuperreq,
                "jiffy_per_req" : statuses[pid].curr.jiffyperreq,
                "rps" : statuses[pid].curr.rps,
                "events" : statuses[pid].curr.events,
                "open_conns" : statuses[pid].curr.oconns,
                "open_requests" : statuses[pid].curr.oreqs,
                "total_requests" : statuses[pid].curr.reqstotal,
                "kbs_out" : statuses[pid].curr.kbs_out,
                "kbs_transferred" : statuses[pid].curr.kb_trans,
                "start_time" : statuses[pid].curr.utcstart * 1000 //convert sec in millis
            });
            response_obj.total_requests = response_obj.total_requests + statuses[pid].curr.reqstotal;
            response_obj.total_kbs_transferred = response_obj.total_kbs_transferred + statuses[pid].curr.kb_trans;
            response_obj.total_kbs_out = response_obj.total_kbs_out + statuses[pid].curr.kbs_out;
            response_obj.total_rps = response_obj.total_rps + statuses[pid].curr.rps;
        });

        callback(null, response_obj);
    }
Example #11
0
exports.getInternalMachineID = function() {
	// Build our machine ID off of hostname, memory, and CPU data
	var os = require('os');
	var cpus = os.cpus().map(function(cpu) {
		return cpu.model;
	});

	cpus.sort();

	var id = os.hostname() + os.totalmem() + cpus.join('');
	var hash = Crypto.createHash('md5');
	hash.update(id);
	return hash.digest('hex');
};
Example #12
0
exports.get = function(req, res) {
  var webinfo = {}
  var serverinfo = {
    name: os.type(),
    platform: os.platform(),
    loadavg: os.loadavg(),
    rss: (os.totalmem() - os.freemem()) / os.totalmem()
  }

  Promise.all([User.countAll(), Book.countAll(), Comment.countAll()])
    .then(function(results) {
      webinfo.userNum = results[0]
      webinfo.bookNum = results[1]
      webinfo.commentNum = results[2]
      res.status(200).jsonp({
        webInfo: webinfo,
        serverInfo: serverinfo
      })
    })
    .catch(function(err) {
      res.status(500).jsonp(null)
    })
}
Example #13
0
			ps(this.mid || process.pid, opts, function (err, result) {
				var now = Date.now();
				setImmediate(function(){
					this.loop.push(Date.now() - now);
				}.bind(this)); 

				if (err) {
					console.error(err);
				} else {
					this.cpu.push(result.cpu);
					this.memory.push(os.freemem() / os.totalmem());
					log.d('CPU %j \t Memory %j \t loop %j \t process %j', this.cpu.value.toFixed(2), this.memory.value.toFixed(2), this.loop.value.toFixed(2), result);
				}
			}.bind(this));
Example #14
0
 })(function () {
     var os = require("os");
     var details = {
         workerId: _workerId,
         environment: __appEnv,
         processName: process.title,
         versions: process.versions,
         architecture: process.arch,
         platform: process.platform,
         environmentVariables: process.env,
         pid: process.pid,
         features: process.features,
         debugPort: process.debugPort,
         listeningPort: _app.get('port'),
         nodeFilePath: process.execPath,
         processConfig: process.config,
         hostname: os.hostname(),
         uptime: os.uptime(),
         ram: {
             free: os.freemem(),
             total: os.totalmem()
         },
         cpus: os.cpus(),
         osType: {
             name: os.type(),
             release: os.release(),
             arch: os.arch()
         },
         networkInterfaces: os.networkInterfaces(),
         tempDir: os.tmpDir(),
         updated: new Date().getTime()
     };
     details = JSON.parse(JSON.stringify(details)); //sanitize
     ClusterWorker.update({workerId: _workerId}, {$set: details}, {upsert: true}, function (err) {
         if (err) log.error(err);
     });
     try {
         ClusterWorker.find({updated: {$lt: (new Date().getTime() - (1000 * 40))}}, function (err, objList) {
             objList.forEach(function (obj) {
                 ClusterWorker.remove({_id: obj._id}, function (err) {
                     if (err) log.error(err);
                     else globalEvent.emit("OnClusterWorkerFoundInactive", obj);
                 });
             });
         });
     } catch (c) {
         log.error(c);
     }
 }), 1000 * 30);
Example #15
0
xmpp.on('chat', function(from, message) {
    if (message.indexOf('reload') !== -1) {
        xmpp.send(from, pretext + 'Exiting on ' + os.hostname());
        process.exit();
    }

    if (message.indexOf('hello') !== -1) {
        xmpp.send(from, pretext + 'Hello from ' + os.hostname());
    }
    if (message.indexOf('version') !== -1) {
        xmpp.send(from, pretext  + 'WatcherBot ' + version);
    }

    if (message.indexOf('uptime') !== -1) {
        var loadavg = os.loadavg(),
         uptime = os.uptime(),
         upstring = '';
        var years = moment.duration(uptime,'seconds').years(),
         months = moment.duration(uptime,'seconds').months(),
         days = moment.duration(uptime,'seconds').days(),
         hours = moment.duration(uptime,'seconds').hours(),
         minutes = moment.duration(uptime,'seconds').minutes();
        if (years !== 0) upstring += years + ' years ';
        if (months !== 0) upstring += months + ' months ';
        if (days !== 0) upstring += days + ' days ';
        if (hours !== 0) upstring += hours + ' hours ';
        if (minutes !== 0) upstring += minutes + ' minutes ';
        xmpp.send(from, pretext + hostname + " " + upstring +
            '\n' + pretext + "loadavg: " + loadavg[0].toFixed(2) + " " + loadavg[1].toFixed(2) + " " + loadavg[2].toFixed(2) +
            '\n' + pretext + "mem: " + humanize.filesize(os.totalmem()) + "/" + humanize.filesize(os.freemem())
        );
    }

    if (message.indexOf('status') !== -1) {
        exec(config.statscmd + ' | grep -e "Services Ok" -e "Hosts Up" | sed "s/       / /g"', function(error, stdout, stderr) {
            var array1 = stdout.split("\n");
            for ( i = 0; i < array1.length; i++) {
                array1[i] = pretext + array1[i];
            }
            stdout = array1.join("\n");
            xmpp.send(from, stdout + config.baseurl + "/icinga/");
        });
    }

    if (message.indexOf('url') !== -1) {
        xmpp.send(from, pretext + config.baseurl);
    }

});
var action_get_status = function(req,res,next) {
	content = {};
	content.status = fs.readFileSync('isrunning','utf8')=="1"?"running":"stopped";
	if (content.status=="running") {
		content.uptime = new Date().getTime()/1000 - parseInt(fs.statSync('isrunning').mtime.getTime()/1000);
	} else {
		content.uptime = 0;
	}
	cpuLoad = process.execSync('wmic cpu get loadpercentage',{encoding:'utf8'});
	cpuLoad = (cpuLoad.split('\n'))[1];
	content.cpuLoad = parseInt(cpuLoad.substr(0,3));
	content.totalmem = os.totalmem();
	content.freemem = os.freemem();
	res.json(content);
}
Example #17
0
 AutoCollectPerformance.prototype._trackMemory = function () {
     var totalMem = os.totalmem();
     var freeMem = os.freemem();
     var usedMem = totalMem - freeMem;
     var percentUsedMem = usedMem / (totalMem || 1);
     var percentAvailableMem = freeMem / (totalMem || 1);
     this._client.trackMetric("Memory Used", usedMem);
     this._client.trackMetric("Memory Free", freeMem);
     this._client.trackMetric("Memory Total", totalMem);
     this._client.trackMetric("% Memory Used", percentUsedMem);
     this._client.trackMetric("% Memory Free", percentAvailableMem);
     // todo: remove this legacy counter once the UI updates (~june 2015)
     this._trackLegacyPerformance(PerfCounterType.AvailableMemory, freeMem);
     this._trackLegacyPerformance(PerfCounterType.PrivateBytes, usedMem);
 };
Example #18
0
function sendStartInfo(from)
{
	if(wxmpp.checkConnected())
	{
		var t = wxmpp.getConnection();
		var tag = new xmpp.Element('info', {board:boardType, uptime:os.uptime(), loadavg1:os.loadavg()[0],
			loadavg5:os.loadavg()[1], loadavg15:os.loadavg()[2], totalmem:os.totalmem(), freemem:os.freemem()});
		var cpus = os.cpus();	
		for(var i=0; i<cpus.length; i++)
		{
			tag.c('cpu', {model:cpus[i].model, speed:cpus[i].speed});
		}
		t.sendWyliodrin(from, tag);
	}
}
Example #19
0
	setInterval(function() {
		contador = contador + 1;
		self._agregarEstadistica();
		var cpu = self.obtenerUsoCPUMedioUltimoMinuto();
		var mensaje = (cpu == undefined) ? 'No disponible.' : parseInt(cpu*100) + '%';
		console.log('Uso medio CPU último minuto: ' + mensaje);
		if (contador % 60 == 0) {    // % significa 'módulo de contador/60'
			var resumen = new ResumenEstadisticas(
								self.id, new Date().getTime(),
								os.freemem(), os.totalmem(),
								cpu); // cpu es una variable local (-> no necesita el self)
			self._enviarResumen(resumen);  // el subrayado indica que es una función privada
		}
		
	}, 1000);
Example #20
0
const memory = () => {
	let l = newLogger('memory');
	let toGB = (val) => [(val / 1024 / 1024 / 1024).toFixed(1), 'GB'].join('');
	let heapTotal = process.memoryUsage().heapTotal;
	let heapUsed = process.memoryUsage().heapUsed;

	l.info({
		systemTotalMemory: toGB(os.totalmem()),
		systemFreeMemory: toGB(os.freemem()),
		processUsingMemory: toGB(process.memoryUsage().rss),
		heapTotal: toGB(heapTotal),
		heapUsed: toGB(heapUsed),
		heapFree: toGB(heapTotal - heapUsed),
	});
};
	var onMonitor = function () {
		// get system informations from nodejs api
		self.data['mem'] = [os.freemem(), os.totalmem()];
		self.data['load'] = os.loadavg();

		// get uptime from /proc/uptime, os.uptimes() has a bug atm
		self.data['uptime'] = [];
		exec('awk \'{print $1}\' /proc/uptime', function (error, stdout, stderr) {
			if(error != null) {
				console.log(error);
				return false;
			}
			self.data['uptime'] = parseInt(stdout.split('\n')[0]);
		});
	};
Example #22
0
  norris.get(function(facts) {
    var info = {
      'agent_version': version.toString(),
      'node_version': process.version,
      'api_version': http.CURRENT_API_VERSION,
      'hostname': facts.hostname,
      'architecture': facts.arch,
      'os': os.release(),
      'memory': os.totalmem(),
      'os_uptime': os.uptime(),
      'agent_uptime': uptime
    };

    httputil.returnJson(res, 200, info);
  });
Example #23
0
	osutils.cpuUsage((v)=>{
		let sysinfo = {
			'hostname'   : os.hostname(),
			'systemtype' : os.type(),
			//'release'    : os.release(),
			//'uptime'     : os.uptime(),
			//'loadavg'    : os.loadavg(),
			'totalmem'   : os.totalmem(),
			'freemem'    : os.freemem(),
			//'cpus'       : os.cpus(),
			'cpuUsage'   : v,
			'process'    : process.memoryUsage()
		}
		res.send(sysinfo)
	})
Example #24
0
 God.getMonitorData(env, function(err, processes) {
   cb(err, {
     system: {
       hostname: os.hostname(),
       uptime: os.uptime(),
       cpus: os.cpus(),
       load: os.loadavg(),
       memory: {
         free: os.freemem(),
         total: os.totalmem()
       }
     },
     processes: processes
   });
 });
function getStats(master, socket) {
    master.hostname = os.hostname();
    master.os = os.type() + ' ' + os.release();
    master.averageLoad = os.loadavg().map(
                    function (n) {
                        return n.toFixed(2);
                    }).join(' ');
    master.coresUsed = master.noWorkers + ' of ' + os.cpus().length;
    master.memoryUsageAtBoot = misc.forMemoryNum(master.freemem) + ' of ' +
                    misc.forMemoryNum(master.totalmem);
    master.totalMem = os.totalmem().toFixed(3);
    master.currentMemoryUsage = (os.totalmem() - os.freemem()) / 1024000;
    master.hostCpu = (_.reduce(os.cpus(), function (memo, cpu) {
                    return memo + (cpu.times.user /
                        (cpu.times.user + cpu.times.nice +
                            cpu.times.sys + cpu.times.idle + cpu.times.irq));
                }, 0) * 100 / os.cpus().length).toFixed(2);

    if(socket) {
        master.address = socket.address();
    }

    return {master: master};
}
Example #26
0
exports.status = function () {
  return {
    sourceVersion: SOURCE_VERSION,
    configVersion: CONFIG_VERSION,
    apiKeysVersion: API_KEYS_VERSION,
    host: os.hostname(),
    uptime: Math.floor((Date.now() - TIME_STARTED) / 1000),
    os: {
      uptime: os.uptime(),
      loadavg: os.loadavg(),
      totalmem: os.totalmem(),
      freemem: os.freemem()
    }
  };
};
Example #27
0
(function() {
	const os = require('os');

	console.log('arch: ' + os.arch());
	console.log('free: ' + os.freemem());
	console.log('total: ' + os.totalmem());
	console.log( 'platform: ' + os.platform() );
	console.log( 'release: ' + os.release() );
	console.log( 'os type: ' + os.type() );
	console.log( 'uptime: ' + os.uptime() );

	console.log('os.cpus()');
	//dump(os.cpus());
	console.log(os.cpus());
})();
Example #28
0
 initLogs: function(appVersion) {
     var ifaces = os.networkInterfaces();
     var memories = os.totalmem() / 1024 / 1024 / 1024;
     var freeMemories = os.freemem() / 1024 / 1024 / 1024;
     this.info("Launching Application: " + AppName());
     this.info("Network Interfaces", ifaces);
     this.info("Operating System", {
         'Release': os.release(),
         'Type': os.type(),
         'Arch': os.arch(),
         'LoadAvg': os.loadavg(),
         'Total Memory': memories + 'GB',
         'Free Memory': freeMemories + 'GB',
         'CPUs': os.cpus().length
     });
 }
Example #29
0
worker.addFunction("statOS", function(job) {
  var retval = {
    name: os.type(),
    platform: os.platform(),
    arch: os.arch(),
    release: os.release(),
    uptime: os.uptime(),
    load: os.loadavg(),
    totalMemory: os.totalmem(),
    freeMemory: os.freemem(),
    cpus: os.cpus(),
    networkInterfaces: os.networkInterfaces(),

  }
  job.workComplete(JSON.stringify({result: retval}));
});
Example #30
0
Filter.prototype.monitoring = function(processes) {
  if (!processes) return null;
  var self = this;
  var filter_procs = {};

  processes.forEach(function(proc) {
    filter_procs[self.getProcessID(proc.pm2_env.name,proc.pm2_env.pm_id)] = [proc.monit.cpu, proc.monit.memory];
  });

  return {
    loadavg   : os.loadavg(),
    total_mem : os.totalmem(),
    free_mem  : os.freemem(),
    processes : filter_procs
  };
};