Skip to content

Commit

Permalink
Automatic transaction span with configurable grouping (#125) (#126)
Browse files Browse the repository at this point in the history
Co-Author: Sergey Kleyman
  • Loading branch information
intuibase authored Nov 26, 2024
1 parent fbf71a5 commit 3d75448
Show file tree
Hide file tree
Showing 8 changed files with 750 additions and 2 deletions.
5 changes: 3 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,9 @@
"open-telemetry/opentelemetry-auto-laravel": "0.0.25",
"open-telemetry/opentelemetry-auto-pdo": "0.0.15",
"open-telemetry/opentelemetry-auto-slim": "1.0.6",
"open-telemetry/sdk": "1.0.8",
"php-http/guzzle7-adapter": "^1.0"
"open-telemetry/sdk": "1.1.2",
"php-http/guzzle7-adapter": "^1.0",
"nyholm/psr7-server": "^1.1"
},
"provide": {
"laravel/framework": "*",
Expand Down
3 changes: 3 additions & 0 deletions docs/configure.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,4 +68,7 @@ _Currently there are no additional `OTEL_` options waiting to be contributed ups
|ELASTIC_OTEL_LOG_LEVEL_STDERR|OFF|OFF, CRITICAL, ERROR, WARNING, INFO, DEBUG, TRACE|Log level for the stderr sink. Set to OFF if you don't want to log to a file. This sink is recommended when running the application in a container.
|ELASTIC_OTEL_LOG_LEVEL_SYSLOG|OFF|OFF, CRITICAL, ERROR, WARNING, INFO, DEBUG, TRACE|Log level for file sink. Set to OFF if you don't want to log to file. This sink is recommended when you don't have write access to file system.
|ELASTIC_OTEL_LOG_FEATURES||Comma separated string with FEATURE=LEVEL pairs.<br>Supported features:<br>ALL, MODULE, REQUEST, TRANSPORT, BOOTSTRAP, HOOKS, INSTRUMENTATION|Allows selective setting of log level for features. For example, "ALL=info,TRANSPORT=trace" will result in all other features logging at the info level, while the TRANSPORT feature logs at the trace level. It should be noted that the appropriate log level must be set for the sink - for our example, this would be TRACE.
|ELASTIC_OTEL_TRANSACTION_SPAN_ENABLED|true|true or false|Enables automatic creation of transaction (root) spans for the webserver SAPI. The name of the span will correspond to the request method and path.|
|ELASTIC_OTEL_TRANSACTION_SPAN_ENABLED_CLI|true|true or false|Enables automatic creation of transaction (root) spans for the CLI SAPI. The name of the span will correspond to the script name.|
|ELASTIC_OTEL_TRANSACTION_URL_GROUPS||Comma-separated list of wildcard expressions|Allows grouping multiple URL paths using wildcard expressions, such as `/user/*`. For example, `/user/Alice` and `/user/Bob` will be mapped to the transaction name `/user/*`.|
| <option> | <default value> | <description> |
9 changes: 9 additions & 0 deletions prod/php/ElasticOTel/PhpPartFacade.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@
use Elastic\OTel\Util\HiddenConstructorTrait;
use Elastic\OTel\Log\ElasticLogWriter;
use Elastic\OTel\HttpTransport\ElasticHttpTransportFactory;
use OpenTelemetry\SDK\SdkAutoloader;

use RuntimeException;
use Throwable;

Expand Down Expand Up @@ -90,6 +92,13 @@ public static function bootstrap(string $elasticOTelNativePartVersion, int $maxE
self::registerAsyncTransportFactory();
self::registerOtelLogWriter();

if (SdkAutoloader::isExcludedUrl()) {
BootstrapStageLogger::logDebug('Url is excluded', __FILE__, __LINE__, __CLASS__, __FUNCTION__);
return false;
}

Traces\ElasticRootSpan::startRootSpan();

self::$singletonInstance = new self();
} catch (Throwable $throwable) {
BootstrapStageLogger::logCriticalThrowable($throwable, 'One of the steps in bootstrap sequence has thrown', __FILE__, __LINE__, __CLASS__, __FUNCTION__);
Expand Down
173 changes: 173 additions & 0 deletions prod/php/ElasticOTel/Traces/ElasticRootSpan.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
<?php

/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

declare(strict_types=1);

namespace Elastic\OTel\Traces;

use Http\Discovery\Exception\NotFoundException;
use Http\Discovery\Psr17FactoryDiscovery;
use Nyholm\Psr7Server\ServerRequestCreator;
use OpenTelemetry\API\Globals;
use OpenTelemetry\API\Behavior\LogsMessagesTrait;
use OpenTelemetry\API\Trace\Span;
use OpenTelemetry\API\Trace\SpanKind;
use OpenTelemetry\Context\Context;
use OpenTelemetry\SDK\Common\Configuration\Configuration;
use OpenTelemetry\SDK\Common\Util\ShutdownHandler;
use OpenTelemetry\SemConv\TraceAttributes;
use OpenTelemetry\SemConv\Version;
use Psr\Http\Message\ServerRequestInterface;
use Elastic\OTel\Util\WildcardListMatcher;

class ElasticRootSpan
{
use LogsMessagesTrait;

public static function startRootSpan()
{
if (php_sapi_name() === 'cli') {
if (!Configuration::getBoolean('ELASTIC_OTEL_TRANSACTION_SPAN_ENABLED_CLI', true)) {
self::logDebug('ELASTIC_OTEL_TRANSACTION_SPAN_ENABLED_CLI set to false');
return;
}
} else if (!Configuration::getBoolean('ELASTIC_OTEL_TRANSACTION_SPAN_ENABLED', true)) {
self::logDebug('ELASTIC_OTEL_TRANSACTION_SPAN_ENABLED set to false');
return;
}

$request = self::createRequest();
if ($request) {
self::create($request);
self::registerShutdownHandler($request);
} else {
self::logWarning('Unable to create server request');
}
}

/**
* @psalm-suppress ArgumentTypeCoercion
* @internal
*/
private static function create(ServerRequestInterface $request): void
{
$tracer = Globals::tracerProvider()->getTracer(
'co.elastic.php.elastic-root-span',
null,
Version::VERSION_1_25_0->url(),
);
$parent = Globals::propagator()->extract($request->getHeaders());
$startTime = array_key_exists('REQUEST_TIME_FLOAT', $request->getServerParams())
? $request->getServerParams()['REQUEST_TIME_FLOAT']
: (int) microtime(true);
$span = $tracer->spanBuilder(self::getSpanName($request))
->setSpanKind(SpanKind::KIND_SERVER)
->setStartTimestamp((int) ($startTime * 1_000_000_000))
->setParent($parent)
->setAttribute(TraceAttributes::URL_FULL, (string) $request->getUri())
->setAttribute(TraceAttributes::HTTP_REQUEST_METHOD, $request->getMethod())
->setAttribute(TraceAttributes::HTTP_REQUEST_BODY_SIZE, $request->getHeaderLine('Content-Length'))
->setAttribute(TraceAttributes::USER_AGENT_ORIGINAL, $request->getHeaderLine('User-Agent'))
->setAttribute(TraceAttributes::SERVER_ADDRESS, $request->getUri()->getHost())
->setAttribute(TraceAttributes::SERVER_PORT, $request->getUri()->getPort())
->setAttribute(TraceAttributes::URL_SCHEME, $request->getUri()->getScheme())
->setAttribute(TraceAttributes::URL_PATH, $request->getUri()->getPath())
->startSpan();
Context::storage()->attach($span->storeInContext($parent));
}

/**
* @internal
*/
private static function createRequest(): ?ServerRequestInterface
{
try {
$creator = new ServerRequestCreator(
Psr17FactoryDiscovery::findServerRequestFactory(),
Psr17FactoryDiscovery::findUriFactory(),
Psr17FactoryDiscovery::findUploadedFileFactory(),
Psr17FactoryDiscovery::findStreamFactory(),
);

return $creator->fromGlobals();
} catch (NotFoundException $e) {
self::logError('Unable to initialize server request creator for auto root span creation', ['exception' => $e]);
}

return null;
}

/**
* @internal
*/
private static function registerShutdownHandler($request): void
{
$shutdownFunc = function () use ($request) {
self::shutdownHandler($request);
};

ShutdownHandler::register($shutdownFunc(...));
}

/**
* @internal
*/
public static function shutdownHandler($request): void
{
$scope = Context::storage()->scope();
if (!$scope) {
self::logDebug('Root span not created or ended too early');
return;
}
$scope->detach();
$span = Span::fromContext($scope->context());

if (is_int(http_response_code())) {
$span->setAttribute(TraceAttributes::HTTP_RESPONSE_STATUS_CODE, http_response_code());
} else if (array_key_exists('REDIRECT_STATUS', $request->getServerParams())) {
$span->setAttribute(TraceAttributes::HTTP_RESPONSE_STATUS_CODE, $request->getServerParams()['REDIRECT_STATUS']);
}

$span->end();
}

private static function getSpanName(ServerRequestInterface $request)
{
if (php_sapi_name() === 'cli') {
return self::processPathMatchers($_SERVER['SCRIPT_NAME']);
}

$method = $request->getMethod();
$path = $request->getUri()->getPath();
return $method . " " . self::processPathMatchers($path);
}

private static function processPathMatchers(string $path): string
{
$groups = Configuration::getList('ELASTIC_OTEL_TRANSACTION_URL_GROUPS', []);
if ($groups === null || count($groups) == 0) {
return $path;
}

$matcher = new WildcardListMatcher($groups);
return $matcher->match($path) ?? $path;
}
}
95 changes: 95 additions & 0 deletions prod/php/ElasticOTel/Util/NumericUtil.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
<?php

/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

declare(strict_types=1);

namespace Elastic\OTel\Util;

final class NumericUtil
{
use StaticClassTrait;

/**
* @param float|int $intervalLeft
* @param float|int $x
* @param float|int $intervalRight
*
* @return bool
*/
public static function isInClosedInterval($intervalLeft, $x, $intervalRight): bool
{
return ($intervalLeft <= $x) && ($x <= $intervalRight);
}

/**
* @param mixed $intervalLeft
* @param mixed $x
* @param mixed $intervalRight
*
* @return bool
*
* @template T
* @phpstan-param T $intervalLeft
* @phpstan-param T $x
* @phpstan-param T $intervalRight
*
*/
public static function isInOpenInterval($intervalLeft, $x, $intervalRight): bool
{
return ($intervalLeft < $x) && ($x < $intervalRight);
}

/**
* @param mixed $intervalLeft
* @param mixed $x
* @param mixed $intervalRight
*
* @return bool
*
* @template T
* @phpstan-param T $intervalLeft
* @phpstan-param T $x
* @phpstan-param T $intervalRight
*
*/
public static function isInRightOpenInterval($intervalLeft, $x, $intervalRight): bool
{
return ($intervalLeft <= $x) && ($x < $intervalRight);
}

/**
* @param mixed $intervalLeft
* @param mixed $x
* @param mixed $intervalRight
*
* @return bool
*
* @template T
* @phpstan-param T $intervalLeft
* @phpstan-param T $x
* @phpstan-param T $intervalRight
*
*/
public static function isInLeftOpenInterval($intervalLeft, $x, $intervalRight): bool
{
return ($intervalLeft < $x) && ($x <= $intervalRight);
}
}
Loading

0 comments on commit 3d75448

Please sign in to comment.