Skip to content

Instantly share code, notes, and snippets.

@pkdavies
Created June 8, 2012 12:31
Show Gist options
  • Save pkdavies/2895384 to your computer and use it in GitHub Desktop.
Save pkdavies/2895384 to your computer and use it in GitHub Desktop.
APC cache fragmentation only value for monitoring service
<?php
ini_set('display_errors',1);
ini_set('error_reporting', E_ALL);
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
// default display mode
//$display_mode='formatted';
$display_mode='other';
// default cache mode
$cache_mode='opcode';
// cache scope
$scope_list=array(
'A' => 'cache_list',
'D' => 'deleted_list'
);
$time = time();
if(!function_exists('apc_cache_info') || !($cache=@apc_cache_info($cache_mode))) {
echo "SYSTEM OK No cache info available. Check APC is running.\n";
exit;
}
if (isset($_GET['clear'])){
apc_clear_cache();
apc_clear_cache('user');
apc_clear_cache('opcode');
}
function bsize($s) {
foreach (array('','K','M','G') as $i => $k) {
if ($s < 1024) break;
$s/=1024;
}
return sprintf("%5.1f %sBytes",$s,$k);
}
$cache_user = apc_cache_info('user', 1);
$mem=apc_sma_info();
if(!$cache['num_hits']) { $cache['num_hits']=1; $time++; }
// Fragementation: (freeseg - 1) / total_seg
$nseg = $freeseg = $fragsize = $freetotal = 0;
for($i=0; $i<$mem['num_seg']; $i++) {
$ptr = 0;
foreach($mem['block_lists'][$i] as $block) {
if ($block['offset'] != $ptr) {
++$nseg;
}
$ptr = $block['offset'] + $block['size'];
//Only consider blocks <5M for the fragmentation %
if($block['size']<(5*1024*1024)) $fragsize+=$block['size'];
$freetotal+=$block['size'];
}
$freeseg += count($mem['block_lists'][$i]);
}
switch ($display_mode) {
case "formatted": $frag = ($freeseg > 1)? sprintf("%.2f%% (%s out of %s in %d fragments)", ($fragsize/$freetotal)*100,bsize($fragsize),bsize($freetotal),$freeseg) : "0%"; break;
default: $frag = ($freeseg > 1)? sprintf("%.2f%", ($fragsize/$freetotal)*100,bsize($fragsize),bsize($freetotal),$freeseg) : 0; break;
}
if ($frag >= 0){
if ($frag > 60){
apc_clear_cache();
apc_clear_cache('user');
apc_clear_cache('opcode');
echo "SYSTEM OK and APC cache fragmentation at: ".$frag."% and now reset.\n";
} else {
echo "SYSTEM OK and APC cache fragmentation at: ".$frag."% \n";
}
} else {
echo "SYSTEM OK No cache info available. Check APC is running.\n";
}
?>
@pkdavies
Copy link
Author

pkdavies commented Jun 8, 2012

Code modified from original apc.php (Ralf Becker, Rasmus Lerdorf, Ilia Alshanetsky) - mainly for use with any monitoring tool to alert if the fragmentation level is too high.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment