-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathprocessor.rs
More file actions
2337 lines (2068 loc) · 87.3 KB
/
processor.rs
File metadata and controls
2337 lines (2068 loc) · 87.3 KB
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
use std::{
collections::{HashMap, VecDeque},
sync::Arc,
time::{SystemTime, UNIX_EPOCH},
};
use chrono::{DateTime, Utc};
use datadog_opentelemetry::propagation::{
context::SpanContext,
datadog::{
DATADOG_PARENT_ID_KEY, DATADOG_SAMPLING_PRIORITY_KEY, DATADOG_TAGS_KEY,
DATADOG_TRACE_ID_KEY,
},
};
use libdd_trace_protobuf::pb::Span;
use libdd_trace_utils::tracer_header_tags;
use serde_json::Value;
use tokio::time::Instant;
use tracing::{debug, error, trace, warn};
use tokio::sync::mpsc;
use crate::{
config::{self, aws::AwsConfig},
extension::telemetry::events::{
InitType, ManagedInstanceReportMetrics, OnDemandReportMetrics, ReportMetrics,
RuntimeDoneMetrics, Status,
},
lifecycle::invocation::{
base64_to_string,
context::{Context, ContextBuffer, ReparentingInfo},
create_empty_span, generate_span_id, get_metadata_from_value,
span_inferrer::{self, SpanInferrer},
triggers::get_default_service_name,
},
logs::lambda::DurableContextUpdate,
metrics::enhanced::lambda::{EnhancedMetricData, Lambda as EnhancedMetrics},
proc::{
self, CPUData, NetworkData,
constants::{ETC_PATH, PROC_PATH},
},
tags::{lambda::tags::resolve_runtime_from_proc, provider},
traces::{
propagation::{DatadogCompositePropagator, carrier::JsonCarrier},
trace_processor::SendingTraceProcessor,
},
};
pub const MS_TO_NS: f64 = 1_000_000.0;
pub const S_TO_MS: u64 = 1_000;
pub const S_TO_NS: f64 = 1_000_000_000.0;
/// Threshold for classifying a Lambda cold start as proactive initialization.
///
/// Proactive initialization is a Lambda optimization where the runtime pre-initializes
/// a sandbox before any invocation is scheduled, to reduce cold start latency for future
/// requests.
pub const PROACTIVE_INITIALIZATION_THRESHOLD_MS: u64 = 10_000;
pub const DATADOG_INVOCATION_ERROR_MESSAGE_KEY: &str = "x-datadog-invocation-error-msg";
pub const DATADOG_INVOCATION_ERROR_TYPE_KEY: &str = "x-datadog-invocation-error-type";
pub const DATADOG_INVOCATION_ERROR_STACK_KEY: &str = "x-datadog-invocation-error-stack";
pub const DATADOG_INVOCATION_ERROR_KEY: &str = "x-datadog-invocation-error";
const DATADOG_SPAN_ID_KEY: &str = "x-datadog-span-id";
const TAG_SAMPLING_PRIORITY: &str = "_sampling_priority_v1";
pub struct Processor {
/// Buffer containing context of the previous 5 invocations
context_buffer: ContextBuffer,
/// Helper class to infer upstream span information and
/// extract trace context if available.
inferrer: SpanInferrer,
/// Propagator to extract span context from carriers.
propagator: Arc<DatadogCompositePropagator>,
/// Helper class to send enhanced metrics.
enhanced_metrics: EnhancedMetrics,
/// AWS configuration from the Lambda environment.
aws_config: Arc<AwsConfig>,
/// Flag to determine if a tracer was detected through
/// universal instrumentation.
tracer_detected: bool,
/// Runtime of the Lambda function.
///
/// This is set on the first invocation and reused for every
/// other invocation. Since we have to resolve the runtime
/// from the proc filesystem, it's not possible to know the
/// runtime before the first invocation.
runtime: Option<String>,
config: Arc<config::Config>,
service: String,
resource: String,
/// Dynamic tags calculated during the start of the invocation.
///
/// These tags are used to capture runtime and initialization.
dynamic_tags: HashMap<String, String>,
/// Tracks active concurrent invocations for monitoring enhanced metrics in Managed Instance mode.
active_invocations: usize,
/// Tracks whether if first invocation after init has been received in Managed Instance mode.
/// Used to determine if we should search for the empty context on an invocation.
awaiting_first_invocation: bool,
/// Sender used to forward durable execution context extracted from `aws.lambda` spans to the
/// logs agent. Decouples the trace agent from the logs agent: the trace agent sends spans
/// to the lifecycle processor, which extracts durable context and relays it here.
durable_context_tx: mpsc::Sender<DurableContextUpdate>,
/// Time of the `SnapStart` restore event, set when `PlatformRestoreStart` is received.
restore_time: Option<Instant>,
}
impl Processor {
#[must_use]
pub fn new(
tags_provider: Arc<provider::Provider>,
config: Arc<config::Config>,
aws_config: Arc<AwsConfig>,
metrics_aggregator: dogstatsd::aggregator::AggregatorHandle,
propagator: Arc<DatadogCompositePropagator>,
durable_context_tx: mpsc::Sender<DurableContextUpdate>,
) -> Self {
let resource = tags_provider
.get_canonical_resource_name()
.unwrap_or(String::from("aws.lambda"));
let service = get_default_service_name(
&config.service.clone().unwrap_or(resource.clone()),
"aws.lambda",
config.trace_aws_service_representation_enabled,
)
.to_lowercase();
let enhanced_metrics = EnhancedMetrics::new(metrics_aggregator, Arc::clone(&config));
enhanced_metrics.start_usage_metrics_task(); // starts the long-running task that monitors usage metrics (fd_use, threads_use, tmp_used)
Processor {
context_buffer: ContextBuffer::default(),
inferrer: SpanInferrer::new(Arc::clone(&config)),
propagator,
enhanced_metrics,
aws_config,
tracer_detected: false,
runtime: None,
config: Arc::clone(&config),
service,
resource,
dynamic_tags: HashMap::new(),
active_invocations: 0,
awaiting_first_invocation: false,
durable_context_tx,
restore_time: None,
}
}
/// Given a `request_id`, creates the context and adds the enhanced metric offsets to the context buffer.
///
pub fn on_invoke_event(&mut self, request_id: String) {
// In Managed Instance mode, if awaiting the first invocation after init, find and update the empty context created on init start
if self.aws_config.is_managed_instance_mode() && self.awaiting_first_invocation {
if self
.context_buffer
.update_empty_context_request_id(&request_id)
{
debug!(
"Updated empty context from init start with request_id: {}",
request_id
);
} else {
debug!("Expected empty context but not found, creating new context");
let invocation_span =
create_empty_span(String::from("aws.lambda"), &self.resource, &self.service);
self.set_init_tags();
self.context_buffer
.start_context(&request_id, invocation_span);
}
self.awaiting_first_invocation = false;
} else {
let invocation_span =
create_empty_span(String::from("aws.lambda"), &self.resource, &self.service);
// Important! Call set_init_tags() before adding the invocation to the context buffer
self.set_init_tags();
self.context_buffer
.start_context(&request_id, invocation_span);
}
let timestamp = std::time::UNIX_EPOCH
.elapsed()
.expect("can't poll clock, unrecoverable")
.as_secs()
.try_into()
.unwrap_or_default();
if self.config.lambda_proc_enhanced_metrics {
if self.aws_config.is_managed_instance_mode() {
// In Managed Instance mode, track concurrent invocations
self.active_invocations += 1;
// Start monitoring on the first active invocation
if self.active_invocations == 1 {
debug!("Starting usage metrics monitoring");
self.enhanced_metrics.resume_usage_metrics_monitoring();
}
} else {
// In On-Demand mode, we reset metrics and resume monitoring on each invocation
self.enhanced_metrics.restart_usage_metrics_monitoring();
}
// Collect offsets for network and cpu metrics
let network_offset: Option<NetworkData> = proc::get_network_data().ok();
let cpu_offset: Option<CPUData> = proc::get_cpu_data().ok();
let uptime_offset: Option<f64> = proc::get_uptime().ok();
let enhanced_metric_offsets = Some(EnhancedMetricData {
network_offset,
cpu_offset,
uptime_offset,
});
self.context_buffer
.add_enhanced_metric_data(&request_id, enhanced_metric_offsets);
}
// Increment the invocation metric
self.enhanced_metrics.increment_invocation_metric(timestamp);
self.enhanced_metrics.set_invoked_received();
// MANAGED INSTANCE MODE: Check for buffered UniversalInstrumentationStart with request_id
if self.aws_config.is_managed_instance_mode() {
if let Some(buffered_event) = self
.context_buffer
.take_universal_instrumentation_start_for_request_id(&request_id)
{
debug!(
"Managed Instance: Found buffered UniversalInstrumentationStart for request_id: {}",
request_id
);
// Infer span
self.inferrer
.infer_span(&buffered_event.payload_value, &self.aws_config);
self.process_on_universal_instrumentation_start(
request_id,
buffered_event.headers,
buffered_event.payload_value,
);
}
return;
}
// ON-DEMAND MODE: Use existing FIFO pairing logic (unchanged)
// If `UniversalInstrumentationStart` event happened first, process it
if let Some((headers, payload_value)) = self.context_buffer.pair_invoke_event(&request_id) {
// Infer span
self.inferrer.infer_span(&payload_value, &self.aws_config);
self.process_on_universal_instrumentation_start(request_id, headers, payload_value);
}
}
/// On the first invocation, determine if it's a cold start or proactive init.
///
/// For every other invocation, it will always be warm start.
///
fn set_init_tags(&mut self) {
let mut proactive_initialization = false;
let mut cold_start = false;
// If it's empty, then we are in a cold start
if self.context_buffer.is_empty() {
if self.aws_config.is_snapstart() {
match self.restore_time {
None => {
// PlatformRestoreStart hasn't arrived yet — restore and invoke
// happened close together, so this is a cold start (not proactive).
cold_start = true;
}
Some(restore_time) => {
let now = Instant::now();
let time_since_restore = now.duration_since(restore_time);
if time_since_restore.as_millis()
> PROACTIVE_INITIALIZATION_THRESHOLD_MS.into()
{
proactive_initialization = true;
} else {
cold_start = true;
}
}
}
} else {
let now = Instant::now();
let time_since_sandbox_init = now.duration_since(self.aws_config.sandbox_init_time);
if time_since_sandbox_init.as_millis()
> PROACTIVE_INITIALIZATION_THRESHOLD_MS.into()
{
proactive_initialization = true;
} else {
cold_start = true;
}
}
// Resolve runtime only once
let runtime = resolve_runtime_from_proc(PROC_PATH, ETC_PATH);
self.runtime = Some(runtime);
}
// Skip cold_start tag in Managed Instance mode
// We don't want to send this tag for spans, as the experience
// won't look good due to the time gap in the flame graph.
if !self.aws_config.is_managed_instance_mode() {
self.dynamic_tags
.insert(String::from("cold_start"), cold_start.to_string());
}
if proactive_initialization {
self.dynamic_tags.insert(
String::from("proactive_initialization"),
proactive_initialization.to_string(),
);
}
if let Some(runtime) = &self.runtime {
self.dynamic_tags
.insert(String::from("runtime"), runtime.clone());
self.enhanced_metrics.set_runtime_tag(runtime);
}
self.enhanced_metrics
.set_init_tags(proactive_initialization, cold_start);
}
/// Called when the platform init starts.
///
/// This is used to create a cold start span, since this telemetry event does not
/// provide a `request_id`, we try to guess which invocation is the cold start.
pub fn on_platform_init_start(&mut self, time: DateTime<Utc>, runtime_version: Option<String>) {
if runtime_version
.as_deref()
.is_some_and(|rv| rv.contains("DurableFunction"))
{
self.enhanced_metrics.set_durable_function_tag();
}
let start_time: i64 = SystemTime::from(time)
.duration_since(UNIX_EPOCH)
.expect("time went backwards")
.as_nanos()
.try_into()
.unwrap_or_default();
// In Managed Instance mode, create a context with empty request_id which will be updated on the first platform start received.
// In On-Demand mode, InitStart is received after the Invoke event, so we get the closest context by timestamp as it does not have a request_id.
let context = if self.aws_config.is_managed_instance_mode() {
let invocation_span =
create_empty_span(String::from("aws.lambda"), &self.resource, &self.service);
self.set_init_tags();
self.context_buffer.start_context("", invocation_span);
self.awaiting_first_invocation = true;
self.context_buffer.get_mut(&String::new())
} else {
self.context_buffer.get_closest_mut(start_time)
};
let Some(context) = context else {
debug!("Cannot process on platform init start, no invocation context found");
return;
};
// Skip creating cold start span in Managed Instances
// Although the telemetry is correct, we instead decide
// to not send it since the flame graph would show a big
// gap between the init and the first invocation.
if self.aws_config.is_managed_instance_mode() {
return;
}
// Create a cold start span
let mut cold_start_span = create_empty_span(
String::from("aws.lambda.cold_start"),
&self.resource,
&self.service,
);
cold_start_span.span_id = generate_span_id();
cold_start_span.start = start_time;
context.cold_start_span = Some(cold_start_span);
}
/// Given the duration of the platform init report, set the init duration metric.
///
#[allow(clippy::cast_possible_truncation)]
pub fn on_platform_init_report(
&mut self,
init_type: InitType,
duration_ms: f64,
timestamp: i64,
) {
self.enhanced_metrics
.set_init_duration_metric(init_type, duration_ms, timestamp);
// In Managed Instance mode, find the context with empty request_id
// In On-Demand mode, find the closest context by timestamp since we do not have the request_id
let context = if self.aws_config.is_managed_instance_mode() {
self.context_buffer.get_mut(&String::new())
} else {
self.context_buffer.get_closest_mut(timestamp)
};
let Some(context) = context else {
debug!("Cannot process on platform init report, no invocation context found");
return;
};
// Add duration to cold start span
if let Some(cold_start_span) = &mut context.cold_start_span {
// `round` is intentionally meant to be a whole integer
cold_start_span.duration = (duration_ms * MS_TO_NS) as i64;
}
}
/// Called when the `SnapStart` restore phase starts.
///
/// This is used to create a `snapstart_restore` span, since this telemetry event does not
/// provide a `request_id`, we try to guess which invocation is the restore similar to init.
pub fn on_platform_restore_start(&mut self, time: DateTime<Utc>) {
self.restore_time = Some(Instant::now());
let start_time: i64 = SystemTime::from(time)
.duration_since(UNIX_EPOCH)
.expect("time went backwards")
.as_nanos()
.try_into()
.unwrap_or_default();
// Get the closest context
let Some(context) = self.context_buffer.get_closest_mut(start_time) else {
debug!("Cannot process on platform restore start, no invocation context found");
return;
};
// Create a SnapStart restore span
let mut snapstart_restore_span = create_empty_span(
String::from("aws.lambda.snapstart_restore"),
&self.resource,
&self.service,
);
snapstart_restore_span.span_id = generate_span_id();
snapstart_restore_span.start = start_time;
context.snapstart_restore_span = Some(snapstart_restore_span);
}
/// Given the duration of the platform restore report, set the snapstart restore duration.
///
#[allow(clippy::cast_possible_truncation)]
pub fn on_platform_restore_report(&mut self, duration_ms: f64, timestamp: i64) {
self.enhanced_metrics
.set_snapstart_restore_duration_metric(duration_ms, timestamp);
let Some(context) = self.context_buffer.get_closest_mut(timestamp) else {
debug!("Cannot process on platform restore report, no invocation context found");
return;
};
if let Some(snapstart_restore_span) = &mut context.snapstart_restore_span {
// `round` is intentionally meant to be a whole integer
snapstart_restore_span.duration = (duration_ms * MS_TO_NS) as i64;
}
}
/// Given a `request_id` and the time of the platform start, add the start time to the context buffer.
///
pub fn on_platform_start(&mut self, request_id: String, time: DateTime<Utc>) {
if self.aws_config.is_managed_instance_mode() {
self.on_invoke_event(request_id.clone());
}
let start_time: i64 = SystemTime::from(time)
.duration_since(UNIX_EPOCH)
.expect("time went backwards")
.as_nanos()
.try_into()
.unwrap_or_default();
self.context_buffer.add_start_time(&request_id, start_time);
}
#[must_use]
pub fn is_managed_instance_mode(&self) -> bool {
self.aws_config.is_managed_instance_mode()
}
#[allow(clippy::too_many_arguments)]
#[allow(clippy::cast_possible_truncation)]
pub async fn on_platform_runtime_done(
&mut self,
request_id: &String,
metrics: RuntimeDoneMetrics,
status: Status,
error_type: Option<String>,
tags_provider: Arc<provider::Provider>,
trace_sender: Arc<SendingTraceProcessor>,
timestamp: i64,
) {
// Set the runtime duration metric
self.enhanced_metrics
.set_runtime_done_metrics(&metrics, timestamp);
if status != Status::Success {
// Increment the error metric
self.enhanced_metrics.increment_errors_metric(timestamp);
// Increment the error type metric
if status == Status::Timeout {
self.enhanced_metrics.increment_timeout_metric(timestamp);
}
if status == Status::Error && error_type == Some("Runtime.OutOfMemory".to_string()) {
debug!(
"Invocation Processor | PlatformRuntimeDone | Got Runtime.OutOfMemory. Incrementing OOM metric."
);
self.enhanced_metrics.increment_oom_metric(timestamp);
}
}
// In On-Demand mode, pause monitoring between invocations and emit the metrics on each invocation
if !self.aws_config.is_managed_instance_mode() {
self.enhanced_metrics.set_max_enhanced_metrics();
self.enhanced_metrics.set_usage_enhanced_metrics();
}
self.context_buffer
.add_runtime_duration(request_id, metrics.duration_ms);
// MANAGED INSTANCE MODE: Check for buffered UniversalInstrumentationEnd with request_id
if self.aws_config.is_managed_instance_mode() {
if let Some(buffered_event) = self
.context_buffer
.take_universal_instrumentation_end_for_request_id(request_id)
{
debug!(
"Managed Instance: Found buffered UniversalInstrumentationEnd for request_id: {}",
request_id
);
self.process_on_universal_instrumentation_end(
request_id.clone(),
buffered_event.headers,
buffered_event.payload_value,
);
}
} else {
// ON-DEMAND MODE: Use existing FIFO pairing logic (unchanged)
// If `UniversalInstrumentationEnd` event happened first, process it first
if let Some((headers, payload)) = self
.context_buffer
.pair_platform_runtime_done_event(request_id)
{
self.process_on_universal_instrumentation_end(request_id.clone(), headers, payload);
}
}
self.process_on_platform_runtime_done(request_id, status, tags_provider, trace_sender)
.await;
}
async fn process_on_platform_runtime_done(
&mut self,
request_id: &String,
status: Status,
tags_provider: Arc<provider::Provider>,
trace_sender: Arc<SendingTraceProcessor>,
) {
let context = self.enrich_ctx_at_platform_done(request_id, status);
if self.tracer_detected {
if let Some(ctx) = context
&& ctx.invocation_span.trace_id != 0
&& ctx.invocation_span.span_id != 0
{
self.send_ctx_spans(&tags_provider, &trace_sender, ctx)
.await;
}
} else {
self.send_cold_start_span(&tags_provider, &trace_sender)
.await;
}
}
fn enrich_ctx_at_platform_done(
&mut self,
request_id: &String,
status: Status,
) -> Option<Context> {
let Some(context) = self.context_buffer.get_mut(request_id) else {
debug!(
"Cannot process on platform runtime done, no invocation context found for request_id: {request_id}"
);
return None;
};
context.runtime_done_received = true;
// Handle timeout error case
if status == Status::Timeout {
if context.invocation_span.trace_id == 0 {
context.invocation_span.trace_id = generate_span_id();
}
if context.invocation_span.span_id == 0 {
context.invocation_span.span_id = generate_span_id();
}
context.invocation_span.error = 1; // Mark as error
context.invocation_span.meta.insert(
"error.msg".to_string(),
"Datadog detected a Timeout".to_string(),
);
context
.invocation_span
.meta
.insert("error.type".to_string(), "Timeout".to_string());
}
// Process enhanced metrics if available
if let Some(offsets) = &context.enhanced_metric_data {
self.enhanced_metrics.set_cpu_utilization_enhanced_metrics(
offsets.cpu_offset.clone(),
offsets.uptime_offset,
);
}
// todo(duncanista): Add missing metric tags for ASM
// Add dynamic and trigger tags
context
.invocation_span
.meta
.extend(self.dynamic_tags.clone());
if let Some(trigger_tags) = self.inferrer.get_trigger_tags() {
context.invocation_span.meta.extend(trigger_tags);
}
self.inferrer
.complete_inferred_spans(&context.invocation_span);
// Handle cold start span if present
if let Some(cold_start_span) = &mut context.cold_start_span
&& context.invocation_span.trace_id != 0
{
cold_start_span.trace_id = context.invocation_span.trace_id;
cold_start_span.parent_id = context.invocation_span.parent_id;
}
// Handle snapstart restore span if present
if let Some(snapstart_restore_span) = &mut context.snapstart_restore_span
&& context.invocation_span.trace_id != 0
{
snapstart_restore_span.trace_id = context.invocation_span.trace_id;
snapstart_restore_span.parent_id = context.invocation_span.parent_id;
}
Some(context.clone())
}
pub async fn send_ctx_spans(
&mut self,
tags_provider: &Arc<provider::Provider>,
trace_sender: &Arc<SendingTraceProcessor>,
context: Context,
) {
let (traces, body_size) = self.get_ctx_spans(context);
self.send_spans(traces, body_size, tags_provider, trace_sender)
.await;
}
fn get_ctx_spans(&mut self, context: Context) -> (Vec<Span>, usize) {
let mut body_size = std::mem::size_of_val(&context.invocation_span);
let mut traces = vec![context.invocation_span.clone()];
if let Some(inferred_span) = &self.inferrer.inferred_span {
body_size += std::mem::size_of_val(inferred_span);
traces.push(inferred_span.clone());
}
if let Some(ws) = &self.inferrer.wrapped_inferred_span {
body_size += std::mem::size_of_val(ws);
traces.push(ws.clone());
}
// SnapStart includes telemetry events from Init (Cold Start).
// However, these Init events are from when the snapshot was created and
// not when the lambda sandbox is actually created.
// So, if we have a snapstart restore span, use it instead of cold start span.
if let Some(snapstart_restore_span) = &context.snapstart_restore_span {
body_size += std::mem::size_of_val(snapstart_restore_span);
traces.push(snapstart_restore_span.clone());
} else if let Some(cold_start_span) = &context.cold_start_span {
body_size += std::mem::size_of_val(cold_start_span);
traces.push(cold_start_span.clone());
}
(traces, body_size)
}
/// For Node/Python: Updates the cold start span with the given trace ID.
/// Returns the Span ID of the cold start span so we can reparent the `aws.lambda.load` span.
pub fn set_cold_start_span_trace_id(&mut self, trace_id: u64) -> Option<u64> {
if let Some(cold_start_context) = self.context_buffer.get_context_with_cold_start()
&& let Some(cold_start_span) = &mut cold_start_context.cold_start_span
{
if cold_start_span.trace_id == 0 {
cold_start_span.trace_id = trace_id;
}
return Some(cold_start_span.span_id);
}
None
}
/// For Node/Python: Sends the cold start span to the trace agent.
async fn send_cold_start_span(
&mut self,
tags_provider: &Arc<provider::Provider>,
trace_sender: &Arc<SendingTraceProcessor>,
) {
if let Some(cold_start_context) = self.context_buffer.get_context_with_cold_start()
&& let Some(cold_start_span) = &mut cold_start_context.cold_start_span
{
if cold_start_span.trace_id == 0 {
debug!("Not sending cold start span because trace ID is unset.");
return;
}
let traces = vec![cold_start_span.clone()];
let body_size = size_of_val(cold_start_span);
self.send_spans(traces, body_size, tags_provider, trace_sender)
.await;
}
}
/// Used by universally instrumented runtimes to send context spans:
/// invocation span, inferred span(s), & cold start span.
/// Used by Node+Python to send cold start span.
async fn send_spans(
&mut self,
traces: Vec<Span>,
body_size: usize,
tags_provider: &Arc<provider::Provider>,
trace_sender: &Arc<SendingTraceProcessor>,
) {
// todo: figure out what to do here
let header_tags = tracer_header_tags::TracerHeaderTags {
lang: "",
lang_version: "",
lang_interpreter: "",
lang_vendor: "",
tracer_version: "",
container_id: "",
client_computed_top_level: false,
client_computed_stats: false,
dropped_p0_traces: 0,
dropped_p0_spans: 0,
};
if let Err(e) = trace_sender
.send_processed_traces(
self.config.clone(),
tags_provider.clone(),
header_tags,
vec![traces],
body_size,
self.inferrer.span_pointers.clone(),
)
.await
{
debug!("Failed to send context spans to agent: {e}");
}
}
/// Given a `request_id` and the duration in milliseconds of the platform report,
/// calculate the duration of the runtime if the `request_id` is found in the context buffer.
///
/// If the `request_id` is not found in the context buffer, return `None`.
/// If the `runtime_duration_ms` hasn't been seen, return `None`.
///
#[allow(clippy::too_many_arguments)]
pub async fn on_platform_report(
&mut self,
request_id: &String,
metrics: ReportMetrics,
timestamp: i64,
status: Status,
error_type: Option<String>,
spans: Option<Vec<crate::extension::telemetry::events::TelemetrySpan>>,
tags_provider: Arc<provider::Provider>,
trace_sender: Arc<SendingTraceProcessor>,
) {
// Set the report log metrics
self.enhanced_metrics
.set_report_log_metrics(&metrics, timestamp);
match metrics {
ReportMetrics::ManagedInstance(metric) => {
self.handle_managed_instance_report(
request_id,
metric,
timestamp,
status,
error_type,
spans,
tags_provider,
trace_sender,
)
.await;
}
ReportMetrics::OnDemand(metrics) => {
self.handle_ondemand_report(request_id, metrics, timestamp);
}
}
// Set Network and CPU time metrics
if let Some(context) = self.context_buffer.get(request_id)
&& let Some(offsets) = &context.enhanced_metric_data
{
self.enhanced_metrics
.set_network_enhanced_metrics(offsets.network_offset);
self.enhanced_metrics
.set_cpu_time_enhanced_metrics(offsets.cpu_offset.clone());
}
// Release the context now that all processing for this invocation is complete.
// This prevents unbounded memory growth across warm invocations.
self.context_buffer.remove(request_id);
// Prune the corresponding reparenting entry so that update_reparenting does not
// warn about a missing context for already-completed invocations.
self.context_buffer
.sorted_reparenting_info
.retain(|info| info.request_id != *request_id);
trace!(
"Context released (buffer size after remove: {})",
self.context_buffer.size()
);
}
/// Handles Managed Instance mode platform report processing.
///
/// In Managed Instance mode, platform.runtimeDone events are not sent, so this function
/// synthesizes a `RuntimeDone` event from the platform.report metrics.
#[allow(clippy::too_many_arguments)]
async fn handle_managed_instance_report(
&mut self,
request_id: &String,
metric: ManagedInstanceReportMetrics,
timestamp: i64,
status: Status,
error_type: Option<String>,
spans: Option<Vec<crate::extension::telemetry::events::TelemetrySpan>>,
tags_provider: Arc<provider::Provider>,
trace_sender: Arc<SendingTraceProcessor>,
) {
// Managed Instance mode doesn't have platform.runtimeDone event, so we synthesize it from platform.report
// Try to get duration from responseLatency span, otherwise fall back to metric.duration_ms
let duration_ms = spans
.as_ref()
.and_then(|span_vec| {
span_vec
.iter()
.find(|span| span.name == "responseLatency")
.map(|span| span.duration_ms)
})
.unwrap_or(metric.duration_ms);
let runtime_done_metrics = RuntimeDoneMetrics {
duration_ms,
produced_bytes: None,
};
// Track concurrent invocations - decrement after handling report
if self.active_invocations > 0 {
self.active_invocations -= 1;
} else {
debug!("Active invocations already at 0, not updating active invocations");
}
// Only pause monitoring when there are no active invocations
if self.active_invocations == 0 {
debug!("No active invocations, pausing usage metrics monitoring");
self.enhanced_metrics.pause_usage_metrics_monitoring();
}
// Only process if we have context for this request
if self.context_buffer.get(request_id).is_some() {
self.on_platform_runtime_done(
request_id,
runtime_done_metrics,
status,
error_type,
tags_provider,
trace_sender,
timestamp,
)
.await;
} else {
debug!(
"Received platform report for unknown request_id: {}",
request_id
);
}
}
/// Handles `OnDemand` mode platform report processing.
///
/// Processes OnDemand-specific metrics including OOM detection for provided.al runtimes
/// and post-runtime duration calculation.
fn handle_ondemand_report(
&mut self,
request_id: &String,
metrics: OnDemandReportMetrics,
timestamp: i64,
) {
// For provided.al runtimes, if the last invocation hit the memory limit, increment the OOM metric.
// We do this for provided.al runtimes because we didn't find another way to detect this under provided.al.
// We don't do this for other runtimes to avoid double counting.
if let Some(runtime) = &self.runtime
&& runtime.starts_with("provided.al")
&& metrics.max_memory_used_mb == metrics.memory_size_mb
{
debug!(
"Invocation Processor | PlatformReport | Last invocation hit memory limit. Incrementing OOM metric."
);
self.enhanced_metrics.increment_oom_metric(timestamp);
}
// Calculate and set post-runtime duration if context is available
if let Some(context) = self.context_buffer.get(request_id)
&& context.runtime_duration_ms != 0.0
{
let post_runtime_duration_ms = metrics.duration_ms - context.runtime_duration_ms;
self.enhanced_metrics
.set_post_runtime_duration_metric(post_runtime_duration_ms, timestamp);
}
}
pub fn on_shutdown_event(&mut self) {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.expect("unable to poll clock, unrecoverable")
.as_secs();
self.enhanced_metrics
.set_shutdown_metric(i64::try_from(now).expect("can't convert now to i64"));
self.enhanced_metrics
.set_unused_init_metric(i64::try_from(now).expect("can't convert now to i64"));
// In managed instance mode, emit sandbox-level usage metrics at shutdown
if self.aws_config.is_managed_instance_mode() {
self.enhanced_metrics.set_max_enhanced_metrics(); // Emit system limits (fd_max, threads_max, tmp_max)
self.enhanced_metrics.set_usage_enhanced_metrics(); // Emit sandbox-wide peak usage
}
}
/// If this method is called, it means that we are operating in a Universally Instrumented
/// runtime. Therefore, we need to set the `tracer_detected` flag to `true`.
///
pub fn on_universal_instrumentation_start(
&mut self,
headers: HashMap<String, String>,
payload_value: Value,
request_id: Option<String>,
) {
self.tracer_detected = true;
self.inferrer.infer_span(&payload_value, &self.aws_config);
// MANAGED INSTANCE MODE: Use request ID-based pairing for concurrent invocations
if self.aws_config.is_managed_instance_mode() {
if let Some(req_id) = request_id {
debug!(
"Managed Instance: Processing UniversalInstrumentationStart for request_id: {}",
req_id
);
if self
.context_buffer
.pair_universal_instrumentation_start_with_request_id(
&req_id,
&headers,
&payload_value,
)
{
// Invoke event already happened, process immediately
self.process_on_universal_instrumentation_start(req_id, headers, payload_value);
} else {
// Buffered for later pairing when Invoke event arrives
debug!(
"Managed Instance: Buffered UniversalInstrumentationStart for request_id: {}",
req_id
);
}
return;
}
// Missing request_id in managed instance mode - log warning and fall back to FIFO
warn!(
"Managed Instance: UniversalInstrumentationStart missing request_id header. \
Falling back to FIFO pairing (may cause incorrect pairing with concurrent invocations)"
);
}
// ON-DEMAND MODE: Use existing FIFO pairing logic (unchanged)
if let Some(request_id) = self
.context_buffer
.pair_universal_instrumentation_start_event(&headers, &payload_value)
{
self.process_on_universal_instrumentation_start(request_id, headers, payload_value);
}