diff options
author | Tuowen Zhao <ztuowen@gmail.com> | 2016-06-25 22:01:34 -0600 |
---|---|---|
committer | Tuowen Zhao <ztuowen@gmail.com> | 2016-06-25 22:01:34 -0600 |
commit | d50bf206dea24e223ca57f92ec28daf2b6bbad37 (patch) | |
tree | 97bc58760420e40160739dc0576d58456b298bca /app.js | |
parent | 1811f8836d5b5eaac3521383dec2176d18d9affa (diff) | |
download | serverstat-d50bf206dea24e223ca57f92ec28daf2b6bbad37.tar.gz serverstat-d50bf206dea24e223ca57f92ec28daf2b6bbad37.tar.bz2 serverstat-d50bf206dea24e223ca57f92ec28daf2b6bbad37.zip |
Diffstat (limited to 'app.js')
-rw-r--r-- | app.js | 239 |
1 files changed, 114 insertions, 125 deletions
@@ -1,84 +1,93 @@ var os = require('os'); -var http = require('http'); var ps = require('portscanner'); -var dispatcher = require('httpdispatcher'); -var spawn = require('child_process').spawn; var nl = require('./numberlogger.js'); -var services = require('./services.js'); +var config = require('./config.js'); +var express = require('express'); +var compression = require('compression'); var PORT = 3369; -var logger = function(name,length) { +var serverstat = { + "uptime": os.uptime(), + "load": [0, 0, 0], + "services": {}, + "stats" : {} +}; + +var serverinfo = { + "hostname": os.hostname(), + "release": os.release(), + "cpuname": os.cpus()[0].model, + "cpunum": os.cpus().length, + "totmem": Math.round(os.totalmem()/1024/1024), + "desc" : config.description, + "stats": {} +}; + +var statResponse = {}; + +function checkp(key) { + ps.checkPortStatus(config.services[key], 'localhost', function (error, status) { + serverstat.services[key] = (status == 'open'); + }) +} + +var logger = function (name, length) { this.name = name; - this.sec = new nl(name+":sec",length); - this.min = new nl(name+":min",length); - this.hrs = new nl(name+":hrs",length); - this.day = new nl(name+":day",length); + this.sec = new nl(name + ":sec", length); + this.min = new nl(name + ":min", length); + this.hrs = new nl(name + ":hrs", length); + this.day = new nl(name + ":day", length); this.time = new Date(); -} +}; -logger.prototype.add = function(time,x) { - function average(l,n) { +logger.prototype.add = function (time, x) { + function average(l, n) { var sum = 0; - for (var i=0;i<n;++i) + for (var i = 0; i < n; ++i) sum += l.ns[l.len - 1 - i]; - return sum/n; + return sum / n; } - if (time.getDay()!=this.time.getDay()) - this.day.add(average(this.hrs,24)); + + if (time.getDay() != this.time.getDay()) + this.day.add(average(this.hrs, 24)); if (time.getHours() != this.time.getHours()) - this.hrs.add(average(this.min,60)); + this.hrs.add(average(this.min, 60)); if (time.getMinutes() != this.time.getMinutes()) - this.min.add(average(this.sec,60)); + this.min.add(average(this.sec, 60)); this.sec.add(x); this.time = time; -} - -logger.prototype.stringify = function() { - return [this.sec.stringify(),this.min.stringify(),this.hrs.stringify(),this.day.stringify()]; -} - -var cpustat = new logger("cpu",100); -var memstat = new logger("mem",100); - -var serverstat={ - "hostname":os.hostname(), - "release":"undef", - "uptime":"", - "load":[0,0,0], - "cpu":cpustat.stringify(), - "mem":memstat.stringify(), - "services":{} -} - -serverstat.release = os.release(); - -function secondsToString(seconds) -{ - function adds(x,a){ - return x + " " + a + " "; +}; + +logger.prototype.setupResponse = function(res){ + var host = this; + var stat = []; + function setupSingleStat(id){ + stat.push(host[id].name); + res[host[id].name] = function (stat) { + stat.stats[host.name] = host[id].stringify(); + }; } - var numdays = Math.floor(seconds / 86400); seconds%=86400; - var numhours = Math.floor(seconds / 3600); seconds%=3600; - var numminutes = Math.floor(seconds / 60); seconds%=60; - return adds(numdays,"day") + adds(numhours,"hrs")+ adds(numminutes,"min") + adds(seconds,"sec"); - -} - -function checkp(key){ - ps.checkPortStatus(services[key], 'localhost', function(error, status) { - // Status is 'open' if currently in use or 'closed' if available - // console.log(key,status); - if (status=='open') - serverstat.services[key]=true; - else - serverstat.services[key]=false; - }) -} - -function refreshStat(){ - for (key in services) { - if (services.hasOwnProperty(key)) { + console.log("Setting up response for "+this.name); + setupSingleStat("sec"); + setupSingleStat("min"); + setupSingleStat("hrs"); + setupSingleStat("day"); + serverinfo.stats[this.name] = stat; +}; + +logger.prototype.stringify = function () { + return [this.sec.stringify(), this.min.stringify(), this.hrs.stringify(), this.day.stringify()]; +}; + +var cpustat = new logger("cpu", 100); +var memstat = new logger("mem", 100); +cpustat.setupResponse(statResponse); +memstat.setupResponse(statResponse); + +function refreshStat() { + for (var key in config.services) { + if (config.services.hasOwnProperty(key)) { checkp(key); } } @@ -86,46 +95,11 @@ function refreshStat(){ serverstat.load = os.loadavg(); } -function handleRequest(request, response){ - try { - //log the request on console -// console.log(request.url); - //Disptach - dispatcher.dispatch(request, response); - } catch(err) { - console.log(err); - } -} - -//For all your static (js/css/images/etc.) set the directory name (relative path). -dispatcher.setStatic('resources'); - -//A sample GET request -dispatcher.onGet("/", function(req, res) { - res.writeHead(200, {'Content-Type': 'application/json','Access-Control-Allow-Origin': '*'}); - res.end(JSON.stringify(serverstat)); -}); - -//A sample POST request -//dispatcher.onPost("/post1", function(req, res) { -// res.writeHead(200, {'Content-Type': 'text/plain'}); -// res.end('Got Post Data'); -//}); - -//Create a server -var server = http.createServer(handleRequest); - -//Lets start our server -server.listen(PORT, function(){ - //Callback triggered when server is successfully listening. Hurray! - console.log("Server listening on: http://localhost:%s", PORT); -}); - refreshStat(); -setInterval(refreshStat,1000); +setInterval(refreshStat, 1000); -function getCPUInfo(callback){ +function getCPUInfo() { var cpus = os.cpus(); var user = 0; @@ -133,52 +107,67 @@ function getCPUInfo(callback){ var sys = 0; var idle = 0; var irq = 0; - var total = 0; - for(var cpu in cpus){ + for (var cpu in cpus) + if (cpus.hasOwnProperty(cpu)) { - user += cpus[cpu].times.user; - nice += cpus[cpu].times.nice; - sys += cpus[cpu].times.sys; - irq += cpus[cpu].times.irq; - idle += cpus[cpu].times.idle; - } + user += cpus[cpu].times.user; + nice += cpus[cpu].times.nice; + sys += cpus[cpu].times.sys; + irq += cpus[cpu].times.irq; + idle += cpus[cpu].times.idle; + } var total = user + nice + sys + idle + irq; return { - 'idle': idle, + 'idle': idle, 'total': total }; } -function getUsage(callback, free){ - +function getUsage() { + var stats = getCPUInfo(); - setInterval(function() { + setInterval(function () { var nstats = getCPUInfo(); - var endIdle = nstats.idle; - var endTotal = nstats.total; - var idle = nstats.idle - stats.idle; - var total = nstats.total - stats.total; - var perc = 1 - idle / total; + var idle = nstats.idle - stats.idle; + var total = nstats.total - stats.total; + var perc = 1 - idle / total; stats = nstats; var time = new Date(); - cpustat.add(time,perc); - memstat.add(time,memPercentage()); - serverstat.cpu=cpustat.stringify(); - serverstat.mem=memstat.stringify(); - - }, 1000 ); + cpustat.add(time, perc); + memstat.add(time, memPercentage()); + }, 1000); } -function memPercentage(){ +function memPercentage() { return 1 - os.freemem() / os.totalmem(); } getUsage(); + +var app = express(); +app.use(compression()); +app.get('/', function (req, res) { + res.append('Content-Type', 'application/json'); + res.append('Access-Control-Allow-Origin', '*'); + res.send(JSON.stringify(serverinfo)); +}); + +app.get('/stat', function (req, res) { + res.append('Content-Type', 'application/json'); + res.append('Access-Control-Allow-Origin', '*'); + var stat = JSON.parse(JSON.stringify(serverstat)); + for (var query in req.query) + if (req.query.hasOwnProperty(query)) + statResponse[req.query[query]](stat); + res.send(JSON.stringify(stat)); +}); +app.listen(PORT); +console.log("Server listening on: %s", PORT); |