-
Notifications
You must be signed in to change notification settings - Fork 180
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
feat: AWS lambda programatic wrap #1308
Draft
joshwestbrook
wants to merge
1
commit into
open-telemetry:main
Choose a base branch
from
joshwestbrook:aws_lambda-programatic-wrap
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
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
171 changes: 171 additions & 0 deletions
171
instrumentation/aws_lambda/lib/opentelemetry/instrumentation/aws_lambda/wrap.rb
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,171 @@ | ||
# frozen_string_literal: true | ||
|
||
# Copyright The OpenTelemetry Authors | ||
# | ||
# SPDX-License-Identifier: Apache-2.0 | ||
|
||
module OpenTelemetry | ||
module Instrumentation | ||
module AwsLambda | ||
# Helper module that can be used to wrap a lambda handler method | ||
module Wrap | ||
AWS_TRIGGERS = ['aws:sqs', 'aws:s3', 'aws:sns', 'aws:dynamodb'].freeze | ||
DEFAULT_FLUSH_TIMEOUT = ENV.fetch('OTEL_INSTRUMENTATION_AWS_LAMBDA_FLUSH_TIMEOUT', '30000').to_i | ||
|
||
def instrument_handler(method, flush_timeout: DEFAULT_FLUSH_TIMEOUT) | ||
raise ArgumentError, "#{method} is not a method of #{name}" unless respond_to?(method) | ||
|
||
uninstrumented_method = "#{method}_without_instrumentation" | ||
singleton_class.alias_method uninstrumented_method, method | ||
|
||
handler = "#{name}.#{method}" | ||
|
||
define_singleton_method(method) do |event:, context:| | ||
wrap_lambda(event:, context:, handler:, flush_timeout:) { public_send(uninstrumented_method, event:, context:) } | ||
end | ||
end | ||
|
||
# Try to record and re-raise any exception from the wrapped function handler | ||
# Instrumentation should never raise its own exception | ||
def wrap_lambda(event:, context:, handler:, flush_timeout: DEFAULT_FLUSH_TIMEOUT) | ||
parent_context = extract_parent_context(event) | ||
|
||
span_kind = if event['Records'] && AWS_TRIGGERS.include?(event['Records'].dig(0, 'eventSource')) | ||
:consumer | ||
else | ||
:server | ||
end | ||
|
||
original_handler_error = nil | ||
original_response = nil | ||
OpenTelemetry::Context.with_current(parent_context) do | ||
tracer.in_span(handler, attributes: otel_attributes(event, context), kind: span_kind) do |span| | ||
begin | ||
response = yield | ||
|
||
unless span.attributes.key?(OpenTelemetry::SemanticConventions::Trace::HTTP_STATUS_CODE) | ||
status_code = response['statusCode'] || response[:statusCode] if response.is_a?(Hash) | ||
span.set_attribute(OpenTelemetry::SemanticConventions::Trace::HTTP_STATUS_CODE, status_code) if status_code | ||
end | ||
rescue StandardError => e | ||
original_handler_error = e | ||
ensure | ||
original_response = response | ||
end | ||
if original_handler_error | ||
span.record_exception(original_handler_error) | ||
span.status = OpenTelemetry::Trace::Status.error(original_handler_error.message) | ||
end | ||
end | ||
end | ||
|
||
OpenTelemetry.tracer_provider.force_flush(timeout: flush_timeout) | ||
OpenTelemetry.meter_provider.force_flush(timeout: flush_timeout) | ||
|
||
raise original_handler_error if original_handler_error | ||
|
||
original_response | ||
end | ||
|
||
def instrumentation_config | ||
AwsLambda::Instrumentation.instance.config | ||
end | ||
|
||
def tracer | ||
AwsLambda::Instrumentation.instance.tracer | ||
end | ||
|
||
private | ||
|
||
# Extract parent context from request headers | ||
# Downcase Traceparent and Tracestate because TraceContext::TextMapPropagator's TRACEPARENT_KEY and TRACESTATE_KEY are all lowercase | ||
# If any error occur, rescue and give empty context | ||
def extract_parent_context(event) | ||
headers = event['headers'] || {} | ||
headers.transform_keys! do |key| | ||
%w[Traceparent Tracestate].include?(key) ? key.downcase : key | ||
end | ||
|
||
OpenTelemetry.propagation.extract( | ||
headers, | ||
getter: OpenTelemetry::Context::Propagation.text_map_getter | ||
) | ||
rescue StandardError => e | ||
OpenTelemetry.logger.error("aws-lambda instrumentation exception occurred while extracting the parent context: #{e.message}") | ||
OpenTelemetry::Context.empty | ||
end | ||
|
||
# lambda event version 1.0 and version 2.0 | ||
# https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-integrations-lambda.html | ||
def v1_proxy_attributes(event) | ||
attributes = { | ||
OpenTelemetry::SemanticConventions::Trace::HTTP_METHOD => event['httpMethod'], | ||
OpenTelemetry::SemanticConventions::Trace::HTTP_ROUTE => event['resource'], | ||
OpenTelemetry::SemanticConventions::Trace::HTTP_TARGET => event['resource'] | ||
} | ||
attributes[OpenTelemetry::SemanticConventions::Trace::HTTP_TARGET] += "?#{event['queryStringParameters']}" if event['queryStringParameters'] | ||
|
||
headers = event['headers'] | ||
if headers | ||
attributes[OpenTelemetry::SemanticConventions::Trace::HTTP_USER_AGENT] = headers['User-Agent'] | ||
attributes[OpenTelemetry::SemanticConventions::Trace::HTTP_SCHEME] = headers['X-Forwarded-Proto'] | ||
attributes[OpenTelemetry::SemanticConventions::Trace::NET_HOST_NAME] = headers['Host'] | ||
end | ||
attributes | ||
end | ||
|
||
def v2_proxy_attributes(event) | ||
request_context = event['requestContext'] | ||
attributes = { | ||
OpenTelemetry::SemanticConventions::Trace::NET_HOST_NAME => request_context['domainName'], | ||
OpenTelemetry::SemanticConventions::Trace::HTTP_METHOD => request_context['http']['method'], | ||
OpenTelemetry::SemanticConventions::Trace::HTTP_USER_AGENT => request_context['http']['userAgent'], | ||
OpenTelemetry::SemanticConventions::Trace::HTTP_ROUTE => request_context['http']['path'], | ||
OpenTelemetry::SemanticConventions::Trace::HTTP_TARGET => request_context['http']['path'] | ||
} | ||
attributes[OpenTelemetry::SemanticConventions::Trace::HTTP_TARGET] += "?#{event['rawQueryString']}" if event['rawQueryString'] | ||
attributes | ||
end | ||
|
||
# fass.trigger set to http: https://github.com/open-telemetry/semantic-conventions/blob/main/docs/faas/aws-lambda.md#api-gateway | ||
# TODO: need to update Semantic Conventions for invocation_id, trigger and resource_id | ||
def otel_attributes(event, context) | ||
span_attributes = {} | ||
span_attributes['faas.invocation_id'] = context.aws_request_id | ||
span_attributes['cloud.resource_id'] = context.invoked_function_arn | ||
span_attributes[OpenTelemetry::SemanticConventions::Trace::AWS_LAMBDA_INVOKED_ARN] = context.invoked_function_arn | ||
span_attributes[OpenTelemetry::SemanticConventions::Resource::CLOUD_ACCOUNT_ID] = context.invoked_function_arn.split(':')[4] | ||
|
||
if event['requestContext'] | ||
request_attributes = event['version'] == '2.0' ? v2_proxy_attributes(event) : v1_proxy_attributes(event) | ||
request_attributes[OpenTelemetry::SemanticConventions::Trace::FAAS_TRIGGER] = 'http' | ||
span_attributes.merge!(request_attributes) | ||
end | ||
|
||
if event['Records'] | ||
trigger_attributes = trigger_type_attributes(event) | ||
span_attributes.merge!(trigger_attributes) | ||
end | ||
|
||
span_attributes | ||
rescue StandardError => e | ||
OpenTelemetry.logger.error("aws-lambda instrumentation exception occurred while preparing span attributes: #{e.message}") | ||
{} | ||
end | ||
|
||
# sqs spec for lambda: https://github.com/open-telemetry/semantic-conventions/blob/main/docs/faas/aws-lambda.md#sqs | ||
# current there is no spec for 'aws:sns', 'aws:s3' and 'aws:dynamodb' | ||
def trigger_type_attributes(event) | ||
attributes = {} | ||
case event['Records'].dig(0, 'eventSource') | ||
when 'aws:sqs' | ||
attributes[OpenTelemetry::SemanticConventions::Trace::FAAS_TRIGGER] = 'pubsub' | ||
attributes[OpenTelemetry::SemanticConventions::Trace::MESSAGING_OPERATION] = 'process' | ||
attributes[OpenTelemetry::SemanticConventions::Trace::MESSAGING_SYSTEM] = 'AmazonSQS' | ||
end | ||
attributes | ||
end | ||
end | ||
end | ||
end | ||
end |
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.
Probably need to throw some
try
s in here so we don't blow up if the metrics SDK isn't in use