Skip to content

Instantly share code, notes, and snippets.

@oberhamsi
Created May 14, 2012 13:11
Show Gist options
  • Select an option

  • Save oberhamsi/2693859 to your computer and use it in GitHub Desktop.

Select an option

Save oberhamsi/2693859 to your computer and use it in GitHub Desktop.
run mtr every 5 seconds and report hosts losing packets
/**
* Continuesly mrts a host and logs errors if packet loss to host
* or on route.
*/
var {command} = require('ringo/subprocess');
var {setInterval} = require('ringo/scheduler');
var log = require('ringo/logging').getLogger('mtr');
var $d = require('ringo/utils/dates');
//var MTR_PATH = '/root/mtr-0.82/mtr';
var MTR_PATH = ['/usr/bin/mtr'];
var MTR_ARGS = [
'--no-dns',
'--report',
'--order',
'LAV',
'--report-cycles',
'2', // 20
'--interval',
'1' // 5
];
var DATE_FORMAT = 'dd.MM.yyyy';
var history = {};
var tick = function() {
var host = 'orf.at';
var stdout = command.apply(null, MTR_PATH.concat(MTR_ARGS).concat([host]));
//HOST: duchov Loss% Avg StDev Avg Best Wrst StDev
//1.|-- 10.156.135.251 0.0% 1.7 2.3 1.7 0.8 8.1 2.3
var lines = stdout.replace(/[\ ]+/g,' ').split('\n').splice(1);
lines.pop();
lines.forEach(function(line, idx) {
var lp = line.split(' ');
// ["", "1.|--", "10.156.135.251", "0.0%", "0.8", "0.0", "0.8", "0.8", "0.9", "0.0"]
var host = lp[2];
var loss = parseFloat(lp[3]);
if (host === '???') {
log.info('A host on route is not responding');
return;
}
if (!(host in history)) {
history[host] = [];
}
if (idx === lines.length-1 && loss > 0.0) {
log.error(
$d.format(new Date(), DATE_FORMAT),
'Packet loss', loss, '% to ', host
);
}
history[host].push({
timestamp: Date.now(),
loss: loss,
avg: lp[4],
routePosition: parseInt(lp[1])
});
});
print (history.toSource())
if (true || history[host].length > 20) {
// find hosts who had more then 5% loss at least
// 3 times.
// truncate history of all entries
var losers = [];
Object.keys(history).forEach(function(host) {
var loseCount = 0;
history[host].some(function(info) {
if (info.loss > 5.0) {
loseCount++;
}
if (loseCount >=3) {
return true;
}
});
if (loseCount >= 3) {
losers.push(host);
}
history[host] = history.host.splice(10);
});
losers.sort(function(a,b) {
if (history[a][0].routePosition < history[a][0].routePosition) {
return -1;
}
if (history[a][0].routePosition > history[a][0].routePosition) {
return 1;
}
return 0;
});
if (losers.length) {
log.error(
$d.format(new Date(), DATE_FORMAT),
'Hosts which had >5% loss >= 3 times, sorted by hops:',
losers.join(', ')
);
}
}
};
setInterval(tick, 5*1000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment