Skip to content

Instantly share code, notes, and snippets.

@michael-grunder
Last active March 7, 2024 18:32
Show Gist options
  • Save michael-grunder/a9799c8496f7f01dcab1213391ad5978 to your computer and use it in GitHub Desktop.
Save michael-grunder/a9799c8496f7f01dcab1213391ad5978 to your computer and use it in GitHub Desktop.
Is PhpRedis calling `CLUSTER SLOTS`
<?php
function accCommandCounts(array &$acc, array $stats) {
$re_cmd = '/cmdstat_([a-zA-Z]+)\|?([a-zA-Z]*)/';
$re_num = '/^calls=(\d+).*/';
foreach ($stats as $cmd => $info) {
if ( ! preg_match($re_cmd, $cmd, $matches))
die("Malformed command name\n");
$cmd = $matches[1];
if ($matches[2])
$cmd .= ' ' . $matches[2];
if ( ! preg_match($re_num, $info, $matches))
die("Malformed info line\n");
if ( ! isset($acc[$cmd]))
$acc[$cmd] = 0;
$acc[$cmd] += $matches[1];
}
}
function getCommandStats(Redis|RedisCluster $client) {
$res = [];
if ($client instanceof RedisCluster) {
foreach ($client->_masters() as $seed) {
accCommandCounts($res, $client->info($seed, 'commandstats'));
}
} else {
accCommandCounts($res, $client->info('commandstats'));
}
return $res;
}
function clusterSlotCalls($rc) {
$counts = getCommandStats($rc);
return $counts['cluster slots'] ?? 0;
}
function getOption($opt, $k, $default) {
if (isset($_GET[$k]))
return $_GET[$k];
else if (isset($opt[$k]))
return $opt[$k];
else
return $default;
}
function getFlag($opt, $k) {
return isset($_GET[$k]) || isset($opt[$k]);
}
$opt = getopt('', ['host:', 'port:', 'clean']);
$host = getOption($opt, 'host', 'localhost');
$port = getOption($opt, 'port', 7000);
echo "<html><body><pre>\n";
$r = new Redis; $r->connect($host, $port);
$s1 = clusterSlotCalls($r);
$rc = new RedisCluster(NULL, ["$host:$port"], 0, 0, true);
$msg = uniqid();
$pong = $rc->echo(uniqid(), $msg);
$s2 = clusterSlotCalls($r);
$pid = getmypid();
$rc->hincrby('slot-calls', $pid, $s2 - $s1);
printf("[%d] ECHO '%s' => '%s'\n", $pid, $msg, $pong);
printf("[%d] CLUSTER SLOT %d -> %d (called %d time(s))\n",
$pid, $s1, $s2, $s2 - $s1);
foreach ($rc->hgetall('slot-calls') as $wpid => $count) {
printf("[%d] PID %d called CLUSTER SLOTS %d %s\n", $pid, $wpid,
$count, $count == 1 ? 'time' : 'times');
}
echo "</pre></body></html>\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment