Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- function sendMemcacheCommands($command){
- $MEMCACHE_SERVERS = variable_get('memcache_servers', array('127.0.0.1:11211' => 'default'));
- $result = array();
- foreach (array_keys($MEMCACHE_SERVERS) as $server){
- $strs = explode(':',$server);
- $host = $strs[0];
- $port = $strs[1];
- $result[$server] = sendMemcacheCommand($host,$port,$command);
- }
- return $result;
- }
- function sendMemcacheCommand($server,$port,$command){
- $s = @fsockopen($server,$port);
- if (!$s){
- die("Cant connect to:".$server.':'.$port);
- }
- fwrite($s, $command."\r\n");
- $buf='';
- while ((!feof($s))) {
- $buf .= fgets($s, 256);
- if (strpos($buf,"END\r\n")!==false){ // stat says end
- break;
- }
- if (strpos($buf,"DELETED\r\n")!==false || strpos($buf,"NOT_FOUND\r\n")!==false){ // delete says these
- break;
- }
- if (strpos($buf,"OK\r\n")!==false){ // flush_all says ok
- break;
- }
- }
- fclose($s);
- return parseMemcacheResults($buf);
- }
- function parseMemcacheResults($str){
- $res = array();
- $lines = explode("\r\n",$str);
- $cnt = count($lines);
- for($i=0; $i< $cnt; $i++){
- $line = $lines[$i];
- $l = explode(' ',$line,3);
- if (count($l)==3){
- $res[$l[0]][$l[1]]=$l[2];
- if ($l[0]=='VALUE'){ // next line is the value
- $res[$l[0]][$l[1]] = array();
- list ($flag,$size)=explode(' ',$l[2]);
- $res[$l[0]][$l[1]]['stat']=array('flag'=>$flag,'size'=>$size);
- $res[$l[0]][$l[1]]['value']=$lines[++$i];
- }
- }
- elseif ($line=='DELETED' || $line=='NOT_FOUND' || $line=='OK'){
- return $line;
- }
- }
- return $res;
- }
- function getCacheItems(){
- $items = sendMemcacheCommands('stats items');
- $serverItems = array();
- $totalItems = array();
- foreach ($items as $server=>$itemlist){
- $serverItems[$server] = array();
- $totalItems[$server]=0;
- if (!isset($itemlist['STAT'])){
- continue;
- }
- $iteminfo = $itemlist['STAT'];
- foreach ($iteminfo as $keyinfo=>$value){
- if (preg_match('/items\:(\d+?)\:(.+?)$/',$keyinfo,$matches)){
- $serverItems[$server][$matches[1]][$matches[2]] = $value;
- if ($matches[2]=='number'){
- $totalItems[$server] +=$value;
- }
- }
- }
- }
- return array('items'=>$serverItems,'counts'=>$totalItems);
- }
- function dumpCacheSlab($server, $slabId, $limit){
- list($host, $port) = explode(':',$server);
- $resp = sendMemcacheCommand($host,$port,'stats cachedump '.$slabId.' '.$limit);
- return $resp;
- }
- function get_all_memcache_keys() {
- $cacheItems= getCacheItems();
- $items = $cacheItems['items'];
- $keys = array();
- foreach ($items as $server => $entries) {
- foreach ($entries as $slabId => $slab) {
- $items = dumpCacheSlab($server,$slabId,$slab['number']);
- foreach (array_keys($items['ITEM']) as $item) {
- $keys[] = urldecode($item);
- }
- }
- }
- sort($keys);
- return $keys;
- }
- get_all_memcache_keys();
Add Comment
Please, Sign In to add comment