-
Notifications
You must be signed in to change notification settings - Fork 190
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
attribute-based sampler #1208
Closed
Closed
attribute-based sampler #1208
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
f09cf80
attribute-based sampler
brettmc a118add
fix example
brettmc 07aa871
require pcre extension
brettmc cd89c60
fixing logging failures
brettmc 35cef0e
update sampler comments
brettmc 6caab08
add test for invalid args
brettmc fcbccbc
linting
brettmc 47bd899
Merge branch 'main' into attribute_sampler
brettmc File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
<?php | ||
|
||
declare(strict_types=1); | ||
|
||
namespace OpenTelemetry\Example; | ||
|
||
require __DIR__ . '/../../../vendor/autoload.php'; | ||
|
||
use OpenTelemetry\SDK\Trace\TracerProviderFactory; | ||
use OpenTelemetry\SemConv\TraceAttributes; | ||
|
||
//@see https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/configuration/sdk-environment-variables.md | ||
putenv('OTEL_RESOURCE_ATTRIBUTES=service.version=1.0.0'); | ||
putenv('OTEL_SERVICE_NAME=example-app'); | ||
putenv('OTEL_PHP_DETECTORS=none'); | ||
putenv('OTEL_LOG_LEVEL=warning'); | ||
putenv('OTEL_TRACES_SAMPLER=parentbased,attribute,traceidratio'); | ||
putenv('OTEL_TRACES_SAMPLER_ARG=attribute.name=url.path,attribute.mode=deny,attribute.pattern=\/health$|\/test$,traceidratio.probability=1.0'); | ||
putenv('OTEL_TRACES_EXPORTER=console'); | ||
|
||
echo 'Starting attribute-based sampler example' . PHP_EOL; | ||
|
||
$tracerProvider = (new TracerProviderFactory())->create(); | ||
|
||
$tracer = $tracerProvider->getTracer('io.opentelemetry.contrib.php'); | ||
|
||
echo 'Starting Tracer' . PHP_EOL; | ||
|
||
$span = $tracer->spanBuilder('root')->setAttribute(TraceAttributes::URL_PATH, '/health')->startSpan(); | ||
$scope = $span->activate(); | ||
|
||
try { | ||
//this span will be sampled iff the root was sampled (parent-based) | ||
$tracer->spanBuilder('child')->startSpan()->end(); | ||
} finally { | ||
$scope->detach(); | ||
} | ||
$span->end(); | ||
|
||
$tracerProvider->shutdown(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,114 @@ | ||
<?php | ||
|
||
declare(strict_types=1); | ||
|
||
namespace OpenTelemetry\SDK\Trace\Sampler; | ||
|
||
use InvalidArgumentException; | ||
use OpenTelemetry\API\Behavior\LogsMessagesTrait; | ||
use OpenTelemetry\Context\ContextInterface; | ||
use OpenTelemetry\SDK\Common\Attribute\AttributesInterface; | ||
use OpenTelemetry\SDK\Trace\SamplerInterface; | ||
use OpenTelemetry\SDK\Trace\SamplingResult; | ||
|
||
/** | ||
* @phan-file-suppress PhanParamTooFewUnpack | ||
* | ||
* Attribute-based sampler. This sampler should be called after a ParentBased sampler, and requires | ||
* another sampler (such as AlwaysOnSampler). | ||
* For example, ParentBased,AttributeBased(<deny if url.path attribute matches /health>),TradeIdRatio(0.5) means | ||
* 1. Trace if parent is already sampled; otherwise | ||
* 2. Do not sample if url.path attribute is set and matches /health; otherwise | ||
* 3. Sample 50% of traces | ||
* | ||
* Two modes exist: | ||
* "allow" mode: always sample if attribute exists and matches the pattern, else do not sample | ||
* "deny" mode: do not sample if attribute exists and matches the pattern, else defer to next sampler | ||
*/ | ||
class AttributeBasedSampler implements SamplerInterface | ||
{ | ||
use LogsMessagesTrait; | ||
|
||
public const ALLOW = 'allow'; | ||
public const DENY = 'deny'; | ||
public const MODES = [ | ||
self::ALLOW, | ||
self::DENY, | ||
]; | ||
|
||
private SamplerInterface $delegate; | ||
private string $mode; | ||
private string $attribute; | ||
private string $pattern; | ||
|
||
/** | ||
* @param SamplerInterface $delegate The sampler to defer to if a decision is not made by this sampler | ||
* @param string $mode Sampling mode (deny or allow) | ||
* @param string $attribute The SemConv trace attribute to test against, eg http.path, http.method | ||
* @param string $pattern The PCRE regex pattern to match against, eg /\/health$|\/test$/ | ||
*/ | ||
public function __construct(SamplerInterface $delegate, string $mode, string $attribute, string $pattern) | ||
{ | ||
if (!in_array($mode, self::MODES)) { | ||
throw new InvalidArgumentException('Unknown Attribute sampler mode: ' . $mode); | ||
} | ||
$this->delegate = $delegate; | ||
$this->mode = $mode; | ||
$this->attribute = $attribute; | ||
$this->pattern = $pattern; | ||
} | ||
|
||
public function shouldSample(ContextInterface $parentContext, string $traceId, string $spanName, int $spanKind, AttributesInterface $attributes, array $links): SamplingResult | ||
{ | ||
switch ($this->mode) { | ||
case self::ALLOW: | ||
if (!$attributes->has($this->attribute)) { | ||
return new SamplingResult(SamplingResult::DROP); | ||
} | ||
if ($this->matches((string) $attributes->get($this->attribute))) { | ||
return new SamplingResult(SamplingResult::RECORD_AND_SAMPLE); | ||
} | ||
|
||
break; | ||
case self::DENY: | ||
if (!$attributes->has($this->attribute)) { | ||
break; | ||
} | ||
if ($this->matches((string) $attributes->get($this->attribute))) { | ||
return new SamplingResult(SamplingResult::DROP); | ||
} | ||
|
||
break; | ||
default: | ||
//do nothing | ||
} | ||
|
||
return $this->delegate->shouldSample(...func_get_args()); | ||
} | ||
|
||
/** | ||
* @todo call preg_last_error_msg directly after 7.4 support dropped | ||
* @phan-suppress PhanUndeclaredFunctionInCallable | ||
*/ | ||
private function matches(string $value): bool | ||
{ | ||
$result = @preg_match($this->pattern, $value); | ||
if ($result === false) { | ||
self::logWarning('Error when pattern matching attribute', [ | ||
'attribute.name' => $this->attribute, | ||
'attribute.value' => $value, | ||
'pattern' => $this->pattern, | ||
'error' => function_exists('preg_last_error_msg') ? call_user_func('preg_last_error_msg') : '', | ||
]); | ||
|
||
return false; | ||
} | ||
|
||
return (bool) $result; | ||
} | ||
|
||
public function getDescription(): string | ||
{ | ||
return sprintf('AttributeSampler{mode=%s,attribute=%s,pattern=%s}+%s', $this->mode, $this->attribute, $this->pattern, $this->delegate->getDescription()); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -19,6 +19,7 @@ | |
"require": { | ||
"php": "^7.4 || ^8.0", | ||
"ext-json": "*", | ||
"ext-pcre": "*", | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. IMO we shouldn't list core extensions as requirement |
||
"open-telemetry/api": "^1.0", | ||
"open-telemetry/context": "^1.0", | ||
"open-telemetry/sem-conv": "^1.0", | ||
|
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I was just reading about the idea of a rule-based sampler in this OTEP and I like the idea of using that approach over what I've done here, given the increased usefulness (and hopefully also compatibility with the proposed sampling configuration).
The prototype looks great, I think we should go with that approach. For the time being, it might not be configurable via env vars (and so not available to auto-instrumentation/sdk-autoloading) due to the complexity of the configuration.