Skip to content

Commit b2c9377

Browse files
committed
Clean up; add test for parsing AWS response
1 parent 83105eb commit b2c9377

File tree

3 files changed

+63
-23
lines changed

3 files changed

+63
-23
lines changed

aws/logs_monitoring/enhanced_metrics.py

Lines changed: 24 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,12 @@
1-
import re
2-
import os
31
import logging
2+
import os
3+
import re
44

55
from collections import defaultdict
66
from time import time
77

8-
98
import boto3
109
from botocore.exceptions import ClientError
11-
1210
from datadog_lambda.metric import lambda_metric
1311

1412

@@ -32,7 +30,8 @@
3230
log = logging.getLogger()
3331
log.setLevel(logging.INFO)
3432

35-
def set_log_level_to_env_var:
33+
34+
def set_log_level_to_env_var():
3635
"""Reads the log level env var and sets the log level according to its value
3736
3837
Defaults to INFO level
@@ -45,6 +44,7 @@ def set_log_level_to_env_var:
4544
if env_var_log_level == "warn" or env_var_log_level == "warning":
4645
log.setLevel(logging.WARN)
4746

47+
4848
set_log_level_to_env_var()
4949

5050

@@ -86,7 +86,15 @@ def get_dd_tag_string_from_aws_dict(aws_key_value_tag_dict):
8686
def parse_get_resources_response_for_tags_by_arn(get_resources_page):
8787
"""Parses a page of GetResources response for the mapping from ARN to tags
8888
89+
Args:
90+
get_resources_page (dict<str, multiple types>): one page of the GetResources response. Ex:
91+
[{
92+
'ResourceARN': 'arn:aws:lambda:us-east-1:123497598159:function:my-test-lambda',
93+
'Tags': [{'Key': 'stage', 'Value': 'dev'}, {'Key': 'team', 'Value': 'serverless'}]
94+
}]
8995
96+
Returns:
97+
tags_by_arn (dict<str, str[]>): Lambda tag lists keyed by ARN
9098
"""
9199
tags_by_arn = defaultdict(list)
92100

@@ -180,6 +188,7 @@ def get_lambda_tags(self, resource_arn):
180188

181189
return function_tags
182190

191+
183192
# Store the cache in the global scope so that it will be reused as long as
184193
# the log forwarder Lambda container is running
185194
account_lambda_tags_cache = LambdaTagsCache()
@@ -236,11 +245,15 @@ def parse_and_submit_enhanced_metrics(logs):
236245
"""
237246
# Wrap everything in try/catch to prevent failing the Lambda on enhanced metrics
238247
try:
239-
enhanced_metrics = generate_enhanced_lambda_metrics(logs, account_lambda_tags_cache)
248+
enhanced_metrics = generate_enhanced_lambda_metrics(
249+
logs, account_lambda_tags_cache
250+
)
240251
for enhanced_metric in enhanced_metrics:
241252
enhanced_metric.submit_to_dd()
242253
except Exception:
243-
log.exception("Encountered an error while trying to parse and submit enhanced metrics")
254+
log.exception(
255+
"Encountered an error while trying to parse and submit enhanced metrics"
256+
)
244257

245258

246259
def generate_enhanced_lambda_metrics(logs, tags_cache):
@@ -283,12 +296,7 @@ def generate_enhanced_lambda_metrics(logs, tags_cache):
283296

284297
# If the log dict is missing any of this data it's not a Lambda REPORT log and we move on
285298
if not all(
286-
(
287-
log_function_arn,
288-
log_message,
289-
timestamp,
290-
log_message.startswith("REPORT"),
291-
)
299+
(log_function_arn, log_message, timestamp, log_message.startswith("REPORT"))
292300
):
293301
continue
294302

@@ -313,6 +321,7 @@ def generate_enhanced_lambda_metrics(logs, tags_cache):
313321

314322
return enhanced_metrics
315323

