Last active
April 12, 2021 05:45
-
-
Save cuchac/d55afa9e769b8cb1e1a967bca0f9ed35 to your computer and use it in GitHub Desktop.
Dump all memcached keys using `lru_crawler metadump all`
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 | |
function getAllKeys(\Memcached $mc): array | |
{ | |
$allKeys = []; | |
foreach ($mc->getServerList() as $id => $server) { | |
$sock = fsockopen($server['host'], $server['port'], $errno, $errstr, 1); | |
if ($sock === false) { | |
throw new Exception("Error connection to server {$server['host']} on port {$server['port']}: ({$errno}) {$errstr}"); | |
} | |
stream_set_timeout($sock, 1); | |
if (fwrite($sock, "lru_crawler metadump all\n") === false) { | |
throw new Exception('Error writing to socket'); | |
} | |
$end = 0; | |
while (($line = fgets($sock)) !== false) { | |
// WORKAROUND: Memcached does not send "END" sometimes | |
// see https://github.com/memcached/memcached/issues/667 | |
// Simulate END by sending next unknown command and waiting for ERROR | |
if ($end == 0) { | |
if (fwrite($sock, "err\n") === false) { | |
throw new Exception('Error writing to socket'); | |
} | |
$end = 1; | |
} | |
$line = trim($line); | |
if ($line === 'END' || $line === 'ERROR') { | |
break; | |
} | |
// key=foobar exp=1596440293 la=1596439293 cas=8492 fetch=no cls=24 size=14908 | |
if (preg_match('!^key=(\S+)!', $line, $matches)) { | |
$allKeys[] = rawurldecode($matches[1]); | |
} | |
} | |
if (fclose($sock) === false) { | |
throw new Exception('Error closing socket'); | |
} | |
} | |
return $allKeys; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment