Created
July 19, 2017 19:34
-
-
Save da-player/a0a7c91faf52924a32c860ec6a4d14de to your computer and use it in GitHub Desktop.
Node - Redis Bandwidth Monitor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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'); |
Bg
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Bv