summaryrefslogtreecommitdiff
path: root/app.js
blob: 165dbebc9deec84c5ff94ff8e3a9d3156142da1f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
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 PORT = 3369;

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.time = new Date();
}

logger.prototype.add = function(time,x) {
    function average(l,n) {
        var sum = 0;
        for (var i=0;i<n;++i)
            sum += l.ns[l.len - 1 - i];
        return sum/n;
    }
    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));
    if (time.getMinutes() != this.time.getMinutes())
        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 + " ";
    }
    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)) {
            checkp(key);
        }
    }
    serverstat.uptime = os.uptime();
    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);

function getCPUInfo(callback){ 
    var cpus = os.cpus();

    var user = 0;
    var nice = 0;
    var sys = 0;
    var idle = 0;
    var irq = 0;
    var total = 0;

    for(var cpu in cpus){

        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, 
        'total': total
    };
}

function getUsage(callback, free){ 
        
    var stats = getCPUInfo();

    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;

        stats = nstats;

        var time = new Date();

        cpustat.add(time,perc);
        memstat.add(time,memPercentage());
        serverstat.cpu=cpustat.stringify();
        serverstat.mem=memstat.stringify();

    }, 1000 );
}

function memPercentage(){
    return 1 - os.freemem() / os.totalmem();
}

getUsage();