Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,13 @@
"phpstan/phpstan-phpunit": "^1.1.0",
"phpstan/phpstan-strict-rules": "^1.1.0",
"phpunit/phpunit": "^9.4",
"predis/predis": "^2.0",
"squizlabs/php_codesniffer": "^3.6",
"symfony/polyfill-apcu": "^1.6"
},
"suggest": {
"ext-redis": "Required if using Redis.",
"predis/predis": "Required if using Predis.",
"ext-apc": "Required if using APCu.",
"ext-pdo": "Required if using PDO.",
"promphp/prometheus_push_gateway_php": "An easy client for using Prometheus PushGateway.",
Expand Down
2 changes: 2 additions & 0 deletions examples/metrics.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
if ($adapter === 'redis') {
Redis::setDefaultOptions(['host' => $_SERVER['REDIS_HOST'] ?? '127.0.0.1']);
$adapter = new Prometheus\Storage\Redis();
} elseif ($adapter === 'predis') {
$adapter = new Prometheus\Storage\Predis(['host' => $_SERVER['REDIS_HOST'] ?? '127.0.0.1']);
} elseif ($adapter === 'apc') {
$adapter = new Prometheus\Storage\APC();
} elseif ($adapter === 'apcng') {
Expand Down
111 changes: 111 additions & 0 deletions src/Prometheus/Storage/Predis.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
<?php

declare(strict_types=1);

namespace Prometheus\Storage;

use Predis\Configuration\Option\Prefix;
use Prometheus\Exception\StorageException;
use Predis\Client;

/**
* @property Client $redis
*/
final class Predis extends Redis
{
/**
* @var mixed[]
*/
private static array $defaultOptions = [
'host' => '127.0.0.1',
'port' => 6379,
'scheme' => 'tcp',
'timeout' => 0.1,
'read_timeout' => '10',
'persistent' => 0,
'password' => null,
];

public function __construct(array $options = [])
{
$this->options = array_merge(self::$defaultOptions, $options);

parent::__construct($options);

$this->redis = new Client($this->options);
}

public static function fromClient(Client $redis): self
{
if ($redis->isConnected() === false) {
throw new StorageException('Connection to Redis server not established');
}

$self = new self();
$self->redis = $redis;

return $self;
}

protected function ensureOpenConnection(): void
{
if ($this->redis->isConnected() === false) {
$this->redis->connect();
}
}

public static function fromExistingConnection(\Redis $redis): Redis
{
throw new \RuntimeException('This method is not supported by predis adapter');
}

protected function getGlobalPrefix(): ?string
{
if ($this->redis->getOptions()->prefix === null) {
return null;
}

if ($this->redis->getOptions()->prefix instanceof Prefix) {
return $this->redis->getOptions()->prefix->getPrefix();
}

return null;
}

/**
* @param mixed[] $args
* @param int $keysCount
* @return mixed[]
*/
protected function evalParams(array $args, int $keysCount): array
{
return [$keysCount, ...$args];
}


protected function prefix(string $key): string
{
// the predis is doing key prefixing on its own
return '';
}

protected function setParams(array $input): array
{
$values = array_values($input);
$params = [];

if (isset($input['EX'])) {
$params[] = 'EX';
$params[] = $input['EX'];
}

if (isset($input['PX'])) {
$params[] = 'PX';
$params[] = $input['PX'];
}

$params[] = $values[0];

return $params;
}
}
119 changes: 76 additions & 43 deletions src/Prometheus/Storage/Redis.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace Prometheus\Storage;

use InvalidArgumentException;
use Predis\Client;
use Prometheus\Counter;
use Prometheus\Exception\StorageException;
use Prometheus\Gauge;
Expand Down Expand Up @@ -38,12 +39,12 @@ class Redis implements Adapter
/**
* @var mixed[]
*/
private $options = [];
protected $options = [];

/**
* @var \Redis
* @var \Redis|Client
*/
private $redis;
protected $redis;

/**
* @var boolean
Expand Down Expand Up @@ -112,8 +113,7 @@ public function wipeStorage(): void

$searchPattern = "";

$globalPrefix = $this->redis->getOption(\Redis::OPT_PREFIX);
// @phpstan-ignore-next-line false positive, phpstan thinks getOptions returns int
$globalPrefix = $this->getGlobalPrefix();
if (is_string($globalPrefix)) {
$searchPattern .= $globalPrefix;
}
Expand All @@ -134,8 +134,10 @@ public function wipeStorage(): void
until cursor == "0"
LUA
,
[$searchPattern],
0
...$this->evalParams(
[$searchPattern],
0
)
);
}

Expand Down Expand Up @@ -188,7 +190,7 @@ function (array $metric): MetricFamilySamples {
/**
* @throws StorageException
*/
private function ensureOpenConnection(): void
protected function ensureOpenConnection(): void
{
if ($this->connectionInitialized === true) {
return;
Expand Down Expand Up @@ -268,15 +270,17 @@ public function updateHistogram(array $data): void
return result
LUA
,
[
$this->toMetricKey($data),
self::$prefix . Histogram::TYPE . self::PROMETHEUS_METRIC_KEYS_SUFFIX,
json_encode(['b' => 'sum', 'labelValues' => $data['labelValues']]),
json_encode(['b' => $bucketToIncrease, 'labelValues' => $data['labelValues']]),
$data['value'],
json_encode($metaData),
],
2
...$this->evalParams(
[
$this->toMetricKey($data),
self::$prefix . Histogram::TYPE . self::PROMETHEUS_METRIC_KEYS_SUFFIX,
json_encode(['b' => 'sum', 'labelValues' => $data['labelValues']]),
json_encode(['b' => $bucketToIncrease, 'labelValues' => $data['labelValues']]),
$data['value'],
json_encode($metaData),
],
2
)
);
}

Expand Down Expand Up @@ -309,7 +313,7 @@ public function updateSummary(array $data): void
$done = false;
while (!$done) {
$sampleKey = $valueKey . ':' . uniqid('', true);
$done = $this->redis->set($sampleKey, $data['value'], ['NX', 'EX' => $data['maxAgeSeconds']]);
$done = $this->redis->set($sampleKey, $data['value'], ...$this->setParams(['NX', 'EX' => $data['maxAgeSeconds']]));
}
}

Expand Down Expand Up @@ -339,15 +343,17 @@ public function updateGauge(array $data): void
end
LUA
,
[
$this->toMetricKey($data),
self::$prefix . Gauge::TYPE . self::PROMETHEUS_METRIC_KEYS_SUFFIX,
$this->getRedisCommand($data['command']),
json_encode($data['labelValues']),
$data['value'],
json_encode($metaData),
],
2
...$this->evalParams(
[
$this->toMetricKey($data),
self::$prefix . Gauge::TYPE . self::PROMETHEUS_METRIC_KEYS_SUFFIX,
$this->getRedisCommand($data['command']),
json_encode($data['labelValues']),
$data['value'],
json_encode($metaData),
],
2
)
);
}

