-
Notifications
You must be signed in to change notification settings - Fork 45
/
Copy pathtest_tracing.py
2111 lines (1930 loc) · 77.9 KB
/
test_tracing.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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import copy
import functools
import json
import traceback
import pytest
import os
import unittest
from unittest.mock import Mock, patch, call
import ddtrace
from ddtrace import tracer
from ddtrace.context import Context
from datadog_lambda.constants import (
SamplingPriority,
TraceHeader,
TraceContextSource,
XraySubsegment,
)
from datadog_lambda.tracing import (
HIGHER_64_BITS,
LOWER_64_BITS,
_deterministic_sha256_hash,
create_inferred_span,
extract_dd_trace_context,
create_dd_dummy_metadata_subsegment,
create_function_execution_span,
get_dd_trace_context,
mark_trace_as_error_for_5xx_responses,
set_correlation_ids,
set_dd_trace_py_root,
_convert_xray_trace_id,
_convert_xray_entity_id,
_convert_xray_sampling,
InferredSpanInfo,
create_service_mapping,
determine_service_name,
service_mapping as global_service_mapping,
propagator,
emit_telemetry_on_exception_outside_of_handler,
is_legacy_lambda_step_function,
)
from datadog_lambda.trigger import EventTypes
from tests.utils import get_mock_context
function_arn = "arn:aws:lambda:us-west-1:123457598159:function:python-layer-test"
fake_xray_header_value = (
"Root=1-5e272390-8c398be037738dc042009320;Parent=94ae789b969f1cc5;Sampled=1"
)
fake_xray_header_value_parent_decimal = "10713633173203262661"
fake_xray_header_value_root_decimal = "3995693151288333088"
event_samples = "tests/event_samples/"
def with_trace_propagation_style(style):
style_list = list(style.split(","))
def _wrapper(fn):
@functools.wraps(fn)
def _wrap(*args, **kwargs):
from ddtrace.propagation.http import config
orig_extract = config._propagation_style_extract
orig_inject = config._propagation_style_inject
config._propagation_style_extract = style_list
config._propagation_style_inject = style_list
try:
return fn(*args, **kwargs)
finally:
config._propagation_style_extract = orig_extract
config._propagation_style_inject = orig_inject
return _wrap
return _wrapper
_test_extract_dd_trace_context = (
("api-gateway", Context(trace_id=12345, span_id=67890, sampling_priority=2)),
(
"api-gateway-no-apiid",
Context(trace_id=12345, span_id=67890, sampling_priority=2),
),
(
"api-gateway-non-proxy",
Context(trace_id=12345, span_id=67890, sampling_priority=2),
),
(
"api-gateway-non-proxy-async",
Context(trace_id=12345, span_id=67890, sampling_priority=2),
),
(
"api-gateway-websocket-connect",
Context(trace_id=12345, span_id=67890, sampling_priority=2),
),
(
"api-gateway-websocket-default",
Context(trace_id=12345, span_id=67890, sampling_priority=2),
),
(
"api-gateway-websocket-disconnect",
Context(trace_id=12345, span_id=67890, sampling_priority=2),
),
(
"authorizer-request-api-gateway-v1",
Context(
trace_id=13478705995797221209,
span_id=8471288263384216896,
sampling_priority=1,
),
),
("authorizer-request-api-gateway-v1-cached", None),
(
"authorizer-request-api-gateway-v2",
Context(
trace_id=14356983619852933354,
span_id=12658621083505413809,
sampling_priority=1,
),
),
("authorizer-request-api-gateway-v2-cached", None),
(
"authorizer-request-api-gateway-websocket-connect",
Context(
trace_id=5351047404834723189,
span_id=18230460631156161837,
sampling_priority=1,
),
),
("authorizer-request-api-gateway-websocket-message", None),
(
"authorizer-token-api-gateway-v1",
Context(
trace_id=17874798268144902712,
span_id=16184667399315372101,
sampling_priority=1,
),
),
("authorizer-token-api-gateway-v1-cached", None),
("cloudfront", None),
("cloudwatch-events", None),
("cloudwatch-logs", None),
("custom", None),
("dynamodb", None),
("eventbridge-custom", Context(trace_id=12345, span_id=67890, sampling_priority=2)),
(
"eventbridge-sqs",
Context(
trace_id=7379586022458917877,
span_id=2644033662113726488,
sampling_priority=1,
),
),
("http-api", Context(trace_id=12345, span_id=67890, sampling_priority=2)),
(
"kinesis",
Context(
trace_id=4948377316357291421,
span_id=2876253380018681026,
sampling_priority=1,
),
),
(
"kinesis-batch",
Context(
trace_id=4948377316357291421,
span_id=2876253380018681026,
sampling_priority=1,
),
),
("lambda-url", None),
("s3", None),
(
"sns-b64-msg-attribute",
Context(
trace_id=4948377316357291421,
span_id=6746998015037429512,
sampling_priority=1,
),
),
(
"sns-batch",
Context(
trace_id=4948377316357291421,
span_id=6746998015037429512,
sampling_priority=1,
),
),
(
"sns-string-msg-attribute",
Context(
trace_id=4948377316357291421,
span_id=6746998015037429512,
sampling_priority=1,
),
),
(
"sqs-batch",
Context(
trace_id=2684756524522091840,
span_id=7431398482019833808,
sampling_priority=1,
),
),
(
"sqs-java-upstream",
Context(
trace_id=7925498337868555493,
span_id=5245570649555658903,
sampling_priority=1,
),
),
(
"sns-sqs-java-upstream",
Context(
trace_id=4781801699472307582,
span_id=7752697518321801287,
sampling_priority=1,
),
),
(
"sqs-string-msg-attribute",
Context(
trace_id=2684756524522091840,
span_id=7431398482019833808,
sampling_priority=1,
),
),
({"headers": None}, None),
)
@pytest.mark.parametrize("event,expect", _test_extract_dd_trace_context)
def test_extract_dd_trace_context(event, expect):
if isinstance(event, str):
with open(f"{event_samples}{event}.json") as f:
event = json.load(f)
ctx = get_mock_context()
actual, _, _ = extract_dd_trace_context(event, ctx)
assert (expect is None) is (actual is None)
assert (expect is None) or actual.trace_id == expect.trace_id
assert (expect is None) or actual.span_id == expect.span_id
assert (expect is None) or actual.sampling_priority == expect.sampling_priority
class TestExtractAndGetDDTraceContext(unittest.TestCase):
def setUp(self):
global dd_tracing_enabled
dd_tracing_enabled = False
os.environ["_X_AMZN_TRACE_ID"] = fake_xray_header_value
patcher = patch("datadog_lambda.tracing.send_segment")
self.mock_send_segment = patcher.start()
self.addCleanup(patcher.stop)
patcher = patch("datadog_lambda.tracing.is_lambda_context")
self.mock_is_lambda_context = patcher.start()
self.mock_is_lambda_context.return_value = True
self.addCleanup(patcher.stop)
def tearDown(self):
global dd_tracing_enabled
dd_tracing_enabled = False
del os.environ["_X_AMZN_TRACE_ID"]
@with_trace_propagation_style("datadog")
def test_without_datadog_trace_headers(self):
lambda_ctx = get_mock_context()
ctx, source, event_source = extract_dd_trace_context({}, lambda_ctx)
self.assertEqual(source, "xray")
self.assertEqual(
ctx,
Context(
trace_id=int(fake_xray_header_value_root_decimal),
span_id=int(fake_xray_header_value_parent_decimal),
sampling_priority=2,
),
)
self.assertDictEqual(
get_dd_trace_context(),
{
TraceHeader.TRACE_ID: fake_xray_header_value_root_decimal,
TraceHeader.PARENT_ID: fake_xray_header_value_parent_decimal,
TraceHeader.SAMPLING_PRIORITY: "2",
},
{},
)
@with_trace_propagation_style("datadog")
def test_with_non_object_event(self):
lambda_ctx = get_mock_context()
ctx, source, event_source = extract_dd_trace_context(b"", lambda_ctx)
self.assertEqual(source, "xray")
self.assertEqual(
ctx,
Context(
trace_id=int(fake_xray_header_value_root_decimal),
span_id=int(fake_xray_header_value_parent_decimal),
sampling_priority=2,
),
)
self.assertDictEqual(
get_dd_trace_context(),
{
TraceHeader.TRACE_ID: fake_xray_header_value_root_decimal,
TraceHeader.PARENT_ID: fake_xray_header_value_parent_decimal,
TraceHeader.SAMPLING_PRIORITY: "2",
},
{},
)
@with_trace_propagation_style("datadog")
def test_with_incomplete_datadog_trace_headers(self):
lambda_ctx = get_mock_context()
ctx, source, event_source = extract_dd_trace_context(
{"headers": {TraceHeader.TRACE_ID: "123"}},
lambda_ctx,
)
self.assertEqual(source, "xray")
self.assertEqual(
ctx,
Context(
trace_id=int(fake_xray_header_value_root_decimal),
span_id=int(fake_xray_header_value_parent_decimal),
sampling_priority=2,
),
)
self.assertDictEqual(
get_dd_trace_context(),
{
TraceHeader.TRACE_ID: fake_xray_header_value_root_decimal,
TraceHeader.PARENT_ID: fake_xray_header_value_parent_decimal,
TraceHeader.SAMPLING_PRIORITY: "2",
},
)
def common_tests_with_trace_context_extraction_injection(
self, headers, event_containing_headers, lambda_context=get_mock_context()
):
ctx, source, event_source = extract_dd_trace_context(
event_containing_headers,
lambda_context,
)
self.assertEqual(source, "event")
expected_context = propagator.extract(headers)
self.assertEqual(ctx, expected_context)
create_dd_dummy_metadata_subsegment(ctx, XraySubsegment.TRACE_KEY)
self.mock_send_segment.assert_called()
self.mock_send_segment.assert_called_with(
XraySubsegment.TRACE_KEY,
expected_context,
)
# when no active ddtrace context, xray context would be used
expected_context.span_id = int(fake_xray_header_value_parent_decimal)
expected_headers = {}
propagator.inject(expected_context, expected_headers)
dd_context_headers = get_dd_trace_context()
self.assertDictEqual(expected_headers, dd_context_headers)
@with_trace_propagation_style("datadog")
def test_with_complete_datadog_trace_headers(self):
headers = {
TraceHeader.TRACE_ID: "123",
TraceHeader.PARENT_ID: "321",
TraceHeader.SAMPLING_PRIORITY: "1",
}
self.common_tests_with_trace_context_extraction_injection(
headers, {"headers": headers}
)
@with_trace_propagation_style("tracecontext")
def test_with_w3c_trace_headers(self):
headers = {
"traceparent": "00-0000000000000000000000000000007b-0000000000000141-01",
"tracestate": "dd=s:2;t.dm:-0,rojo=00f067aa0ba902b7,congo=t61rcWkgMzE",
}
self.common_tests_with_trace_context_extraction_injection(
headers, {"headers": headers}
)
@with_trace_propagation_style("datadog")
def test_with_extractor_function(self):
def extractor_foo(event, context):
foo = event.get("foo", {})
lowercase_foo = {k.lower(): v for k, v in foo.items()}
trace_id = lowercase_foo.get(TraceHeader.TRACE_ID)
parent_id = lowercase_foo.get(TraceHeader.PARENT_ID)
sampling_priority = lowercase_foo.get(TraceHeader.SAMPLING_PRIORITY)
return trace_id, parent_id, sampling_priority
lambda_ctx = get_mock_context()
ctx, ctx_source, event_source = extract_dd_trace_context(
{
"foo": {
TraceHeader.TRACE_ID: "123",
TraceHeader.PARENT_ID: "321",
TraceHeader.SAMPLING_PRIORITY: "1",
}
},
lambda_ctx,
extractor=extractor_foo,
)
self.assertEqual(ctx_source, "event")
self.assertEqual(
ctx,
Context(
trace_id=123,
span_id=321,
sampling_priority=1,
),
)
self.assertDictEqual(
get_dd_trace_context(),
{
TraceHeader.TRACE_ID: "123",
TraceHeader.PARENT_ID: fake_xray_header_value_parent_decimal,
TraceHeader.SAMPLING_PRIORITY: "1",
},
)
@with_trace_propagation_style("datadog")
def test_graceful_fail_of_extractor_function(self):
def extractor_raiser(event, context):
raise Exception("kreator")
lambda_ctx = get_mock_context()
ctx, ctx_source, event_source = extract_dd_trace_context(
{
"foo": {
TraceHeader.TRACE_ID: "123",
TraceHeader.PARENT_ID: "321",
TraceHeader.SAMPLING_PRIORITY: "1",
}
},
lambda_ctx,
extractor=extractor_raiser,
)
self.assertEqual(ctx_source, "xray")
self.assertEqual(
ctx,
Context(
trace_id=int(fake_xray_header_value_root_decimal),
span_id=int(fake_xray_header_value_parent_decimal),
sampling_priority=2,
),
)
self.assertDictEqual(
get_dd_trace_context(),
{
TraceHeader.TRACE_ID: fake_xray_header_value_root_decimal,
TraceHeader.PARENT_ID: fake_xray_header_value_parent_decimal,
TraceHeader.SAMPLING_PRIORITY: "2",
},
)
@with_trace_propagation_style("datadog")
def test_with_sqs_distributed_datadog_trace_data(self):
headers = {
TraceHeader.TRACE_ID: "123",
TraceHeader.PARENT_ID: "321",
TraceHeader.SAMPLING_PRIORITY: "1",
}
sqs_event = {
"Records": [
{
"messageId": "059f36b4-87a3-44ab-83d2-661975830a7d",
"receiptHandle": "AQEBwJnKyrHigUMZj6rYigCgxlaS3SLy0a...",
"body": "Test message.",
"attributes": {
"ApproximateReceiveCount": "1",
"SentTimestamp": "1545082649183",
"SenderId": "AIDAIENQZJOLO23YVJ4VO",
"ApproximateFirstReceiveTimestamp": "1545082649185",
},
"messageAttributes": {
"_datadog": {
"stringValue": json.dumps(headers),
"dataType": "String",
}
},
"md5OfBody": "e4e68fb7bd0e697a0ae8f1bb342846b3",
"eventSource": "aws:sqs",
"eventSourceARN": "arn:aws:sqs:us-east-2:123456789012:my-queue",
"awsRegion": "us-east-2",
}
]
}
self.common_tests_with_trace_context_extraction_injection(headers, sqs_event)
@with_trace_propagation_style("tracecontext")
def test_with_sqs_distributed_w3c_trace_data(self):
headers = {
"traceparent": "00-0000000000000000000000000000007b-0000000000000141-01",
"tracestate": "dd=s:2;t.dm:-0,rojo=00f067aa0ba902b7,congo=t61rcWkgMzE",
}
sqs_event = {
"Records": [
{
"messageId": "059f36b4-87a3-44ab-83d2-661975830a7d",
"receiptHandle": "AQEBwJnKyrHigUMZj6rYigCgxlaS3SLy0a...",
"body": "Test message.",
"attributes": {
"ApproximateReceiveCount": "1",
"SentTimestamp": "1545082649183",
"SenderId": "AIDAIENQZJOLO23YVJ4VO",
"ApproximateFirstReceiveTimestamp": "1545082649185",
},
"messageAttributes": {
"_datadog": {
"stringValue": json.dumps(headers),
"dataType": "String",
}
},
"md5OfBody": "e4e68fb7bd0e697a0ae8f1bb342846b3",
"eventSource": "aws:sqs",
"eventSourceARN": "arn:aws:sqs:us-east-2:123456789012:my-queue",
"awsRegion": "us-east-2",
}
]
}
self.common_tests_with_trace_context_extraction_injection(headers, sqs_event)
@with_trace_propagation_style("datadog")
def test_with_legacy_client_context_datadog_trace_data(self):
headers = {
TraceHeader.TRACE_ID: "666",
TraceHeader.PARENT_ID: "777",
TraceHeader.SAMPLING_PRIORITY: "1",
}
lambda_ctx = get_mock_context(custom={"_datadog": headers})
self.common_tests_with_trace_context_extraction_injection(
headers, {}, lambda_ctx
)
@with_trace_propagation_style("tracecontext")
def test_with_legacy_client_context_w3c_trace_data(self):
headers = {
"traceparent": "00-0000000000000000000000000000029a-0000000000000309-01",
"tracestate": "dd=s:1;t.dm:-0,rojo=00f067aa0ba902b7,congo=t61rcWkgMzE",
}
lambda_ctx = get_mock_context(custom={"_datadog": headers})
self.common_tests_with_trace_context_extraction_injection(
headers, {}, lambda_ctx
)
@with_trace_propagation_style("datadog")
def test_with_new_client_context_datadog_trace_data(self):
headers = {
TraceHeader.TRACE_ID: "666",
TraceHeader.PARENT_ID: "777",
TraceHeader.SAMPLING_PRIORITY: "1",
}
lambda_ctx = get_mock_context(custom=headers)
self.common_tests_with_trace_context_extraction_injection(
headers, {}, lambda_ctx
)
@with_trace_propagation_style("tracecontext")
def test_with_new_client_context_w3c_trace_data(self):
headers = {
"traceparent": "00-0000000000000000000000000000029a-0000000000000309-01",
"tracestate": "dd=s:1;t.dm:-0,rojo=00f067aa0ba902b7,congo=t61rcWkgMzE",
}
lambda_ctx = get_mock_context(custom=headers)
self.common_tests_with_trace_context_extraction_injection(
headers, {}, lambda_ctx
)
@with_trace_propagation_style("datadog")
def test_with_complete_datadog_trace_headers_with_mixed_casing(self):
lambda_ctx = get_mock_context()
headers = {
"X-Datadog-Trace-Id": "123",
"X-Datadog-Parent-Id": "321",
"X-Datadog-Sampling-Priority": "1",
}
extract_dd_trace_context(
{"headers": headers},
lambda_ctx,
)
extract_headers = {}
context = propagator.extract(headers)
context.span_id = fake_xray_header_value_parent_decimal
propagator.inject(context, extract_headers)
self.assertDictEqual(extract_headers, get_dd_trace_context())
def test_with_complete_datadog_trace_headers_with_trigger_tags(self):
trigger_tags = {
"function_trigger.event_source": "sqs",
"function_trigger.event_source_arn": "arn:aws:sqs:us-east-1:123456789012:MyQueue",
}
create_dd_dummy_metadata_subsegment(
trigger_tags, XraySubsegment.LAMBDA_FUNCTION_TAGS_KEY
)
self.mock_send_segment.assert_called()
self.mock_send_segment.assert_has_calls(
[
call(
XraySubsegment.LAMBDA_FUNCTION_TAGS_KEY,
{
"function_trigger.event_source": "sqs",
"function_trigger.event_source_arn": "arn:aws:sqs:us-east-1:123456789012:MyQueue",
},
),
]
)
@with_trace_propagation_style("datadog")
def test_step_function_trace_data(self):
lambda_ctx = get_mock_context()
sqs_event = {
"Execution": {
"Id": "665c417c-1237-4742-aaca-8b3becbb9e75",
},
"StateMachine": {},
"State": {
"Name": "my-awesome-state",
"EnteredTime": "Mon Nov 13 12:43:33 PST 2023",
},
}
ctx, source, event_source = extract_dd_trace_context(sqs_event, lambda_ctx)
self.assertEqual(source, "event")
expected_context = Context(
trace_id=3675572987363469717,
span_id=6880978411788117524,
sampling_priority=1,
meta={"_dd.p.tid": "e987c84b36b11ab"},
)
self.assertEqual(ctx, expected_context)
self.assertEqual(
get_dd_trace_context(),
{
TraceHeader.TRACE_ID: "3675572987363469717",
TraceHeader.PARENT_ID: "10713633173203262661",
TraceHeader.SAMPLING_PRIORITY: "1",
"x-datadog-tags": "_dd.p.tid=e987c84b36b11ab",
},
)
create_dd_dummy_metadata_subsegment(ctx, XraySubsegment.TRACE_KEY)
self.mock_send_segment.assert_called_with(
XraySubsegment.TRACE_KEY,
expected_context,
)
def test_is_legacy_lambda_step_function(self):
sf_event = {
"Payload": {
"Execution": {
"Id": "665c417c-1237-4742-aaca-8b3becbb9e75",
},
"StateMachine": {},
"State": {
"Name": "my-awesome-state",
"EnteredTime": "Mon Nov 13 12:43:33 PST 2023",
},
}
}
self.assertTrue(is_legacy_lambda_step_function(sf_event))
sf_event = {
"Execution": {
"Id": "665c417c-1237-4742-aaca-8b3becbb9e75",
},
"StateMachine": {},
"State": {
"Name": "my-awesome-state",
"EnteredTime": "Mon Nov 13 12:43:33 PST 2023",
},
}
self.assertFalse(is_legacy_lambda_step_function(sf_event))
class TestXRayContextConversion(unittest.TestCase):
def test_convert_xray_trace_id(self):
self.assertEqual(
_convert_xray_trace_id("00000000e1be46a994272793"), 7043144561403045779
)
self.assertEqual(
_convert_xray_trace_id("bd862e3fe1be46a994272793"), 7043144561403045779
)
self.assertEqual(
_convert_xray_trace_id("ffffffffffffffffffffffff"),
9223372036854775807, # 0x7FFFFFFFFFFFFFFF
)
def test_convert_xray_entity_id(self):
self.assertEqual(
_convert_xray_entity_id("53995c3f42cd8ad8"), 6023947403358210776
)
self.assertEqual(
_convert_xray_entity_id("1000000000000000"), 1152921504606846976
)
self.assertEqual(
_convert_xray_entity_id("ffffffffffffffff"), 18446744073709551615
)
def test_convert_xray_sampling(self):
self.assertEqual(_convert_xray_sampling(True), SamplingPriority.USER_KEEP)
self.assertEqual(_convert_xray_sampling(False), SamplingPriority.USER_REJECT)
class TestLogsInjection(unittest.TestCase):
def setUp(self):
patcher = patch("datadog_lambda.tracing.get_dd_trace_context_obj")
self.mock_get_dd_trace_context = patcher.start()
self.mock_get_dd_trace_context.return_value = Context(
trace_id=int(fake_xray_header_value_root_decimal),
span_id=int(fake_xray_header_value_parent_decimal),
sampling_priority=1,
)
self.addCleanup(patcher.stop)
patcher = patch("datadog_lambda.tracing.is_lambda_context")
self.mock_is_lambda_context = patcher.start()
self.mock_is_lambda_context.return_value = True
self.addCleanup(patcher.stop)
def test_set_correlation_ids(self):
set_correlation_ids()
span = tracer.current_span()
self.assertEqual(span.trace_id, int(fake_xray_header_value_root_decimal))
self.assertEqual(span.parent_id, int(fake_xray_header_value_parent_decimal))
span.finish()
def test_set_correlation_ids_handle_empty_trace_context(self):
# neither x-ray or ddtrace is used. no tracing context at all.
self.mock_get_dd_trace_context.return_value = Context()
# no exception thrown
set_correlation_ids()
span = tracer.current_span()
self.assertIsNone(span)
class TestFunctionSpanTags(unittest.TestCase):
def test_function(self):
ctx = get_mock_context()
span = create_function_execution_span(
ctx, "", False, False, {"source": ""}, False, {}
)
self.assertEqual(span.get_tag("function_arn"), function_arn)
self.assertEqual(span.get_tag("function_version"), "$LATEST")
self.assertEqual(span.get_tag("resource_names"), "Function")
self.assertEqual(span.get_tag("functionname"), "function")
def test_function_with_version(self):
function_version = "1"
ctx = get_mock_context(
invoked_function_arn=function_arn + ":" + function_version
)
span = create_function_execution_span(
ctx, "", False, False, {"source": ""}, False, {}
)
self.assertEqual(span.get_tag("function_arn"), function_arn)
self.assertEqual(span.get_tag("function_version"), function_version)
self.assertEqual(span.get_tag("resource_names"), "Function")
self.assertEqual(span.get_tag("functionname"), "function")
def test_function_with_alias(self):
function_alias = "alias"
ctx = get_mock_context(invoked_function_arn=function_arn + ":" + function_alias)
span = create_function_execution_span(
ctx, "", False, False, {"source": ""}, False, {}
)
self.assertEqual(span.get_tag("function_arn"), function_arn)
self.assertEqual(span.get_tag("function_version"), function_alias)
self.assertEqual(span.get_tag("resource_names"), "Function")
self.assertEqual(span.get_tag("functionname"), "function")
def test_function_with_trigger_tags(self):
ctx = get_mock_context()
span = create_function_execution_span(
ctx,
"",
False,
False,
{"source": ""},
False,
{"function_trigger.event_source": "cloudwatch-logs"},
)
self.assertEqual(span.get_tag("function_arn"), function_arn)
self.assertEqual(span.get_tag("resource_names"), "Function")
self.assertEqual(span.get_tag("functionname"), "function")
self.assertEqual(
span.get_tag("function_trigger.event_source"), "cloudwatch-logs"
)
class TestSetTraceRootSpan(unittest.TestCase):
def setUp(self):
global dd_tracing_enabled
dd_tracing_enabled = False
os.environ["_X_AMZN_TRACE_ID"] = fake_xray_header_value
patcher = patch("datadog_lambda.tracing.send_segment")
self.mock_send_segment = patcher.start()
self.addCleanup(patcher.stop)
patcher = patch("datadog_lambda.tracing.is_lambda_context")
self.mock_is_lambda_context = patcher.start()
self.mock_is_lambda_context.return_value = True
self.addCleanup(patcher.stop)
patcher = patch("datadog_lambda.tracing.tracer.context_provider.activate")
self.mock_activate = patcher.start()
self.mock_activate.return_value = True
self.addCleanup(patcher.stop)
def tearDown(self):
global dd_tracing_enabled
dd_tracing_enabled = False
del os.environ["_X_AMZN_TRACE_ID"]
def test_mixed_parent_context_when_merging(self):
# When trace merging is enabled, and dd_trace headers are present,
# use the dd-trace trace-id and the x-ray parent-id
# This allows parenting relationships like dd-trace -> x-ray -> dd-trace
lambda_ctx = get_mock_context()
ctx, source, event_type = extract_dd_trace_context(
{
"headers": {
TraceHeader.TRACE_ID: "123",
TraceHeader.PARENT_ID: "321",
TraceHeader.SAMPLING_PRIORITY: "1",
}
},
lambda_ctx,
)
set_dd_trace_py_root(
source, True
) # When merging is off, always use dd-trace-context
expected_context = Context(
trace_id=123, # Trace Id from incomming context
span_id=int(fake_xray_header_value_parent_decimal), # Parent Id from x-ray
sampling_priority=1, # Sampling priority from incomming context
)
self.mock_activate.assert_called()
self.mock_activate.assert_has_calls([call(expected_context)])
def test_set_dd_trace_py_root_no_span_id(self):
os.environ["_X_AMZN_TRACE_ID"] = "Root=1-5e272390-8c398be037738dc042009320"
lambda_ctx = get_mock_context()
ctx, source, event_type = extract_dd_trace_context(
{
"headers": {
TraceHeader.TRACE_ID: "123",
TraceHeader.PARENT_ID: "321",
TraceHeader.SAMPLING_PRIORITY: "1",
}
},
lambda_ctx,
)
set_dd_trace_py_root(TraceContextSource.EVENT, True)
expected_context = Context(
trace_id=123, # Trace Id from incomming context
span_id=321, # Span Id from incoming context
sampling_priority=1, # Sampling priority from incomming context
)
self.mock_activate.assert_called()
self.mock_activate.assert_has_calls([call(expected_context)])
class TestServiceMapping(unittest.TestCase):
def setUp(self):
self.service_mapping = {}
def get_service_mapping(self):
return global_service_mapping
def set_service_mapping(self, new_service_mapping):
global_service_mapping.clear()
global_service_mapping.update(new_service_mapping)
def test_create_service_mapping_invalid_input(self):
# Test case where the input is a string without a colon to split on
val = "api1"
self.assertEqual(create_service_mapping(val), {})
# Test case where the input is an empty string
val = ""
self.assertEqual(create_service_mapping(val), {})
# Test case where the key and value are identical
val = "api1:api1"
self.assertEqual(create_service_mapping(val), {})
# Test case where the key or value is missing
val = ":api1"
self.assertEqual(create_service_mapping(val), {})
val = "api1:"
self.assertEqual(create_service_mapping(val), {})
def test_create_service_mapping(self):
val = "api1:service1,api2:service2"
expected_output = {"api1": "service1", "api2": "service2"}
self.assertEqual(create_service_mapping(val), expected_output)
def test_get_service_mapping(self):
os.environ["DD_SERVICE_MAPPING"] = "api1:service1,api2:service2"
expected_output = {"api1": "service1", "api2": "service2"}
self.set_service_mapping(
create_service_mapping(os.environ["DD_SERVICE_MAPPING"])
)
self.assertEqual(self.get_service_mapping(), expected_output)
def test_set_service_mapping(self):
new_service_mapping = {"api3": "service3", "api4": "service4"}
self.set_service_mapping(new_service_mapping)
self.assertEqual(self.get_service_mapping(), new_service_mapping)
def test_determine_service_name(self):
# Prepare the environment
os.environ["DD_SERVICE_MAPPING"] = "api1:service1,api2:service2"
self.set_service_mapping(
create_service_mapping(os.environ["DD_SERVICE_MAPPING"])
)
# Case where specific key is in the service mapping
specific_key = "api1"
self.assertEqual(
determine_service_name(
self.get_service_mapping(), specific_key, "lambda_url", "default"
),
"service1",
)
# Case where specific key is not in the service mapping, but generic key is
specific_key = "api3"
self.assertEqual(
determine_service_name(
self.get_service_mapping(), specific_key, "api2", "default"
),
"service2",
)
# Case where neither specific nor generic keys are in the service mapping
specific_key = "api3"
self.assertEqual(
determine_service_name(
self.get_service_mapping(), specific_key, "api3", "default"
),
"default",
)
def test_remaps_all_inferred_span_service_names_from_api_gateway_event(self):
new_service_mapping = {"lambda_api_gateway": "new-name"}
self.set_service_mapping(new_service_mapping)
event_sample_source = "api-gateway"
test_file = event_samples + event_sample_source + ".json"
with open(test_file, "r") as event:
original_event = json.load(event)
ctx = get_mock_context()
ctx.aws_request_id = "123"
span1 = create_inferred_span(original_event, ctx)
self.assertEqual(span1.get_tag("operation_name"), "aws.apigateway.rest")
self.assertEqual(span1.service, "new-name")
# Testing the second event
event2 = copy.deepcopy(original_event)
event2["requestContext"][
"domainName"
] = "different.execute-api.us-east-2.amazonaws.com"
span2 = create_inferred_span(event2, ctx)
self.assertEqual(span2.get_tag("operation_name"), "aws.apigateway.rest")
self.assertEqual(span2.service, "new-name")
def test_remaps_specific_inferred_span_service_names_from_api_gateway_event(
self,
):
new_service_mapping = {"1234567890": "new-name"}
self.set_service_mapping(new_service_mapping)
event_sample_source = "api-gateway"
test_file = event_samples + event_sample_source + ".json"
with open(test_file, "r") as event:
original_event = json.load(event)
ctx = get_mock_context()
ctx.aws_request_id = "123"
span1 = create_inferred_span(original_event, ctx)
self.assertEqual(span1.get_tag("operation_name"), "aws.apigateway.rest")
self.assertEqual(span1.service, "new-name")
# Testing the second event
event2 = copy.deepcopy(original_event)
event2["requestContext"]["apiId"] = "different"
span2 = create_inferred_span(event2, ctx)
self.assertEqual(span2.get_tag("operation_name"), "aws.apigateway.rest")