|
2 | 2 | # under the Apache License Version 2.0. |
3 | 3 | # This product includes software developed at Datadog (https://www.datadoghq.com/). |
4 | 4 | # Copyright 2019 Datadog, Inc. |
5 | | - |
| 5 | +import hashlib |
6 | 6 | import logging |
7 | 7 | import os |
8 | 8 | import json |
@@ -328,6 +328,39 @@ def extract_context_from_kinesis_event(event, lambda_context): |
328 | 328 | return extract_context_from_lambda_context(lambda_context) |
329 | 329 |
|
330 | 330 |
|
| 331 | +def _deterministic_md5_hash(s: str) -> str: |
| 332 | + """MD5 here is to generate trace_id, not for any encryption.""" |
| 333 | + hex_number = hashlib.md5(s.encode("ascii")).hexdigest() |
| 334 | + binary = bin(int(hex_number, 16)) |
| 335 | + binary_str = str(binary) |
| 336 | + binary_str_remove_0b = binary_str[2:].rjust(128, "0") |
| 337 | + most_significant_64_bits_without_leading_1 = "0" + binary_str_remove_0b[1:-64] |
| 338 | + result = str(int(most_significant_64_bits_without_leading_1, 2)) |
| 339 | + if result == "0" * 64: |
| 340 | + return "1" |
| 341 | + return result |
| 342 | + |
| 343 | + |
| 344 | +def extract_context_from_step_functions(event, lambda_context): |
| 345 | + """ |
| 346 | + Only extract datadog trace context when Step Functions Context Object is injected |
| 347 | + into lambda's event dict. |
| 348 | + """ |
| 349 | + try: |
| 350 | + execution_id = event.get("Execution").get("Id") |
| 351 | + state_name = event.get("State").get("Name") |
| 352 | + state_entered_time = event.get("State").get("EnteredTime") |
| 353 | + trace_id = _deterministic_md5_hash(execution_id) |
| 354 | + parent_id = _deterministic_md5_hash( |
| 355 | + execution_id + "#" + state_name + "#" + state_entered_time |
| 356 | + ) |
| 357 | + sampling_priority = SamplingPriority.AUTO_KEEP |
| 358 | + return trace_id, parent_id, sampling_priority |
| 359 | + except Exception as e: |
| 360 | + logger.debug("The Step Functions trace extractor returned with error %s", e) |
| 361 | + return extract_context_from_lambda_context(lambda_context) |
| 362 | + |
| 363 | + |
331 | 364 | def extract_context_custom_extractor(extractor, event, lambda_context): |
332 | 365 | """ |
333 | 366 | Extract Datadog trace context using a custom trace extractor function |
@@ -440,6 +473,12 @@ def extract_dd_trace_context( |
440 | 473 | parent_id, |
441 | 474 | sampling_priority, |
442 | 475 | ) = extract_context_from_kinesis_event(event, lambda_context) |
| 476 | + elif event_source.equals(EventTypes.STEPFUNCTIONS): |
| 477 | + ( |
| 478 | + trace_id, |
| 479 | + parent_id, |
| 480 | + sampling_priority, |
| 481 | + ) = extract_context_from_step_functions(event, lambda_context) |
443 | 482 | else: |
444 | 483 | trace_id, parent_id, sampling_priority = extract_context_from_lambda_context( |
445 | 484 | lambda_context |
|
0 commit comments