diff --git a/.github/docker-compose.yml b/.github/docker-compose.yml index 1ea14c2d..e023f1ed 100644 --- a/.github/docker-compose.yml +++ b/.github/docker-compose.yml @@ -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 diff --git a/.github/otel-collector.yml b/.github/otel-collector.yml new file mode 100644 index 00000000..1f88f2e1 --- /dev/null +++ b/.github/otel-collector.yml @@ -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] diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 37feaf8f..fbf71d47 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -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' }} diff --git a/README.md b/README.md index 9f42e312..9b59e9d3 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/examples/otel_metrics.php b/examples/otel_metrics.php new file mode 100644 index 00000000..f7bda0be --- /dev/null +++ b/examples/otel_metrics.php @@ -0,0 +1,95 @@ +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; diff --git a/phpstan-tests.dist.neon b/phpstan-tests.dist.neon index d1afbdb4..c78f575c 100644 --- a/phpstan-tests.dist.neon +++ b/phpstan-tests.dist.neon @@ -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\\(\\)\\.$#" diff --git a/phpunit.relay.xml b/phpunit.relay.xml index e7bb768e..ab08901a 100644 --- a/phpunit.relay.xml +++ b/phpunit.relay.xml @@ -30,6 +30,7 @@ cluster gears unprotected + otel @@ -48,6 +49,10 @@ + + + + gears-cluster unprotected sentinel + otel @@ -56,6 +57,10 @@ + + + + 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 $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)); + } +} diff --git a/tests/Predis/Observability/OperationDurationTest.php b/tests/Predis/Observability/OperationDurationTest.php index c1276074..e1c42a5e 100644 --- a/tests/Predis/Observability/OperationDurationTest.php +++ b/tests/Predis/Observability/OperationDurationTest.php @@ -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 */