-
Notifications
You must be signed in to change notification settings - Fork 0
Add custom instrumentation for user-defined class/method hooks #6
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
Open
kaz29
wants to merge
4
commits into
main
Choose a base branch
from
feat/custom-instrumentation
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+672
−5
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
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 hidden or 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 hidden or 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 hidden or 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 hidden or 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,212 @@ | ||
| <?php | ||
| declare(strict_types=1); | ||
|
|
||
| namespace OtelInstrumentation\Instrumentation; | ||
|
|
||
| use OpenTelemetry\API\Instrumentation\CachedInstrumentation; | ||
| use OpenTelemetry\API\Trace\Span; | ||
| use OpenTelemetry\API\Trace\SpanKind; | ||
| use OpenTelemetry\API\Trace\StatusCode; | ||
| use OpenTelemetry\Context\Context; | ||
|
|
||
| final class CustomInstrumentation | ||
| { | ||
| /** @var HookDefinition[] */ | ||
| private static array $definitions = []; | ||
|
|
||
| /** @var array<string, true> */ | ||
| private static array $registeredKeys = []; | ||
|
|
||
| private static bool $applied = false; | ||
|
|
||
| /** | ||
| * Register a hook for a class method. | ||
| * | ||
| * @param class-string $class | ||
| * @param string $method | ||
| * @param string|null $spanName Override span name (default: FQCN::method) | ||
| * @param int $kind SpanKind constant (default: KIND_INTERNAL) | ||
| * @param array<string, mixed> $attributes Static attributes | ||
| * @param (\Closure(object|null, array, string, string): array<string, mixed>)|null $attributeCallback | ||
| */ | ||
| public static function register( | ||
| string $class, | ||
| string $method, | ||
| ?string $spanName = null, | ||
| int $kind = SpanKind::KIND_INTERNAL, | ||
| array $attributes = [], | ||
| ?\Closure $attributeCallback = null, | ||
| ): void { | ||
| $definition = new HookDefinition( | ||
| class: $class, | ||
| method: $method, | ||
| spanName: $spanName, | ||
| kind: $kind, | ||
| attributes: $attributes, | ||
| attributeCallback: $attributeCallback, | ||
| ); | ||
|
|
||
| if (!self::addDefinition($definition)) { | ||
| return; | ||
| } | ||
|
|
||
| if (self::$applied) { | ||
| self::applyDefinition($definition); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Register from a HookDefinition directly. | ||
| */ | ||
| public static function add(HookDefinition $definition): void | ||
| { | ||
| if (!self::addDefinition($definition)) { | ||
| return; | ||
| } | ||
|
|
||
| if (self::$applied) { | ||
| self::applyDefinition($definition); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Load hook definitions from Configure-style array format. | ||
| * | ||
| * @param array<array{class: class-string, method: string, spanName?: string, kind?: int, attributes?: array<string, mixed>, attributeCallback?: \Closure}> $configs | ||
| */ | ||
| public static function loadFromConfig(array $configs): void | ||
| { | ||
| foreach ($configs as $i => $config) { | ||
| if (!isset($config['class']) || !isset($config['method'])) { | ||
| throw new \InvalidArgumentException( | ||
| sprintf('OtelInstrumentation.hooks[%d] must have "class" and "method" keys.', $i) | ||
| ); | ||
| } | ||
|
|
||
| $definition = new HookDefinition( | ||
| class: $config['class'], | ||
| method: $config['method'], | ||
| spanName: $config['spanName'] ?? null, | ||
| kind: $config['kind'] ?? SpanKind::KIND_INTERNAL, | ||
| attributes: $config['attributes'] ?? [], | ||
| attributeCallback: $config['attributeCallback'] ?? null, | ||
| ); | ||
|
|
||
| if (!self::addDefinition($definition)) { | ||
| continue; | ||
| } | ||
|
|
||
| if (self::$applied) { | ||
| self::applyDefinition($definition); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Apply all registered hooks via \OpenTelemetry\Instrumentation\hook(). | ||
| * Called during Plugin::bootstrap(). Definitions registered after apply() | ||
| * will be hooked immediately. | ||
| */ | ||
| public static function apply(): void | ||
| { | ||
| if (self::$applied) { | ||
| return; | ||
| } | ||
| self::$applied = true; | ||
|
|
||
| foreach (self::$definitions as $definition) { | ||
| self::applyDefinition($definition); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Add a definition if not already registered for the same class/method. | ||
| * | ||
| * @return bool true if added, false if duplicate | ||
| */ | ||
| private static function addDefinition(HookDefinition $definition): bool | ||
| { | ||
| $key = $definition->class . '::' . $definition->method; | ||
| if (isset(self::$registeredKeys[$key])) { | ||
| return false; | ||
| } | ||
|
|
||
| self::$registeredKeys[$key] = true; | ||
| self::$definitions[] = $definition; | ||
|
|
||
| return true; | ||
| } | ||
|
|
||
| private static function applyDefinition(HookDefinition $def): void | ||
| { | ||
| $instrumentation = new CachedInstrumentation('otel-instrumentation.cakephp.custom'); | ||
|
|
||
| \OpenTelemetry\Instrumentation\hook( | ||
| class: $def->class, | ||
| function: $def->method, | ||
| pre: static function ( | ||
| mixed $instance, | ||
| array $params, | ||
| string $class, | ||
| string $function, | ||
| ?string $filename, | ||
| ?int $lineno, | ||
| ) use ($instrumentation, $def): void { | ||
| $spanBuilder = $instrumentation->tracer() | ||
| ->spanBuilder($def->spanName ?? ($class . '::' . $function)) | ||
| ->setSpanKind($def->kind); | ||
|
|
||
| foreach ($def->attributes as $key => $value) { | ||
| $spanBuilder->setAttribute($key, $value); | ||
| } | ||
|
|
||
| if ($def->attributeCallback !== null) { | ||
| try { | ||
| $dynamicAttrs = ($def->attributeCallback)($instance, $params, $class, $function); | ||
| foreach ($dynamicAttrs as $key => $value) { | ||
| $spanBuilder->setAttribute($key, $value); | ||
| } | ||
| } catch (\Throwable) { | ||
| // Instrumentation must not break application code | ||
| } | ||
| } | ||
|
|
||
| $span = $spanBuilder->startSpan(); | ||
| Context::storage()->attach($span->storeInContext(Context::getCurrent())); | ||
| }, | ||
| post: static function ( | ||
| mixed $instance, | ||
| array $params, | ||
| mixed $returnValue, | ||
| ?\Throwable $exception, | ||
| ): void { | ||
| $scope = Context::storage()->scope(); | ||
| if ($scope === null) { | ||
| return; | ||
| } | ||
|
|
||
| $scope->detach(); | ||
| $span = Span::fromContext($scope->context()); | ||
|
|
||
| if ($exception !== null) { | ||
| $span->recordException($exception); | ||
| $span->setStatus(StatusCode::STATUS_ERROR, $exception->getMessage()); | ||
| } else { | ||
| $span->setStatus(StatusCode::STATUS_OK); | ||
| } | ||
|
|
||
| $span->end(); | ||
| }, | ||
| ); | ||
| } | ||
|
|
||
| /** | ||
| * Reset state (for testing). | ||
| */ | ||
| public static function reset(): void | ||
| { | ||
| self::$definitions = []; | ||
| self::$registeredKeys = []; | ||
| self::$applied = false; | ||
| } | ||
| } | ||
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.
CustomInstrumentation::apply() becomes a one-shot toggle (self::$applied). Because Plugin::bootstrap() calls apply() unconditionally, any later CustomInstrumentation::register()/add()/loadFromConfig() calls will never take effect. Consider either (a) making register/add/loadFromConfig immediately hook definitions when already applied, or (b) tracking which definitions have been hooked and allowing apply() to be called multiple times to apply newly registered hooks.