Debian Codegraph @

includes/libs/telemetry/OtlpHttpExporter.php

raw symbols SCIP
1 <?php
2 namespace Wikimedia\Telemetry;
3
4 use GuzzleHttp\Psr7\Utils;
5 use Psr\Http\Client\ClientExceptionInterface;
6 use Psr\Http\Client\ClientInterface;
7 use Psr\Http\Message\RequestFactoryInterface;
8 use Psr\Log\LoggerInterface;
9
10 /**
11 * An {@link ExporterInterface} that exports collected data over HTTP, serialized in OTLP JSON format.
12 *
13 * @since 1.43
14 * @internal
15 */
16 class OtlpHttpExporter implements ExporterInterface {
17 private ClientInterface $client;
18 private RequestFactoryInterface $requestFactory;
19 private LoggerInterface $logger;
20
21 /**
22 * URI of the OTLP receiver endpoint to send data to.
23 * @var string
24 */
25 private string $endpoint;
26
27 /**
28 * Descriptive name used to identify this service in traces.
29 * @var string
30 */
31 private string $serviceName;
32
33 /**
34 * The host name of this server to be reported in traces.
35 * @var string
36 */
37 private string $hostName;
38
39 public function __construct(
40 ClientInterface $client,
41 RequestFactoryInterface $requestFactory,
42 LoggerInterface $logger,
43 string $uri,
44 string $serviceName,
45 string $hostName
46 ) {
47 $this->client = $client;
48 $this->requestFactory = $requestFactory;
49 $this->logger = $logger;
50 $this->endpoint = $uri;
51 $this->serviceName = $serviceName;
52 $this->hostName = $hostName;
53 }
54
55 /** @inheritDoc */
56 public function export( TracerState $tracerState ): void {
57 $spanContexts = $tracerState->getSpanContexts();
58 if ( count( $spanContexts ) === 0 ) {
59 return;
60 }
61
62 $resourceInfo = array_filter( [
63 'service.name' => $this->serviceName,
64 'host.name' => $this->hostName,
65 "server.socket.address" => $_SERVER['SERVER_ADDR'] ?? null,
66 ] );
67
68 $data = [
69 'resourceSpans' => [
70 [
71 'resource' => [
72 'attributes' => OtlpSerializer::serializeKeyValuePairs( $resourceInfo )
73 ],
74 'scopeSpans' => [
75 [
76 'scope' => [
77 'name' => 'org.wikimedia.telemetry',
78 ],
79 'spans' => $spanContexts
80 ]
81 ]
82 ]
83 ]
84 ];
85
86 $request = $this->requestFactory->createRequest( 'POST', $this->endpoint )
87 ->withHeader( 'Content-Type', 'application/json' )
88 ->withBody( Utils::streamFor( json_encode( $data ) ) );
89
90 try {
91 $response = $this->client->sendRequest( $request );
92 if ( $response->getStatusCode() !== 200 ) {
93 $this->logger->error( 'Failed to export trace data' );
94 }
95 } catch ( ClientExceptionInterface $e ) {
96 $this->logger->error( 'Failed to connect to exporter', [ 'exception' => $e ] );
97 }
98
99 // Clear out finished spans after exporting them.
100 $tracerState->clearSpanContexts();
101 }
102 }