324+
316325
# Names to use for metrics and for the named regex groups
317326
REQUEST_ID_FIELD_NAME = "request_id"
318327
DURATION_METRIC_NAME = "duration"
@@ -364,9 +373,9 @@ def parse_lambda_tags_from_arn(arn):
364373
_, _, _, region, account_id, _, function_name = split_arn
365374

366375
return [
367-
"functionname:{}".format(function_name),
368-
"account_id:{}".format(account_id),
369376
"region:{}".format(region),
377+
"account_id:{}".format(account_id),
378+
"functionname:{}".format(function_name),
370379
]
371380

372381

aws/logs_monitoring/lambda_function.py

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
import ssl
1717
import six.moves.urllib as urllib # for for Python 2.7 urllib.unquote_plus
1818
import itertools
19-
import uuid
19+
2020
from io import BytesIO, BufferedReader
2121

2222
from enhanced_metrics import parse_and_submit_enhanced_metrics
@@ -59,11 +59,6 @@
5959
DD_URL = os.getenv("DD_URL", default="lambda-http-intake.logs." + DD_SITE)
6060

6161

62-
lambda_container_uuid = uuid.uuid4()
63-
container_start_time = time.time()
64-
65-
66-
6762
class ScrubbingRuleConfig(object):
6863
def __init__(self, name, pattern, placeholder):
6964
self.name = name

aws/logs_monitoring/tests/test_enhanced_metrics.py

Lines changed: 38 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,10 @@
88
parse_lambda_tags_from_arn,
99
generate_enhanced_lambda_metrics,
1010
LambdaTagsCache,
11+
parse_get_resources_response_for_tags_by_arn,
1112
)
1213

1314

14-
# python -m unittest tests.test_enhanced_metrics from parent dir
1515
class TestEnhancedMetrics(unittest.TestCase):
1616

1717
maxDiff = None
@@ -47,6 +47,42 @@ def test_parse_lambda_tags_from_arn(self):
4747
],
4848
)
4949

50+
def test_generate_custom_tags_cache(self):
51+
self.assertEqual(
52+
parse_get_resources_response_for_tags_by_arn(
53+
{
54+
"ResourceTagMappingList": [
55+
{
56+
"ResourceARN": "arn:aws:lambda:us-east-1:123497598159:function:my-test-lambda-dev",
57+
"Tags": [
58+
{"Key": "stage", "Value": "dev"},
59+
{"Key": "team", "Value": "serverless"},
60+
],
61+
},
62+
{
63+
"ResourceARN": "arn:aws:lambda:us-east-1:123497598159:function:my-test-lambda-prod",
64+
"Tags": [
65+
{"Key": "stage", "Value": "prod"},
66+
{"Key": "team", "Value": "serverless"},
67+
{"Key": "datacenter", "Value": "eu"},
68+
],
69+
},
70+
]
71+
}
72+
),
73+
{
74+
"arn:aws:lambda:us-east-1:123497598159:function:my-test-lambda-dev": [
75+
"stage:dev",
76+
"team:serverless",
77+
],
78+
"arn:aws:lambda:us-east-1:123497598159:function:my-test-lambda-prod": [
79+
"stage:prod",
80+
"team:serverless",
81+
"datacenter:eu",
82+
],
83+
},
84+
)
85+
5086
def test_parse_metrics_from_report_log(self):
5187
parsed_metrics = parse_metrics_from_report_log(self.malformed_report)
5288
self.assertEqual(parsed_metrics, [])
@@ -115,7 +151,7 @@ def test_parse_metrics_from_report_log(self):
115151
],
116152
)
117153

118-
@patch("enhanced_metrics.build_arn_to_lambda_tags_cache")
154+
@patch("enhanced_metrics.build_tags_by_arn_cache")
119155
def test_generate_enhanced_lambda_metrics(self, mock_build_cache):
120156
mock_build_cache.return_value = {}
121157
tags_cache = LambdaTagsCache()

0 commit comments

Comments
 (0)