Skip to content

Instantly share code, notes, and snippets.

@GeertHauwaerts
Created August 21, 2018 11:49
Show Gist options
  • Save GeertHauwaerts/dd8f989490460f42232608d34a3b0e43 to your computer and use it in GitHub Desktop.
Save GeertHauwaerts/dd8f989490460f42232608d34a3b0e43 to your computer and use it in GitHub Desktop.
Create an outage report based on a ping log file
<?php
/**
* Create an outage report based on a ping log file.
*
* Command: ping <target> -DO >> ping.log
*/
$report = [
'log' => 'ping.log',
'min_loss' => 5
];
parseLog();
report();
function parseLog() {
global $report;
if ($handle = fopen($report['log'], 'r')) {
while (($line = fgets($handle)) !== false) {
parseLine($line);
}
fclose($handle);
} else {
die('Unable to read the log.');
}
}
function parseLine($line) {
global $report;
if (substr($line, 0, 4 ) === 'PING') {
getTarget($line);
} elseif (substr($line, 0, 1) === '[') {
getResponse($line);
}
}
function getTarget($line) {
global $report;
if (preg_match('/^PING (.*) \((.*)\) \d+\(\d+\) bytes of data\.$/', $line, $matches)) {
$report['target_host'] = $matches[1];
$report['target_ip'] = $matches[2];
} else {
die('Unable to read the target.');
}
}
function getResponse($line) {
global $report;
if (preg_match('/^\[(\d+)\.\d+\] 64 bytes from/', $line, $matches)) {
if (!isset($report['log_start'])) {
$report['log_start'] = $matches[1];
}
if (isset($report['status']) && ($report['status'] === 'down')) {
if ($matches[1] - $report['down_start'] > $report['min_loss']) {
$report['cycles'][] = [
'down' => $report['down_start'],
'up' => $matches[1]
];
}
unset($report['down_start']);
}
$report['status'] = 'up';
$report['log_end'] = $matches[1];
} elseif (preg_match('/^\[(\d+)\.\d+\] no answer yet for/', $line, $matches)) {
if (!isset($report['down_start'])) {
$report['down_start'] = $matches[1];
}
$report['status'] = 'down';
$report['log_end'] = $matches[1];
} else {
die('Invalid response: ' . $line);
}
}
function report() {
global $report;
echo "Report Start:\t" . date('r', $report['log_start']) . "\n";
echo "Report End:\t" . date('r', $report['log_end']) . "\n\n";
echo "Target:\t\t" . $report['target_ip'] . "\n";
echo "Outages:\t" . count($report['cycles']) . "\n\n";
echo "Downtime:\n";
foreach ($report['cycles'] as $cycle) {
echo "\t" . date('r', $cycle['down']) . " -> " . date('r', $cycle['up']) . " (" . ($cycle['up'] - $cycle['down']) . " seconds)\n";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment