-
Notifications
You must be signed in to change notification settings - Fork 204
Support other propagators in Python Layer #124
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
Changes from 4 commits
2bcabf5
4965453
da03b2f
6461cf0
930d98c
aaa09bd
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -47,19 +47,27 @@ def lambda_handler(event, context): | |
import logging | ||
import os | ||
from importlib import import_module | ||
from typing import Collection | ||
from wrapt import wrap_function_wrapper | ||
from typing import Any, Collection | ||
|
||
# TODO: aws propagator | ||
from opentelemetry.sdk.extension.aws.trace.propagation.aws_xray_format import ( | ||
AwsXRayFormat, | ||
) | ||
from opentelemetry.context.context import Context | ||
from opentelemetry.instrumentation.aws_lambda.package import _instruments | ||
from opentelemetry.instrumentation.aws_lambda.version import __version__ | ||
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor | ||
from opentelemetry.instrumentation.utils import unwrap | ||
from opentelemetry.propagate import get_global_textmap | ||
from opentelemetry.sdk.extension.aws.trace.propagation.aws_xray_format import ( | ||
TRACE_HEADER_KEY, | ||
AwsXRayFormat, | ||
) | ||
from opentelemetry.semconv.trace import SpanAttributes | ||
from opentelemetry.trace import SpanKind, get_tracer, get_tracer_provider | ||
from opentelemetry.trace import ( | ||
SpanKind, | ||
Tracer, | ||
get_tracer, | ||
get_tracer_provider, | ||
) | ||
from opentelemetry.trace.propagation import get_current_span | ||
from wrapt import wrap_function_wrapper | ||
|
||
logger = logging.getLogger(__name__) | ||
|
||
|
@@ -69,15 +77,22 @@ def instrumentation_dependencies(self) -> Collection[str]: | |
return _instruments | ||
|
||
def _instrument(self, **kwargs): | ||
"""Instruments Lambda Handlers on AWS Lambda | ||
"""Instruments Lambda Handlers on AWS Lambda. | ||
|
||
See more: | ||
https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/instrumentation/aws-lambda.md#instrumenting-aws-lambda | ||
|
||
Args: | ||
**kwargs: Optional arguments | ||
``tracer_provider``: a TracerProvider, defaults to global | ||
``event_context_extractor``: a method which takes the Lambda | ||
Event as input and extracts an OTel Context from it. Usually | ||
the the context is extract from HTTP headers on the event. | ||
""" | ||
tracer = get_tracer( | ||
__name__, __version__, kwargs.get("tracer_provider") | ||
) | ||
event_context_extractor = kwargs.get("event_context_extractor") | ||
|
||
lambda_handler = os.environ.get( | ||
"ORIG_HANDLER", os.environ.get("_HANDLER") | ||
|
@@ -87,7 +102,10 @@ def _instrument(self, **kwargs): | |
self._wrapped_function_name = wrapped_names[1] | ||
|
||
_instrument( | ||
tracer, self._wrapped_module_name, self._wrapped_function_name | ||
tracer, | ||
self._wrapped_module_name, | ||
self._wrapped_function_name, | ||
event_context_extractor, | ||
) | ||
|
||
def _uninstrument(self, **kwargs): | ||
|
@@ -97,16 +115,80 @@ def _uninstrument(self, **kwargs): | |
) | ||
|
||
|
||
def _instrument(tracer, wrapped_module_name, wrapped_function_name): | ||
def _default_event_context_extractor(lambda_event: Any) -> Context: | ||
"""Default way of extracting the context from the Lambda Event. | ||
|
||
Assumes the Lambda Event is a map with the headers under the 'headers' key. | ||
This is the mapping to use when the Lambda is invoked by an API Gateway | ||
REST API where API Gateway is acting as a pure proxy for the request. | ||
|
||
See more: | ||
https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-input-format | ||
|
||
Args: | ||
lambda_event: user-defined, so it could be anything, but this | ||
method counts it being a map with a 'headers' key | ||
Returns: | ||
A Context with configuration found in the carrier. | ||
NathanielRN marked this conversation as resolved.
Show resolved
Hide resolved
|
||
""" | ||
try: | ||
headers = lambda_event["headers"] | ||
except (TypeError, KeyError): | ||
logger.warning("Failed to extract context from Lambda Event.") | ||
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. We can add more on what a user should do if they see this error. Either X-Ray needs to be enabled or the function must be serving API Gateway as a HTTP proxy. Otherwise, this instrumentation should not be included. Something like that 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. That makes sense to me. What do you think about
? I'm wondering if there's a use case where someone would want instrumentation and they're okay with the empty parent context. That's why I though "instrumentation should not be included" to not fit as well. As does the 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. Hmm - I guess there is a use case where the function does not use X-Ray, and is not API Gateway but meant to always be a root - still it would be a bit weird to have no ability to parent at all but it's conceivable. Your message seems fine then, and yeah it should be debug level if there is a conceivable use case for it rather than always being in error. 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. Yeah like if they just trigger it from the console is the easiest case I can think of. Maybe that Lambda triggers another Lambda 😝 I've made the updates 👍 |
||
headers = {} | ||
return get_global_textmap().extract(headers) | ||
|
||
|
||
def _instrument( | ||
tracer: Tracer, | ||
wrapped_module_name, | ||
wrapped_function_name, | ||
event_context_extractor=None, | ||
): | ||
def _determine_parent_context(lambda_event: Any) -> Context: | ||
"""Determine the parent context for the current Lambda invocation. | ||
|
||
See more: | ||
https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/instrumentation/aws-lambda.md#determining-the-parent-of-a-span | ||
|
||
Args: | ||
lambda_event: user-defined, so it could be anything, but this | ||
method counts it being a map with a 'headers' key | ||
Returns: | ||
A Context with configuration found in the carrier. | ||
""" | ||
parent_context = None | ||
|
||
xray_env_var = os.environ.get("_X_AMZN_TRACE_ID") | ||
|
||
if xray_env_var: | ||
parent_context = AwsXRayFormat().extract( | ||
{TRACE_HEADER_KEY: xray_env_var} | ||
) | ||
|
||
if ( | ||
parent_context | ||
and get_current_span(parent_context) | ||
.get_span_context() | ||
.trace_flags.sampled | ||
): | ||
return parent_context | ||
|
||
if event_context_extractor: | ||
parent_context = event_context_extractor(lambda_event) | ||
else: | ||
parent_context = _default_event_context_extractor(lambda_event) | ||
|
||
return parent_context | ||
|
||
def _instrumented_lambda_handler_call(call_wrapped, instance, args, kwargs): | ||
orig_handler_name = ".".join( | ||
[wrapped_module_name, wrapped_function_name] | ||
) | ||
|
||
# TODO: enable propagate from AWS by env variable | ||
xray_trace_id = os.environ.get("_X_AMZN_TRACE_ID", "") | ||
propagator = AwsXRayFormat() | ||
parent_context = propagator.extract({"X-Amzn-Trace-Id": xray_trace_id}) | ||
lambda_event = args[0] | ||
|
||
parent_context = _determine_parent_context(lambda_event) | ||
|
||
with tracer.start_as_current_span( | ||
name=orig_handler_name, context=parent_context, kind=SpanKind.SERVER | ||
|
Uh oh!
There was an error while loading. Please reload this page.