Node - Redis Bandwidth Monitor
/* | |
npm install redis | |
*/ | |
var http = require('http'); | |
var fs = require('fs'); | |
var redis = require("redis"); | |
/* ------------------------------------------------------------------------------------------------ */ | |
var server_id = 'source1'; // unique server id | |
var server_hostname = 'http://source1.domain.com'; // hostname | |
var server_network_interface = 'eth0'; // public network interface where nginx listens | |
var refresh_interval = 1000; // bandwidth monitor refresh interval (ms) | |
var redis_host = '192.168.0.2'; // redis hostname or ip | |
var redis_port = 1234; // redis port | |
var redis_password = 'SUPER_STRONG_PASSWORD_X80'; // redis password. Use strong password! | |
var redisHashKey = 'bandwidth:usage'; // redis key path (you don't need to change it) | |
/* ------------------------------------------------------------------------------------------------ */ | |
var isFirst = true; | |
var previousValue = 0; | |
var currentValue = 0; | |
var usage = 0; | |
var redisDetails = { | |
host: redis_host, | |
port: redis_port, | |
password: redis_password | |
}; | |
var client = redis.createClient(redisDetails); | |
Array.prototype.getMin = function (attr) { | |
return this.reduce(function (prev, curr) { | |
return prev[attr] < curr[attr] ? prev : curr; | |
}); | |
} | |
setInterval(function () { | |
getMetrics(); | |
}, refresh_interval); | |
/** | |
* Metrics | |
*/ | |
var getMetrics = function () { | |
fs.readFile('/sys/class/net/' + server_network_interface + '/statistics/tx_bytes', function (err, buf) { | |
currentValue = parseInt(buf.toString().replace(/\n/, '')); | |
usage = currentValue - previousValue; | |
if (!isFirst) { | |
var bandwidthData = {'host': server_hostname, 'bandwidth': usage, 'last_update': new Date().getTime()}; | |
client.hset(redisHashKey, server_id, JSON.stringify(bandwidthData)); | |
} else { | |
isFirst = false; | |
} | |
previousValue = currentValue; | |
}); | |
}; | |
/** | |
* Node Http Server | |
*/ | |
http.createServer(function (req, res) { | |
client.hgetall(redisHashKey, function (error, object) { | |
var container = []; | |
for (var obj in object) { | |
container.push(JSON.parse(object[obj])); | |
} | |
var result = container.getMin('bandwidth'); | |
res.writeHead(200, {"Content-Type": "application/json"}); | |
res.end(JSON.stringify(result)); | |
}); | |
}).listen(3030, 'localhost'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment