<?php
/**
* @brief: this is a qiangda de tools of watching memcache.
* @author: phpor <lijunjie1982@yahoo.com.cn>
* @date: 2010-07-26 16:00:00
* @version: 1.1
*/
$arropt = getopt('h:p:i:n:rw:e:E:');
if(!isset($arropt['h']) || !isset($arropt['h'])) showHelp();
$host = $arropt['h'];
$port = $arropt['p'];
$interval = isset($arropt['i'])?$arropt['i']:1;
$count = isset($arropt['n'])?$arropt['n']:0;
$relative = isset($arropt['r']);
$width = isset($arropt['w'])?$arropt['w']:15;
$arrExtra = array();
if (isset($arropt['e'])) {
$arrE = explode(':',$arropt['e']);
foreach ($arrE as $field) {
$arrExtra[$field] = $field;
}
}
$mc = new Memcache();
if(!@$mc->connect($host,$port)) {
die("connect $host:$port error\n");
}
init();
$arrShow = array_merge($arrShow, $arrExtra);
if (isset($arropt['E'])) {
$arrE = explode(':',$arropt['E']);
foreach ($arrE as $field) {
unset($arrShow[$field]);
}
}
$arrStats = $mc->getStats();
showHead($arrStats);
show($arrStats,$relative);
$i = 1;
while($count ==0 || $i++ < $count) {
sleep($interval);
$arrStats = $mc->getStats();
show($arrStats,$relative);
}
exit(0);
function showHelp(){
echo <<<eof
Usage:
-h host :
-p port :
-i interval :
-n counts :
-w field width: default 15
-e extends fields: eg: "bytes_read:bytes_written"
-E erase fields: eg: "cmd_get:cmd_set"
-r : show relative
eg :
1. php mc_watch.php -h 10.65.129.61 -p 11241 -i 1 -n 10 -r
2. php mc_watch.php -h 10.65.129.61 -p 11241 -i 1 -n 10 -r -e "bytes_read:bytes_written" -E "cmd_get:cmd_set"
eof;
exit(0);
}
function init() {
global $arrShow, $arrOld;
$arrShow = array(
'curr_connections' =>'curr_conn',
'cmd_get' =>'cmd_get',
'cmd_set' =>'cmd_set',
'get_hits' =>'get_hits',
'get_misses' =>'get_misses',
'hits_rate' =>'hits_rate',
'evictions' =>'evictions'
);
$arrOld = array();
foreach ($arrShow as $key=>$val) {
$arrOld[$key] = 0;
}
}
function showHead($arrStats) {
global $arrShow, $width;
echo "pid: ".$arrStats['pid']
."\tserver_time: ".date('Y-m-d H:i:s',$arrStats['time'])
."\tmemcache_version: ".$arrStats['version']
."\tmem_used: ".(getUse() / 1024 / 1024)."MB"
."\n";
foreach($arrShow as $val) {
printf("%{$width}s",$val);
}
echo "\n";
}
function show($arrStats,$relative = false) {
global $arrShow,$arrOld, $width;
$cnt_hits = $relative?$arrStats["get_hits"]-$arrOld["get_hits"]:$arrStats["get_hits"];
$cnt_get = $relative?$arrStats["cmd_get"]-$arrOld["cmd_get"]:$arrStats["cmd_get"];
foreach($arrShow as $key=>$title) {
if ($key == "hits_rate") {
printf("%{$width}s",sprintf("%0.2d%s", ($cnt_hits/$cnt_get)*100, "%"));
}
if(!isset($arrStats[$key])) continue;
$val = $arrStats[$key];
printf("%{$width}s",$relative?$val - $arrOld[$key]:$val );
}
echo "\n";
$arrOld = $arrStats;
}
function getUse() {
global $mc;
$arr = $mc->getStats('slabs');
return $arr['total_malloced'];
}