-
Notifications
You must be signed in to change notification settings - Fork 614
/
__init__.py
475 lines (407 loc) · 17.8 KB
/
__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
# Copyright 2020, OpenTelemetry Authors
#
# 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.
"""
The opentelemetry-instrumentation-aws-lambda package provides an Instrumentor
to traces calls within a Python AWS Lambda function.
Usage
-----
.. code:: python
# Copy this snippet into an AWS Lambda function
import boto3
from opentelemetry.instrumentation.botocore import BotocoreInstrumentor
from opentelemetry.instrumentation.aws_lambda import AwsLambdaInstrumentor
# Enable instrumentation
BotocoreInstrumentor().instrument()
AwsLambdaInstrumentor().instrument()
# Lambda function
def lambda_handler(event, context):
s3 = boto3.resource('s3')
for bucket in s3.buckets.all():
print(bucket.name)
return "200 OK"
API
---
The `instrument` method accepts the following keyword args:
tracer_provider (TracerProvider) - an optional tracer provider
meter_provider (MeterProvider) - an optional meter provider
event_context_extractor (Callable) - a function that returns an OTel Trace
Context given the Lambda Event the AWS Lambda was invoked with
this function signature is: def event_context_extractor(lambda_event: Any) -> Context
for example:
.. code:: python
from opentelemetry.instrumentation.aws_lambda import AwsLambdaInstrumentor
def custom_event_context_extractor(lambda_event):
# If the `TraceContextTextMapPropagator` is the global propagator, we
# can use it to parse out the context from the HTTP Headers.
return get_global_textmap().extract(lambda_event["foo"]["headers"])
AwsLambdaInstrumentor().instrument(
event_context_extractor=custom_event_context_extractor
)
---
"""
import logging
import os
import time
from importlib import import_module
from typing import Any, Callable, Collection
from urllib.parse import urlencode
from wrapt import wrap_function_wrapper
from opentelemetry import context as context_api
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.metrics import MeterProvider, get_meter_provider
from opentelemetry.propagate import get_global_textmap
from opentelemetry.semconv.resource import ResourceAttributes
from opentelemetry.semconv.trace import SpanAttributes
from opentelemetry.trace import (
Span,
SpanKind,
TracerProvider,
get_tracer,
get_tracer_provider,
)
from opentelemetry.trace.status import Status, StatusCode
logger = logging.getLogger(__name__)
_HANDLER = "_HANDLER"
_X_AMZN_TRACE_ID = "_X_AMZN_TRACE_ID"
ORIG_HANDLER = "ORIG_HANDLER"
OTEL_INSTRUMENTATION_AWS_LAMBDA_FLUSH_TIMEOUT = (
"OTEL_INSTRUMENTATION_AWS_LAMBDA_FLUSH_TIMEOUT"
)
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.
Protects headers from being something other than dictionary, as this
is what downstream propagators expect.
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 on it being a map with a 'headers' key
Returns:
A Context with configuration found in the event.
"""
headers = None
try:
headers = lambda_event["headers"]
except (TypeError, KeyError):
logger.debug(
"Extracting context from Lambda Event failed: either enable X-Ray active tracing or configure API Gateway to trigger this Lambda function as a pure proxy. Otherwise, generated spans will have an invalid (empty) parent context."
)
if not isinstance(headers, dict):
headers = {}
return get_global_textmap().extract(headers)
def _determine_parent_context(
lambda_event: Any,
event_context_extractor: Callable[[Any], Context],
) -> 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
event_context_extractor: a method which takes the Lambda
Event as input and extracts an OTel Context from it. By default,
the context is extracted from the HTTP headers of an API Gateway
request.
Returns:
A Context with configuration found in the carrier.
"""
if event_context_extractor is None:
return _default_event_context_extractor(lambda_event)
return event_context_extractor(lambda_event)
def _set_api_gateway_v1_proxy_attributes(
lambda_event: Any, span: Span
) -> Span:
"""Sets HTTP attributes for REST APIs and v1 HTTP APIs
More info:
https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-input-format
"""
span.set_attribute(
SpanAttributes.HTTP_METHOD, lambda_event.get("httpMethod")
)
if lambda_event.get("headers"):
if "User-Agent" in lambda_event["headers"]:
span.set_attribute(
SpanAttributes.HTTP_USER_AGENT,
lambda_event["headers"]["User-Agent"],
)
if "X-Forwarded-Proto" in lambda_event["headers"]:
span.set_attribute(
SpanAttributes.HTTP_SCHEME,
lambda_event["headers"]["X-Forwarded-Proto"],
)
if "Host" in lambda_event["headers"]:
span.set_attribute(
SpanAttributes.NET_HOST_NAME,
lambda_event["headers"]["Host"],
)
if "resource" in lambda_event:
span.set_attribute(SpanAttributes.HTTP_ROUTE, lambda_event["resource"])
if lambda_event.get("queryStringParameters"):
span.set_attribute(
SpanAttributes.HTTP_TARGET,
f"{lambda_event['resource']}?{urlencode(lambda_event['queryStringParameters'])}",
)
else:
span.set_attribute(
SpanAttributes.HTTP_TARGET, lambda_event["resource"]
)
return span
def _set_api_gateway_v2_proxy_attributes(
lambda_event: Any, span: Span
) -> Span:
"""Sets HTTP attributes for v2 HTTP APIs
More info:
https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-integrations-lambda.html
"""
if "domainName" in lambda_event["requestContext"]:
span.set_attribute(
SpanAttributes.NET_HOST_NAME,
lambda_event["requestContext"]["domainName"],
)
if lambda_event["requestContext"].get("http"):
if "method" in lambda_event["requestContext"]["http"]:
span.set_attribute(
SpanAttributes.HTTP_METHOD,
lambda_event["requestContext"]["http"]["method"],
)
if "userAgent" in lambda_event["requestContext"]["http"]:
span.set_attribute(
SpanAttributes.HTTP_USER_AGENT,
lambda_event["requestContext"]["http"]["userAgent"],
)
if "path" in lambda_event["requestContext"]["http"]:
span.set_attribute(
SpanAttributes.HTTP_ROUTE,
lambda_event["requestContext"]["http"]["path"],
)
if lambda_event.get("rawQueryString"):
span.set_attribute(
SpanAttributes.HTTP_TARGET,
f"{lambda_event['requestContext']['http']['path']}?{lambda_event['rawQueryString']}",
)
else:
span.set_attribute(
SpanAttributes.HTTP_TARGET,
lambda_event["requestContext"]["http"]["path"],
)
return span
# pylint: disable=too-many-statements
def _instrument(
wrapped_module_name,
wrapped_function_name,
flush_timeout,
event_context_extractor: Callable[[Any], Context],
tracer_provider: TracerProvider = None,
meter_provider: MeterProvider = None,
):
# pylint: disable=too-many-locals
# pylint: disable=too-many-statements
def _instrumented_lambda_handler_call( # noqa pylint: disable=too-many-branches
call_wrapped, instance, args, kwargs
):
orig_handler_name = ".".join(
[wrapped_module_name, wrapped_function_name]
)
lambda_event = args[0]
parent_context = _determine_parent_context(
lambda_event,
event_context_extractor,
)
try:
event_source = lambda_event["Records"][0].get(
"eventSource"
) or lambda_event["Records"][0].get("EventSource")
if event_source in {
"aws:sqs",
"aws:s3",
"aws:sns",
"aws:dynamodb",
}:
# See more:
# https://docs.aws.amazon.com/lambda/latest/dg/with-sqs.html
# https://docs.aws.amazon.com/lambda/latest/dg/with-sns.html
# https://docs.aws.amazon.com/AmazonS3/latest/userguide/notification-content-structure.html
# https://docs.aws.amazon.com/lambda/latest/dg/with-ddb.html
span_kind = SpanKind.CONSUMER
else:
span_kind = SpanKind.SERVER
except (IndexError, KeyError, TypeError):
span_kind = SpanKind.SERVER
tracer = get_tracer(
__name__,
__version__,
tracer_provider,
schema_url="https://opentelemetry.io/schemas/1.11.0",
)
token = context_api.attach(parent_context)
try:
with tracer.start_as_current_span(
name=orig_handler_name,
kind=span_kind,
) as span:
if span.is_recording():
lambda_context = args[1]
# NOTE: The specs mention an exception here, allowing the
# `SpanAttributes.CLOUD_RESOURCE_ID` attribute to be set as a span
# attribute instead of a resource attribute.
#
# See more:
# https://github.com/open-telemetry/semantic-conventions/blob/main/docs/faas/aws-lambda.md#resource-detector
span.set_attribute(
SpanAttributes.CLOUD_RESOURCE_ID,
lambda_context.invoked_function_arn,
)
span.set_attribute(
SpanAttributes.FAAS_INVOCATION_ID,
lambda_context.aws_request_id,
)
# NOTE: `cloud.account.id` can be parsed from the ARN as the fifth item when splitting on `:`
#
# See more:
# https://github.com/open-telemetry/semantic-conventions/blob/main/docs/faas/aws-lambda.md#all-triggers
account_id = lambda_context.invoked_function_arn.split(
":"
)[4]
span.set_attribute(
ResourceAttributes.CLOUD_ACCOUNT_ID,
account_id,
)
exception = None
result = None
try:
result = call_wrapped(*args, **kwargs)
except Exception as exc: # pylint: disable=W0703
exception = exc
span.set_status(Status(StatusCode.ERROR))
span.record_exception(exception)
# If the request came from an API Gateway, extract http attributes from the event
# https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/instrumentation/aws-lambda.md#api-gateway
# https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/http.md#http-server-semantic-conventions
if isinstance(lambda_event, dict) and lambda_event.get(
"requestContext"
):
span.set_attribute(SpanAttributes.FAAS_TRIGGER, "http")
if lambda_event.get("version") == "2.0":
_set_api_gateway_v2_proxy_attributes(
lambda_event, span
)
else:
_set_api_gateway_v1_proxy_attributes(
lambda_event, span
)
if isinstance(result, dict) and result.get("statusCode"):
span.set_attribute(
SpanAttributes.HTTP_STATUS_CODE,
result.get("statusCode"),
)
finally:
context_api.detach(token)
now = time.time()
_tracer_provider = tracer_provider or get_tracer_provider()
if hasattr(_tracer_provider, "force_flush"):
try:
# NOTE: `force_flush` before function quit in case of Lambda freeze.
_tracer_provider.force_flush(flush_timeout)
except Exception: # pylint: disable=broad-except
logger.exception("TracerProvider failed to flush traces")
else:
logger.warning(
"TracerProvider was missing `force_flush` method. This is necessary in case of a Lambda freeze and would exist in the OTel SDK implementation."
)
_meter_provider = meter_provider or get_meter_provider()
if hasattr(_meter_provider, "force_flush"):
rem = flush_timeout - (time.time() - now) * 1000
if rem > 0:
try:
# NOTE: `force_flush` before function quit in case of Lambda freeze.
_meter_provider.force_flush(rem)
except Exception: # pylint: disable=broad-except
logger.exception("MeterProvider failed to flush metrics")
else:
logger.warning(
"MeterProvider was missing `force_flush` method. This is necessary in case of a Lambda freeze and would exist in the OTel SDK implementation."
)
if exception is not None:
raise exception.with_traceback(exception.__traceback__)
return result
wrap_function_wrapper(
wrapped_module_name,
wrapped_function_name,
_instrumented_lambda_handler_call,
)
class AwsLambdaInstrumentor(BaseInstrumentor):
def instrumentation_dependencies(self) -> Collection[str]:
return _instruments
def _instrument(self, **kwargs):
"""Instruments Lambda Handlers on AWS Lambda.
See more:
https://github.com/open-telemetry/semantic-conventions/blob/main/docs/faas/aws-lambda.md
Args:
**kwargs: Optional arguments
``tracer_provider``: a TracerProvider, defaults to global
``meter_provider``: a MeterProvider, defaults to global
``event_context_extractor``: a method which takes the Lambda
Event as input and extracts an OTel Context from it. By default,
the context is extracted from the HTTP headers of an API Gateway
request.
"""
lambda_handler = os.environ.get(ORIG_HANDLER, os.environ.get(_HANDLER))
if not lambda_handler:
logger.warning(
(
"Could not find the ORIG_HANDLER or _HANDLER in the environment variables. ",
"This instrumentation requires the OpenTelemetry Lambda extension installed.",
)
)
return
# pylint: disable=attribute-defined-outside-init
(
self._wrapped_module_name,
self._wrapped_function_name,
) = lambda_handler.rsplit(".", 1)
flush_timeout_env = os.environ.get(
OTEL_INSTRUMENTATION_AWS_LAMBDA_FLUSH_TIMEOUT, None
)
flush_timeout = 30000
try:
if flush_timeout_env is not None:
flush_timeout = int(flush_timeout_env)
except ValueError:
logger.warning(
"Could not convert OTEL_INSTRUMENTATION_AWS_LAMBDA_FLUSH_TIMEOUT value %s to int",
flush_timeout_env,
)
_instrument(
self._wrapped_module_name,
self._wrapped_function_name,
flush_timeout,
event_context_extractor=kwargs.get(
"event_context_extractor", _default_event_context_extractor
),
tracer_provider=kwargs.get("tracer_provider"),
meter_provider=kwargs.get("meter_provider"),
)
def _uninstrument(self, **kwargs):
unwrap(
import_module(self._wrapped_module_name),
self._wrapped_function_name,
)