-
Notifications
You must be signed in to change notification settings - Fork 1.7k
WIP: feat(observability): add base OpenTelemetry span enricher interceptor #17528
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
Draft
chalmerlowe
wants to merge
7
commits into
main
Choose a base branch
from
feat/otel-prototype-interceptor
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.
Draft
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
1231c5a
feat: Add OpenTelemetry environment variable and options configuratio…
chalmerlowe 3915ae2
feat(observability): add base OpenTelemetry span enricher interceptor
chalmerlowe 3a2248c
test(observability): add test-only environment variable overrides and…
chalmerlowe 39cdcd5
feat(observability): simplify options resolver to tracing-only
chalmerlowe 26e8fc1
feat(api-core): implement OtelUnaryClientInterceptor and feature gating
chalmerlowe 91e5ce2
chore(api-core): remove obsolete samples and fix pytest skip logic
chalmerlowe 98b4f27
test(api-core): achieve 100% coverage for observability package
chalmerlowe 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
9 changes: 9 additions & 0 deletions
9
packages/google-api-core/google/api_core/observability/__init__.py
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,9 @@ | ||
| try: | ||
| # Tell flake8 that it's okay this is unused, it's just being exposed to the package namespace. | ||
| from .tracing import OtelUnaryClientInterceptor # noqa: F401 | ||
|
|
||
| __all__ = [ | ||
| "OtelUnaryClientInterceptor", | ||
| ] | ||
| except ImportError: | ||
| __all__ = [] |
96 changes: 96 additions & 0 deletions
96
packages/google-api-core/google/api_core/observability/tracing.py
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,96 @@ | ||
| # Copyright 2026 Google LLC | ||
| # | ||
| # Licensed 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. | ||
|
|
||
| """OpenTelemetry Tracing Enrichment Interceptors.""" | ||
|
|
||
| from typing import Any, Callable, Dict, Optional | ||
|
|
||
| import grpc | ||
| from opentelemetry import trace | ||
|
|
||
|
|
||
| class OtelUnaryClientInterceptor(grpc.UnaryUnaryClientInterceptor): | ||
| """A gRPC client interceptor that creates OpenTelemetry spans for outgoing requests. | ||
|
|
||
| This interceptor explicitly creates a standard SpanKind.CLIENT span for each network attempt | ||
| and enriches it with standard Google Cloud attributes. | ||
| """ | ||
|
|
||
| def __init__( | ||
| self, | ||
| static_attributes: Optional[Dict[str, Any]] = None, | ||
| ): | ||
| """Initializes the OtelUnaryClientInterceptor. | ||
|
|
||
| Args: | ||
| static_attributes: Standard static attributes to attach to every span. | ||
| E.g. {"gcp.client.repo": "googleapis/google-cloud-python"} | ||
| """ | ||
| self._static_attributes = static_attributes or {} | ||
|
|
||
| def intercept_unary_unary( | ||
| self, | ||
| continuation: Callable[[grpc.ClientCallDetails, Any], Any], | ||
| client_call_details: grpc.ClientCallDetails, | ||
| request: Any, | ||
| ) -> Any: | ||
| from google.api_core._feature_gating_helpers import resolve_feature_flags | ||
|
|
||
| # For now, we only check environment variables as we don't have access to ClientOptions here. | ||
| # To support programmatic configuration, we would need to pass it during Client | ||
| # initialization. | ||
| # TODO: we need to refactor resolve_feature_flags to allows feature_key to be optional. | ||
| enabled = resolve_feature_flags( | ||
| env_var="GOOGLE_CLOUD_PYTHON_TRACING_ENABLED", | ||
| feature_key="tracer_provider", | ||
| ) | ||
|
|
||
| if not enabled: | ||
| return continuation(client_call_details, request) | ||
|
|
||
| tracer = trace.get_tracer(__name__) | ||
|
|
||
| # Determine span name (e.g., from client_call_details.method) | ||
| span_name = client_call_details.method | ||
|
|
||
| with tracer.start_as_current_span( | ||
| span_name, kind=trace.SpanKind.CLIENT | ||
| ) as span: | ||
| if span.is_recording(): | ||
| # Inject static attributes | ||
| for key, val in self._static_attributes.items(): | ||
| span.set_attribute(key, val) | ||
|
|
||
| # Extract dynamic attributes from metadata | ||
| for key, value in client_call_details.metadata: | ||
| if key == "x-goog-request-params": | ||
| try: | ||
| # x-goog-request-params is urlencoded string of key=value pairs separated by & | ||
| params = dict( | ||
| p.split("=") for p in value.split("&") if "=" in p | ||
| ) | ||
|
|
||
| # Standard resource identifiers are usually in 'name' or 'parent' | ||
| resource_id = params.get("name") or params.get("parent") | ||
| if resource_id: | ||
| span.set_attribute( | ||
| "gcp.resource.destination.id", resource_id | ||
| ) | ||
| except Exception: | ||
| # Fail open if parsing fails to avoid breaking the request | ||
| pass | ||
|
|
||
| span.set_attribute("rpc.system.name", "grpc") | ||
|
|
||
| return continuation(client_call_details, request) | ||
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 |
|---|---|---|
|
|
@@ -12,3 +12,4 @@ requests==2.33.0 | |
| grpcio==1.41.0 | ||
| grpcio-status==1.41.0 | ||
| proto-plus==1.24.0 | ||
| opentelemetry-api==1.27.0 | ||
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 |
|---|---|---|
|
|
@@ -13,3 +13,4 @@ grpcio==1.41.0 | |
| grpcio-status==1.41.0 | ||
| proto-plus==1.24.0 | ||
| aiohttp==3.13.4 | ||
| opentelemetry-api==1.27.0 | ||
53 changes: 53 additions & 0 deletions
53
packages/google-api-core/tests/unit/observability/test_init.py
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,53 @@ | ||
| # Copyright 2026 Google LLC | ||
| # | ||
| # Licensed 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. | ||
|
|
||
| """Tests for google.api_core.observability.__init__.""" | ||
|
|
||
| import importlib | ||
| import sys | ||
|
|
||
|
|
||
| def test_init_exports(): | ||
| import google.api_core.observability | ||
|
|
||
| # Check if dependencies are available | ||
| try: | ||
| import grpc # noqa: F401 | ||
| import opentelemetry.trace # noqa: F401 | ||
|
|
||
| has_deps = True | ||
| except ImportError: | ||
| has_deps = False | ||
|
|
||
| if has_deps: | ||
| assert "OtelUnaryClientInterceptor" in google.api_core.observability.__all__ | ||
| else: | ||
| assert google.api_core.observability.__all__ == [] | ||
|
|
||
|
|
||
| def test_init_import_error_forced(monkeypatch): | ||
| """Verifies behavior when tracing module fails to import, even if deps are present.""" | ||
| import google.api_core.observability | ||
|
|
||
| # Poison the tracing module | ||
| monkeypatch.setitem(sys.modules, "google.api_core.observability.tracing", None) | ||
|
|
||
| # Reload observability, it should fail to import tracing and trigger except block | ||
| importlib.reload(google.api_core.observability) | ||
|
|
||
| assert google.api_core.observability.__all__ == [] | ||
|
|
||
| # Clean up | ||
| monkeypatch.undo() | ||
| importlib.reload(google.api_core.observability) |
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.
Issues Identified:
client_call_details.metadatacan beNoneif no metadata is provided for the gRPC call. Iterating over it directly will raise aTypeErrorand crash the RPC call.bytesinstead ofstr. Ifvalueisbytes, calling.split("&")with a string argument will raise aTypeErrorand silently fail open.x-goog-request-paramsare URL-encoded. Standard resource identifiers (e.g., containing slashes or special characters) should be URL-decoded usingurllib.parse.unquotebefore being set as the span attribute.except Exception:blocks that silently pass or ignore errors. Instead, log the exception to aid in debugging and prevent masking underlying issues.Recommendation:
Update the metadata extraction loop to handle
Nonemetadata gracefully, decodebytesvalues tostr, URL-decode the extracted resource ID, and log any parsing exceptions instead of silently passing.References