| 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 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
class OtlpHttpExporter implements ExporterInterface { |
| 17 |
private ClientInterface $client; |
| 18 |
private RequestFactoryInterface $requestFactory; |
| 19 |
private LoggerInterface $logger; |
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
private string $endpoint; |
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
private string $serviceName; |
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
|
| 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 |
|
| 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 |
|
| 100 |
$tracerState->clearSpanContexts(); |
| 101 |
} |
| 102 |
} |