datadog_lambda 5.91.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,352 @@
1
+ # Unless explicitly stated otherwise all files in this repository are licensed
2
+ # under the Apache License Version 2.0.
3
+ # This product includes software developed at Datadog (https://www.datadoghq.com/).
4
+ # Copyright 2019 Datadog, Inc.
5
+
6
+ import base64
7
+ import gzip
8
+ import json
9
+ from io import BytesIO, BufferedReader
10
+ from enum import Enum
11
+ from typing import Any
12
+
13
+
14
+ class _stringTypedEnum(Enum):
15
+ """
16
+ _stringTypedEnum provides a type-hinted convenience function for getting the string value of
17
+ an enum.
18
+ """
19
+
20
+ def get_string(self) -> str:
21
+ return self.value
22
+
23
+
24
+ class EventTypes(_stringTypedEnum):
25
+ """
26
+ EventTypes is an enum of Lambda event types we care about.
27
+ """
28
+
29
+ UNKNOWN = "unknown"
30
+ API_GATEWAY = "api-gateway"
31
+ APPSYNC = "appsync"
32
+ ALB = "application-load-balancer"
33
+ CLOUDWATCH_LOGS = "cloudwatch-logs"
34
+ CLOUDWATCH_EVENTS = "cloudwatch-events"
35
+ CLOUDFRONT = "cloudfront"
36
+ DYNAMODB = "dynamodb"
37
+ EVENTBRIDGE = "eventbridge"
38
+ KINESIS = "kinesis"
39
+ LAMBDA_FUNCTION_URL = "lambda-function-url"
40
+ S3 = "s3"
41
+ SNS = "sns"
42
+ SQS = "sqs"
43
+ STEPFUNCTIONS = "states"
44
+
45
+
46
+ class EventSubtypes(_stringTypedEnum):
47
+ """
48
+ EventSubtypes is an enum of Lambda event subtypes.
49
+ Currently, API Gateway events subtypes are supported,
50
+ e.g. HTTP-API and Websocket events vs vanilla API-Gateway events.
51
+ """
52
+
53
+ NONE = "none"
54
+ API_GATEWAY = "api-gateway" # regular API Gateway
55
+ WEBSOCKET = "websocket"
56
+ HTTP_API = "http-api"
57
+
58
+
59
+ class _EventSource:
60
+ """
61
+ _EventSource holds an event's type and subtype.
62
+ """
63
+
64
+ def __init__(
65
+ self,
66
+ event_type: EventTypes,
67
+ subtype: EventSubtypes = EventSubtypes.NONE,
68
+ ):
69
+ self.event_type = event_type
70
+ self.subtype = subtype
71
+
72
+ def to_string(self) -> str:
73
+ """
74
+ to_string returns the string representation of an _EventSource.
75
+ Since to_string was added to support trigger tagging,
76
+ the event's subtype will never be included in the string.
77
+ """
78
+ return self.event_type.get_string()
79
+
80
+ def equals(
81
+ self, event_type: EventTypes, subtype: EventSubtypes = EventSubtypes.NONE
82
+ ) -> bool:
83
+ """
84
+ equals provides syntactic sugar to determine whether this _EventSource has a given type
85
+ and subtype.
86
+ Unknown events will never equal other events.
87
+ """
88
+ if self.event_type == EventTypes.UNKNOWN:
89
+ return False
90
+ if self.event_type != event_type:
91
+ return False
92
+ if self.subtype != subtype:
93
+ return False
94
+ return True
95
+
96
+
97
+ def get_aws_partition_by_region(region):
98
+ if region.startswith("us-gov-"):
99
+ return "aws-us-gov"
100
+ if region.startswith("cn-"):
101
+ return "aws-cn"
102
+ return "aws"
103
+
104
+
105
+ def get_first_record(event):
106
+ records = event.get("Records")
107
+ if records and len(records) > 0:
108
+ return records[0]
109
+
110
+
111
+ def parse_event_source(event: dict) -> _EventSource:
112
+ """Determines the source of the trigger event"""
113
+ if type(event) is not dict:
114
+ return _EventSource(EventTypes.UNKNOWN)
115
+
116
+ event_source = _EventSource(EventTypes.UNKNOWN)
117
+
118
+ request_context = event.get("requestContext")
119
+ if request_context and request_context.get("stage"):
120
+ if "domainName" in request_context and detect_lambda_function_url_domain(
121
+ request_context.get("domainName")
122
+ ):
123
+ return _EventSource(EventTypes.LAMBDA_FUNCTION_URL)
124
+ event_source = _EventSource(EventTypes.API_GATEWAY)
125
+ if "httpMethod" in event:
126
+ event_source.subtype = EventSubtypes.API_GATEWAY
127
+ if "routeKey" in event:
128
+ event_source.subtype = EventSubtypes.HTTP_API
129
+ if event.get("requestContext", {}).get("messageDirection"):
130
+ event_source.subtype = EventSubtypes.WEBSOCKET
131
+
132
+ if request_context and request_context.get("elb"):
133
+ event_source = _EventSource(EventTypes.ALB)
134
+
135
+ if event.get("awslogs"):
136
+ event_source = _EventSource(EventTypes.CLOUDWATCH_LOGS)
137
+
138
+ if event.get("detail-type"):
139
+ event_source = _EventSource(EventTypes.EVENTBRIDGE)
140
+
141
+ event_detail = event.get("detail")
142
+ has_event_categories = (
143
+ isinstance(event_detail, dict)
144
+ and event_detail.get("EventCategories") is not None
145
+ )
146
+ if event.get("source") == "aws.events" or has_event_categories:
147
+ event_source = _EventSource(EventTypes.CLOUDWATCH_EVENTS)
148
+
149
+ if "Execution" in event and "StateMachine" in event and "State" in event:
150
+ event_source = _EventSource(EventTypes.STEPFUNCTIONS)
151
+
152
+ event_record = get_first_record(event)
153
+ if event_record:
154
+ aws_event_source = event_record.get(
155
+ "eventSource", event_record.get("EventSource")
156
+ )
157
+
158
+ if aws_event_source == "aws:dynamodb":
159
+ event_source = _EventSource(EventTypes.DYNAMODB)
160
+ if aws_event_source == "aws:kinesis":
161
+ event_source = _EventSource(EventTypes.KINESIS)
162
+ if aws_event_source == "aws:s3":
163
+ event_source = _EventSource(EventTypes.S3)
164
+ if aws_event_source == "aws:sns":
165
+ event_source = _EventSource(EventTypes.SNS)
166
+ if aws_event_source == "aws:sqs":
167
+ event_source = _EventSource(EventTypes.SQS)
168
+
169
+ if event_record.get("cf"):
170
+ event_source = _EventSource(EventTypes.CLOUDFRONT)
171
+
172
+ return event_source
173
+
174
+
175
+ def detect_lambda_function_url_domain(domain: str) -> bool:
176
+ # e.g. "etsn5fibjr.lambda-url.eu-south-1.amazonaws.com"
177
+ domain_parts = domain.split(".")
178
+ if len(domain_parts) < 2:
179
+ return False
180
+ return domain_parts[1] == "lambda-url"
181
+
182
+
183
+ def parse_event_source_arn(source: _EventSource, event: dict, context: Any) -> str:
184
+ """
185
+ Parses the trigger event for an available ARN. If an ARN field is not provided
186
+ in the event we stitch it together.
187
+ """
188
+ split_function_arn = context.invoked_function_arn.split(":")
189
+ region = split_function_arn[3]
190
+ account_id = split_function_arn[4]
191
+ aws_arn = get_aws_partition_by_region(region)
192
+
193
+ event_record = get_first_record(event)
194
+ # e.g. arn:aws:s3:::lambda-xyz123-abc890
195
+ if source.to_string() == "s3":
196
+ return event_record.get("s3", {}).get("bucket", {}).get("arn")
197
+
198
+ # e.g. arn:aws:sns:us-east-1:123456789012:sns-lambda
199
+ if source.to_string() == "sns":
200
+ return event_record.get("Sns", {}).get("TopicArn")
201
+
202
+ # e.g. arn:aws:cloudfront::123456789012:distribution/ABC123XYZ
203
+ if source.event_type == EventTypes.CLOUDFRONT:
204
+ distribution_id = (
205
+ event_record.get("cf", {}).get("config", {}).get("distributionId")
206
+ )
207
+ return "arn:{}:cloudfront::{}:distribution/{}".format(
208
+ aws_arn, account_id, distribution_id
209
+ )
210
+
211
+ # e.g. arn:aws:lambda:<region>:<account_id>:url:<function-name>:<function-qualifier>
212
+ if source.equals(EventTypes.LAMBDA_FUNCTION_URL):
213
+ function_name = ""
214
+ if len(split_function_arn) >= 7:
215
+ function_name = split_function_arn[6]
216
+ function_arn = f"arn:aws:lambda:{region}:{account_id}:url:{function_name}"
217
+ function_qualifier = ""
218
+ if len(split_function_arn) >= 8:
219
+ function_qualifier = split_function_arn[7]
220
+ function_arn = function_arn + f":{function_qualifier}"
221
+ return function_arn
222
+
223
+ # e.g. arn:aws:apigateway:us-east-1::/restapis/xyz123/stages/default
224
+ if source.event_type == EventTypes.API_GATEWAY:
225
+ request_context = event.get("requestContext")
226
+ return "arn:{}:apigateway:{}::/restapis/{}/stages/{}".format(
227
+ aws_arn, region, request_context.get("apiId"), request_context.get("stage")
228
+ )
229
+
230
+ # e.g. arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/lambda-xyz/123
231
+ if source.event_type == EventTypes.ALB:
232
+ request_context = event.get("requestContext")
233
+ return request_context.get("elb", {}).get("targetGroupArn")
234
+
235
+ # e.g. arn:aws:logs:us-west-1:123456789012:log-group:/my-log-group-xyz
236
+ if source.event_type == EventTypes.CLOUDWATCH_LOGS:
237
+ with gzip.GzipFile(
238
+ fileobj=BytesIO(base64.b64decode(event.get("awslogs", {}).get("data")))
239
+ ) as decompress_stream:
240
+ data = b"".join(BufferedReader(decompress_stream))
241
+ logs = json.loads(data)
242
+ log_group = logs.get("logGroup", "cloudwatch")
243
+ return "arn:{}:logs:{}:{}:log-group:{}".format(
244
+ aws_arn, region, account_id, log_group
245
+ )
246
+
247
+ # e.g. arn:aws:events:us-east-1:123456789012:rule/my-schedule
248
+ if source.event_type == EventTypes.CLOUDWATCH_EVENTS and event.get("resources"):
249
+ return event.get("resources")[0]
250
+
251
+
252
+ def get_event_source_arn(source: _EventSource, event: dict, context: Any) -> str:
253
+ event_source_arn = event.get("eventSourceARN") or event.get("eventSourceArn")
254
+
255
+ event_record = get_first_record(event)
256
+ if event_record:
257
+ event_source_arn = event_record.get("eventSourceARN") or event_record.get(
258
+ "eventSourceArn"
259
+ )
260
+
261
+ if event_source_arn is None:
262
+ event_source_arn = parse_event_source_arn(source, event, context)
263
+
264
+ return event_source_arn
265
+
266
+
267
+ def extract_http_tags(event):
268
+ """
269
+ Extracts HTTP facet tags from the triggering event
270
+ """
271
+ http_tags = {}
272
+ request_context = event.get("requestContext")
273
+ path = event.get("path")
274
+ method = event.get("httpMethod")
275
+ if request_context and request_context.get("stage"):
276
+ if request_context.get("domainName"):
277
+ http_tags["http.url"] = request_context.get("domainName")
278
+
279
+ path = request_context.get("path")
280
+ method = request_context.get("httpMethod")
281
+ # Version 2.0 HTTP API Gateway
282
+ apigateway_v2_http = request_context.get("http")
283
+ if event.get("version") == "2.0" and apigateway_v2_http:
284
+ path = apigateway_v2_http.get("path")
285
+ method = apigateway_v2_http.get("method")
286
+
287
+ if path:
288
+ http_tags["http.url_details.path"] = path
289
+ if method:
290
+ http_tags["http.method"] = method
291
+
292
+ headers = event.get("headers")
293
+ if headers and headers.get("Referer"):
294
+ http_tags["http.referer"] = headers.get("Referer")
295
+
296
+ return http_tags
297
+
298
+
299
+ def extract_trigger_tags(event: dict, context: Any) -> dict:
300
+ """
301
+ Parses the trigger event object to get tags to be added to the span metadata
302
+ """
303
+ trigger_tags = {}
304
+ event_source = parse_event_source(event)
305
+ if event_source.to_string() is not None and event_source.to_string() != "unknown":
306
+ trigger_tags["function_trigger.event_source"] = event_source.to_string()
307
+
308
+ event_source_arn = get_event_source_arn(event_source, event, context)
309
+ if event_source_arn:
310
+ trigger_tags["function_trigger.event_source_arn"] = event_source_arn
311
+
312
+ if event_source.event_type in [
313
+ EventTypes.API_GATEWAY,
314
+ EventTypes.ALB,
315
+ EventTypes.LAMBDA_FUNCTION_URL,
316
+ ]:
317
+ trigger_tags.update(extract_http_tags(event))
318
+
319
+ return trigger_tags
320
+
321
+
322
+ def extract_http_status_code_tag(trigger_tags, response):
323
+ """
324
+ If the Lambda was triggered by API Gateway, Lambda Function URL, or ALB,
325
+ add the returned status code as a tag to the function execution span.
326
+ """
327
+ if trigger_tags is None:
328
+ return
329
+ str_event_source = trigger_tags.get("function_trigger.event_source")
330
+ # it would be cleaner if each event type was a constant object that
331
+ # knew some properties about itself like this.
332
+ str_http_triggers = [
333
+ et.value
334
+ for et in [
335
+ EventTypes.API_GATEWAY,
336
+ EventTypes.LAMBDA_FUNCTION_URL,
337
+ EventTypes.ALB,
338
+ ]
339
+ ]
340
+ if str_event_source not in str_http_triggers:
341
+ return
342
+
343
+ status_code = "200"
344
+ if response is None:
345
+ # Return a 502 status if no response is found
346
+ status_code = "502"
347
+ elif hasattr(response, "get"):
348
+ status_code = response.get("statusCode")
349
+ elif hasattr(response, "status_code"):
350
+ status_code = response.status_code
351
+
352
+ return str(status_code)