Added integration testing with OTel

This commit is contained in:
vladvildanov
2026-11-25 12:12:32 +02:00
parent aba81b94d0
commit ee955ff682
11 changed files with 373 additions and 7 deletions
+13
View File
@@ -119,3 +119,16 @@ services:
profiles:
- sentinel
- all
otel-collector:
image: otel/opentelemetry-collector-contrib:latest
container_name: otel-collector
command: ["--config=/etc/otel-collector.yml"]
ports:
- 4318:4318 # OTLP HTTP receiver
- 8889:8889 # Prometheus endpoint read by the tests
volumes:
- "./otel-collector.yml:/etc/otel-collector.yml"
profiles:
- otel
- all
+15
View File
@@ -0,0 +1,15 @@
receivers:
otlp:
protocols:
http:
endpoint: 0.0.0.0:4318
exporters:
prometheus:
endpoint: 0.0.0.0:8889
service:
pipelines:
metrics:
receivers: [otlp]
exporters: [prometheus]
+21 -3
View File
@@ -139,10 +139,28 @@ jobs:
with:
dependency-versions: highest
# Optional dependency that cannot be part of require-dev: it does not support PHP < 8.1.
- name: Install OpenTelemetry API
# Optional dependencies that cannot be part of require-dev: they do not support PHP < 8.2.
- name: Install OpenTelemetry SDK
if: ${{ matrix.php >= '8.2' }}
run: composer require --dev --no-interaction open-telemetry/api
run: |
composer config --no-plugins allow-plugins.php-http/discovery false
composer config --no-plugins allow-plugins.tbachert/spi false
composer require --dev --no-interaction open-telemetry/sdk open-telemetry/exporter-otlp guzzlehttp/guzzle
- name: Start OpenTelemetry collector
if: ${{ matrix.php >= '8.2' }}
uses: hoverkraft-tech/compose-action@v3.2.0
with:
compose-file: .github/docker-compose.yml
services: otel-collector
- name: Run OpenTelemetry tests
if: ${{ matrix.php >= '8.2' }}
run: vendor/bin/phpunit --group otel
- name: Run OpenTelemetry tests using Relay
if: ${{ matrix.php >= '8.2' && matrix.redis >= '8.0' }}
run: vendor/bin/phpunit -c phpunit.relay.xml --group otel
- name: Run tests
if: ${{ matrix.php != '8.4' || matrix.redis != '8.0' }}
+2 -2
View File
@@ -743,8 +743,8 @@ each command as seen by the application, retries and cluster redirects included:
by Relay are not visible to Predis and are not counted.
- `db.namespace` is the database selected when connecting, later `SELECT` commands are not tracked.
- `server.address` and `server.port` are the connection parameters of the node, while
`network.peer.address` and `network.peer.port` are the resolved address of the socket (not available
with Relay). With aggregate connections they are reported only when the node is known: always with
`network.peer.address` and `network.peer.port` are the resolved address of the socket (with Relay,
which does not expose it, they repeat the connection parameters). With aggregate connections they are reported only when the node is known: always with
replication, and for commands that succeeded or failed with a connection error with cluster.
PHP has no background exporter, so metrics leave the process only when the meter provider is flushed
+95
View File
@@ -0,0 +1,95 @@
<?php
/*
* This file is part of the Predis package.
*
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2026 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
// Exports Predis metrics to an OpenTelemetry collector over OTLP/HTTP.
//
// Requires PHP 8.2+ and:
// composer require --dev open-telemetry/sdk open-telemetry/exporter-otlp guzzlehttp/guzzle
//
// Usage:
// php examples/otel_metrics.php [redis-uri] [collector-endpoint] [seconds]
// php examples/otel_metrics.php tcp://127.0.0.1:6381 http://127.0.0.1:4318 120
//
// The workload repeats for the given number of seconds (60 by default): dashboards built on
// rate() show nothing for counters that are exported only once.
use OpenTelemetry\Contrib\Otlp\MetricExporter;
use OpenTelemetry\Contrib\Otlp\OtlpHttpTransportFactory;
use OpenTelemetry\SDK\Common\Attribute\Attributes;
use OpenTelemetry\SDK\Metrics\MeterProvider;
use OpenTelemetry\SDK\Metrics\MetricReader\ExportingReader;
use OpenTelemetry\SDK\Resource\ResourceInfo;
use Predis\Client;
use Predis\Observability\MetricGroup;
use Predis\Observability\MetricsConfig;
use Predis\Observability\ObservabilityInstance;
use Predis\Observability\OTelConfig;
use Predis\Response\ServerException;
require __DIR__ . '/../vendor/autoload.php';
$redis = $argv[1] ?? 'tcp://127.0.0.1:6381';
$collector = $argv[2] ?? 'http://127.0.0.1:4318';
$seconds = (int) ($argv[3] ?? 60);
$transport = (new OtlpHttpTransportFactory())->create($collector . '/v1/metrics', 'application/x-protobuf');
$provider = MeterProvider::builder()
->setResource(ResourceInfo::create(Attributes::create(['service.name' => 'predis-example'])))
->addReader(new ExportingReader(new MetricExporter($transport)))
->build();
ObservabilityInstance::getInstance()->init(new OTelConfig(
new MetricsConfig([
'enabled' => true,
'enabled_metric_groups' => [MetricGroup::COMMAND],
]),
$provider
));
$client = new Client($redis);
echo "Exporting to $collector for $seconds seconds as service 'predis-example'", PHP_EOL;
$deadline = time() + $seconds;
do {
$client->set('otel:string', 'bar');
$client->get('otel:string');
try {
$client->lpush('otel:string', 'x');
} catch (ServerException $exception) {
// Expected: recorded as a failed operation.
}
$client->pipeline(function ($pipeline) {
$pipeline->set('otel:counter', 1);
$pipeline->incr('otel:counter');
$pipeline->get('otel:counter');
});
$client->transaction(function ($transaction) {
$transaction->incr('otel:counter');
});
$client->del('otel:string', 'otel:counter');
// PHP has no background exporter: nothing leaves the process until the provider is flushed.
if (!ObservabilityInstance::getInstance()->forceFlush()) {
echo 'Failed to export', PHP_EOL;
}
usleep(200000);
} while (time() < $deadline);
echo 'Done', PHP_EOL;
+2 -2
View File
@@ -9,8 +9,8 @@ parameters:
- message: "#^Static method Predis\\\\Command\\\\RawCommand\\:\\:create\\(\\) invoked with 0 parameters, at least 1 required\\.$#"
count: 1
path: tests/Predis/Command/RawCommandTest.php
# Optional dependency (open-telemetry/api) that cannot be installed on PHP < 8.1
- message: "#OpenTelemetry\\\\API\\\\#"
# Optional dependencies (open-telemetry/api, sdk, exporter-otlp) that cannot be installed on PHP < 8.1
- message: "#OpenTelemetry\\\\#"
path: tests/Predis/Observability/*
# Mockery
- message: "#^Call to an undefined method Predis\\\\Configuration\\\\Option\\\\AggregateTest\\:\\:getMockConnectionClass\\(\\)\\.$#"
+5
View File
@@ -30,6 +30,7 @@
<group>cluster</group>
<group>gears</group>
<group>unprotected</group>
<group>otel</group>
</exclude>
</groups>
@@ -48,6 +49,10 @@
<env name="USE_RELAY" value="true" />
<env name="REDIS_STACK_SERVER_PORT" value="6479" />
<!-- OpenTelemetry collector: OTLP HTTP receiver and Prometheus exporter -->
<env name="OTEL_COLLECTOR_ENDPOINT" value="http://127.0.0.1:4318" />
<env name="OTEL_PROMETHEUS_ENDPOINT" value="http://127.0.0.1:8889/metrics" />
<!-- Redis Cluster -->
<!-- Only master nodes endpoints included -->
<const
+5
View File
@@ -34,6 +34,7 @@
<group>gears-cluster</group>
<group>unprotected</group>
<group>sentinel</group>
<group>otel</group>
<!-- <group>connected</group> -->
<!-- <group>disconnected</group> -->
<!-- <group>commands</group> -->
@@ -56,6 +57,10 @@
<env name="USE_RELAY" value="false" />
<env name="REDIS_STACK_SERVER_PORT" value="6479" />
<!-- OpenTelemetry collector: OTLP HTTP receiver and Prometheus exporter -->
<env name="OTEL_COLLECTOR_ENDPOINT" value="http://127.0.0.1:4318" />
<env name="OTEL_PROMETHEUS_ENDPOINT" value="http://127.0.0.1:8889/metrics" />
<!-- Sentinel -->
<const name="REDIS_SENTINEL_SERVICE" value="predis-test" />
<const
+8
View File
@@ -20,6 +20,7 @@ use Predis\CommunicationException;
use Predis\Connection\Cluster\ClusterInterface;
use Predis\Connection\ConnectionInterface;
use Predis\Connection\NodeConnectionInterface;
use Predis\Connection\RelayConnection;
use Predis\Connection\Replication\ReplicationInterface;
use Predis\Connection\Resource\Exception\StreamInitException;
use Predis\Connection\StreamConnection;
@@ -230,6 +231,13 @@ class MetricsCollector
$attributes['network.peer.address'] = trim(substr($peer, 0, $separator), '[]');
$attributes['network.peer.port'] = (int) substr($peer, $separator + 1);
}
} elseif ($node instanceof RelayConnection) {
// Relay does not expose the resolved address of its socket, the configured one is the closest known.
$attributes['network.peer.address'] = $attributes['server.address'];
if (isset($attributes['server.port'])) {
$attributes['network.peer.port'] = $attributes['server.port'];
}
}
return $attributes;
@@ -0,0 +1,188 @@
<?php
/*
* This file is part of the Predis package.
*
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2026 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Predis\Observability;
use OpenTelemetry\Contrib\Otlp\MetricExporter;
use OpenTelemetry\Contrib\Otlp\OtlpHttpTransportFactory;
use OpenTelemetry\SDK\Common\Attribute\Attributes;
use OpenTelemetry\SDK\Metrics\MeterProvider;
use OpenTelemetry\SDK\Metrics\MetricReader\ExportingReader;
use OpenTelemetry\SDK\Resource\ResourceInfo;
use Predis\Response\ServerException;
use PredisTestCase;
/**
* Exports metrics with the OpenTelemetry SDK over OTLP to a collector, then reads them back
* from the Prometheus endpoint of the collector (see .github/otel-collector.yml).
*
* @group otel
*/
class OTelIntegrationTest extends PredisTestCase
{
/**
* @var string
*/
private $runId;
protected function setUp(): void
{
if (!class_exists(MetricExporter::class)) {
$this->markTestSkipped('The OpenTelemetry SDK and OTLP exporter are not installed.');
}
// The collector keeps the series of previous runs, this label tells ours apart.
$this->runId = uniqid('predis');
}
protected function tearDown(): void
{
ObservabilityInstance::getInstance()->init(new OTelConfig());
}
/**
* @group connected
*/
public function testExportsOperationDurationThroughCollector(): void
{
$client = $this->createClient();
$this->initObservability([MetricGroup::COMMAND]);
$client->set('otel:string', 'bar');
$client->get('otel:string');
try {
$client->lpush('otel:string', 'x');
$this->fail('LPUSH on a string key should fail');
} catch (ServerException $exception) {
// Recorded as a failed operation.
}
$client->pipeline(function ($pipeline) {
$pipeline->set('otel:counter', 1);
$pipeline->incr('otel:counter');
$pipeline->get('otel:counter');
});
$client->transaction(function ($transaction) {
$transaction->incr('otel:counter');
});
$this->assertTrue(ObservabilityInstance::getInstance()->forceFlush());
$name = 'db_client_operation_duration_seconds';
$series = $this->scrape($name . '_count', 5);
$node = [
'db_system_name' => 'redis',
'redis_client_library' => 'predis:' . \Predis\Client::VERSION,
'db_namespace' => (string) constant('REDIS_SERVER_DBNUM'),
'server_address' => constant('REDIS_SERVER_HOST'),
'server_port' => (string) constant('REDIS_SERVER_PORT'),
'network_peer_address' => constant('REDIS_SERVER_HOST'),
'network_peer_port' => (string) constant('REDIS_SERVER_PORT'),
'redis_client_operation_retry_attempts' => '0',
];
$this->assertSeries($series, $name . '_count', ['db_operation_name' => 'SET'] + $node);
$this->assertSeries($series, $name . '_count', ['db_operation_name' => 'GET'] + $node);
$this->assertSeries($series, $name . '_count', [
'db_operation_name' => 'LPUSH',
'error_type' => 'WRONGTYPE',
'db_response_status_code' => 'WRONGTYPE',
'redis_client_errors_category' => 'server',
] + $node);
$this->assertSeries($series, $name . '_count', ['db_operation_name' => 'PIPELINE', 'db_operation_batch_size' => '3'] + $node);
$this->assertSeries($series, $name . '_count', ['db_operation_name' => 'MULTI', 'db_operation_batch_size' => '1'] + $node);
// The bucket boundaries advised by Predis reach the backend, not the SDK defaults (0, 5, 10, ...).
$this->assertSeries($series, $name . '_bucket', ['db_operation_name' => 'SET', 'le' => '0.0001']);
$this->assertSeries($series, $name . '_bucket', ['db_operation_name' => 'SET', 'le' => '2.5']);
}
/**
* Enables the given metric groups with a provider exporting to the collector.
*/
private function initObservability(array $groups): void
{
$endpoint = getenv('OTEL_COLLECTOR_ENDPOINT') ?: 'http://127.0.0.1:4318';
$transport = (new OtlpHttpTransportFactory())->create($endpoint . '/v1/metrics', 'application/x-protobuf');
$provider = MeterProvider::builder()
->setResource(ResourceInfo::create(Attributes::create(['service.name' => 'predis-tests'])))
->addReader(new ExportingReader(new MetricExporter($transport)))
->build();
ObservabilityInstance::getInstance()->init(new OTelConfig(
new MetricsConfig([
'enabled' => true,
'enabled_metric_groups' => $groups,
'custom_attributes' => ['test.run' => $this->runId],
]),
$provider
));
}
/**
* Returns the Prometheus series of this run, waiting for the collector to publish them.
*
* @return string[]
*/
private function scrape(string $metric, int $expected): array
{
$endpoint = getenv('OTEL_PROMETHEUS_ENDPOINT') ?: 'http://127.0.0.1:8889/metrics';
for ($attempt = 0; $attempt < 50; ++$attempt) {
$series = array_values(array_filter(explode("\n", (string) @file_get_contents($endpoint)), function (string $line) {
return strpos($line, 'test_run="' . $this->runId . '"') !== false;
}));
$found = array_filter($series, function (string $line) use ($metric) {
return strpos($line, $metric . '{') === 0;
});
if (count($found) >= $expected) {
return $series;
}
usleep(200000);
}
$this->fail("The collector did not publish $expected '$metric' series:\n" . implode("\n", $series));
}
/**
* Asserts that exactly one series has the given name and labels.
*
* @param string[] $series
* @param array<string, string> $labels
*/
private function assertSeries(array $series, string $name, array $labels): void
{
$matches = array_filter($series, function (string $line) use ($name, $labels) {
if (strpos($line, $name . '{') !== 0) {
return false;
}
foreach ($labels as $label => $value) {
if (!preg_match('/[{,]' . $label . '="' . preg_quote($value, '/') . '"/', $line)) {
return false;
}
}
return true;
});
$this->assertCount(1, $matches, "$name " . json_encode($labels) . " not found in:\n" . implode("\n", $series));
}
}
@@ -18,6 +18,7 @@ use OpenTelemetry\API\Metrics\MeterProviderInterface;
use Predis\Client;
use Predis\Command\CommandInterface;
use Predis\Connection\ConnectionException;
use Predis\Connection\RelayConnection;
use Predis\Connection\StreamConnection;
use Predis\Response\Error;
use Predis\Response\ServerException;
@@ -317,6 +318,24 @@ class OperationDurationTest extends PredisTestCase
$this->assertSame(6379, $attributes['network.peer.port']);
}
/**
* @group disconnected
*/
public function testRecordsConfiguredAddressAsPeerWithRelay(): void
{
$this->enableCommandMetrics();
$connection = $this->getMockBuilder(RelayConnection::class)->disableOriginalConstructor()->getMock();
$connection->method('getParameters')->willReturn($this->getParameters(['host' => 'redis.local', 'port' => 6380]));
$connection->method('executeCommand')->willReturn('bar');
(new Client($connection))->get('foo');
$attributes = $this->records[0][1];
$this->assertSame('redis.local', $attributes['network.peer.address']);
$this->assertSame(6380, $attributes['network.peer.port']);
}
/**
* @group disconnected
*/