Last active
August 29, 2015 14:24
-
-
Save brisbanewebdeveloper/04d547937e111e6d0aa3 to your computer and use it in GitHub Desktop.
Get percentage of time that the CPU was idle from sar command as JavaScript variable
This file contains hidden or 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
<?php | |
/** | |
* Place this PHP script somewhere accessible via HTTP, amend it for your situation if necessary | |
* | |
* Example Usage with jQuery | |
* $.getScript( | |
* 'http://my-site.com/get-sar.php', | |
* function() { | |
* // You can use something like http://www.chartjs.org/ to display the data as chart | |
* console.log(sarData.data[0].time); | |
* console.log(sarData.data[0].idle); | |
* console.log(sarData.avg.idle); | |
* } | |
* ); | |
*/ | |
$sar = '/usr/bin/sar -u'; // You may have to amend here | |
exec($sar, $sarResults); | |
// var_dump($sarResults); exit; | |
$data = array(); | |
foreach ($sarResults as $r) { | |
if (strpos($r, 'Linux') !== false) continue; | |
if ($r == '') continue; | |
sscanf($r, "%s%s%s%s%s%s%s%s\n", $time, $cpu, $user, $nice, $system, $iowait, $steal, $idle); | |
if ($cpu == 'CPU') continue; | |
if ($time == 'Average:') { | |
$data['avg'] = $idle; | |
continue; | |
} | |
// echo $time . $cpu . $user . $nice . $system . $iowait . $steal . $idle . "\n"; | |
$data['data'][] = array( | |
'time' => $time, | |
'idle' => $idle, | |
); | |
} | |
header('Content-Type:text/javascript; charset=utf-8'); | |
echo 'var sarData = ' . json_encode($data) . ';'; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment