Skip to content

Instantly share code, notes, and snippets.

@cuchac
Last active April 12, 2021 05:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cuchac/d55afa9e769b8cb1e1a967bca0f9ed35 to your computer and use it in GitHub Desktop.
Save cuchac/d55afa9e769b8cb1e1a967bca0f9ed35 to your computer and use it in GitHub Desktop.
Dump all memcached keys using `lru_crawler metadump all`
<?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