Expand All @@ -370,15 +376,17 @@ public function updateCounter(array $data): void
return result
LUA
,
[
$this->toMetricKey($data),
self::$prefix . Counter::TYPE . self::PROMETHEUS_METRIC_KEYS_SUFFIX,
$this->getRedisCommand($data['command']),
$data['value'],
json_encode($data['labelValues']),
json_encode($metaData),
],
2
...$this->evalParams(
[
$this->toMetricKey($data),
self::$prefix . Counter::TYPE . self::PROMETHEUS_METRIC_KEYS_SUFFIX,
$this->getRedisCommand($data['command']),
$data['value'],
json_encode($data['labelValues']),
json_encode($metaData),
],
2
)
);
}

Expand All @@ -403,7 +411,7 @@ private function collectHistograms(): array
sort($keys);
$histograms = [];
foreach ($keys as $key) {
$raw = $this->redis->hGetAll(str_replace($this->redis->_prefix(''), '', $key));
$raw = $this->redis->hGetAll(str_replace($this->prefix(''), '', $key));
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
$raw = $this->redis->hGetAll(str_replace($this->prefix(''), '', $key));
$raw = $this->redis->hGetAll($this->removePrefixFromKey($key));

if (!isset($raw['__meta'])) {
continue;
}
Expand Down Expand Up @@ -481,12 +489,11 @@ private function collectHistograms(): array
*/
private function removePrefixFromKey(string $key): string
{
// @phpstan-ignore-next-line false positive, phpstan thinks getOptions returns int
if ($this->redis->getOption(\Redis::OPT_PREFIX) === null) {
if ($this->getGlobalPrefix() === null) {
return $key;
}
// @phpstan-ignore-next-line false positive, phpstan thinks getOptions returns int
return substr($key, strlen($this->redis->getOption(\Redis::OPT_PREFIX)));

return substr($key, strlen($this->getGlobalPrefix()));
}

/**
Expand Down Expand Up @@ -586,7 +593,7 @@ private function collectGauges(bool $sortMetrics = true): array
sort($keys);
$gauges = [];
foreach ($keys as $key) {
$raw = $this->redis->hGetAll(str_replace($this->redis->_prefix(''), '', $key));
$raw = $this->redis->hGetAll(str_replace($this->prefix(''), '', $key));
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

$this->prefix('') is always an empty string for this adater, but $key contains the prefix to remove.
perhaps $this->removePrefixFromKey($key) was intended here ?
The same applies to collectHistograms, collectGauges

Suggested change
$raw = $this->redis->hGetAll(str_replace($this->prefix(''), '', $key));
$raw = $this->redis->hGetAll($this->removePrefixFromKey($key));

if (!isset($raw['__meta'])) {
continue;
}
Expand Down Expand Up @@ -622,7 +629,7 @@ private function collectCounters(bool $sortMetrics = true): array
sort($keys);
$counters = [];
foreach ($keys as $key) {
$raw = $this->redis->hGetAll(str_replace($this->redis->_prefix(''), '', $key));
$raw = $this->redis->hGetAll(str_replace($this->prefix(''), '', $key));
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
$raw = $this->redis->hGetAll(str_replace($this->prefix(''), '', $key));
$raw = $this->redis->hGetAll($this->removePrefixFromKey($key));

if (!isset($raw['__meta'])) {
continue;
}
Expand Down Expand Up @@ -707,4 +714,30 @@ private function decodeLabelValues(string $values): array
}
return $decodedValues;
}

protected function getGlobalPrefix(): ?string
{
// @phpstan-ignore-next-line false positive, phpstan thinks getOptions returns int
return $this->redis->getOption(\Redis::OPT_PREFIX);
}

/**
* @param mixed[] $args
* @param int $keysCount
* @return mixed[]
*/
protected function evalParams(array $args, int $keysCount): array
{
return [$args, $keysCount];
}

protected function prefix(string $key): string
{
return $this->redis->_prefix($key);
}

protected function setParams(array $params): array
{
return [$params];
}
}
21 changes: 21 additions & 0 deletions tests/Test/Prometheus/Predis/CollectorRegistryTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

declare(strict_types=1);

namespace Test\Prometheus\Predis;

use Predis\Client;
use Prometheus\Storage\Predis;
use Test\Prometheus\AbstractCollectorRegistryTest;

/**
* @requires predis
*/
class CollectorRegistryTest extends AbstractCollectorRegistryTest
{
public function configureAdapter(): void
{
$this->adapter = new Predis(['host' => REDIS_HOST]);
$this->adapter->wipeStorage();
}
}
22 changes: 22 additions & 0 deletions tests/Test/Prometheus/Predis/CounterTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

declare(strict_types=1);

namespace Test\Prometheus\Predis;

use Predis\Client;
use Prometheus\Storage\Predis;
use Test\Prometheus\AbstractCounterTest;

/**
* See https://prometheus.io/docs/instrumenting/exposition_formats/
* @requires extension redis
*/
class CounterTest extends AbstractCounterTest
{
public function configureAdapter(): void
{
$this->adapter = new Predis(['host' => REDIS_HOST]);
$this->adapter->wipeStorage();
}
}
Loading