-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathlambda.rs
More file actions
1791 lines (1633 loc) · 62.6 KB
/
lambda.rs
File metadata and controls
1791 lines (1633 loc) · 62.6 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 crate::extension::telemetry::events::{InitType, ReportMetrics, RuntimeDoneMetrics};
use crate::metrics::enhanced::constants::{self, BASE_LAMBDA_INVOCATION_PRICE};
use crate::metrics::enhanced::statfs;
use crate::metrics::enhanced::usage_metrics::{EnhancedMetricsHandle, EnhancedMetricsService};
use crate::proc::{self, CPUData, NetworkData};
use dogstatsd::metric::SortedTags;
use dogstatsd::metric::{Metric, MetricValue};
use dogstatsd::{aggregator::AggregatorHandle, metric};
use std::collections::HashMap;
use std::env::consts::ARCH;
use std::sync::Arc;
use tracing::debug;
use tracing::error;
pub struct Lambda {
pub aggr_handle: AggregatorHandle,
pub config: Arc<crate::config::Config>,
// Dynamic value tags are the ones we cannot obtain statically from the sandbox
dynamic_value_tags: HashMap<String, String>,
invoked_received: bool,
pub enhanced_metrics_handle: EnhancedMetricsHandle,
}
impl Lambda {
#[must_use]
pub fn new(aggregator: AggregatorHandle, config: Arc<crate::config::Config>) -> Lambda {
let (enhanced_metrics_service, enhanced_metrics_handle) = EnhancedMetricsService::new();
tokio::spawn(async move {
enhanced_metrics_service.run().await; // starts the enhanced metrics service for usage metrics
});
Lambda {
aggr_handle: aggregator,
config,
dynamic_value_tags: HashMap::new(),
invoked_received: false,
enhanced_metrics_handle,
}
}
/// Set the init tags in `dynamic_value_tags`
pub fn set_init_tags(&mut self, proactive_initialization: bool, cold_start: bool) {
self.dynamic_value_tags.remove("cold_start");
self.dynamic_value_tags.remove("proactive_initialization");
self.dynamic_value_tags
.insert(String::from("cold_start"), cold_start.to_string());
// Only set `proactive_initialization` tag if it is true
if proactive_initialization {
self.dynamic_value_tags.insert(
String::from("proactive_initialization"),
String::from("true"),
);
}
}
/// Sets the runtime tag in `dynamic_value_tags`
pub fn set_runtime_tag(&mut self, runtime: &str) {
self.dynamic_value_tags
.insert(String::from("runtime"), runtime.to_string());
}
/// Sets the `durable_function:true` tag in `dynamic_value_tags`
pub fn set_durable_function_tag(&mut self) {
self.dynamic_value_tags
.insert(String::from("durable_function"), String::from("true"));
}
fn get_dynamic_value_tags(&self) -> Option<SortedTags> {
let vec_tags: Vec<String> = self
.dynamic_value_tags
.iter()
.map(|(k, v)| format!("{k}:{v}"))
.collect();
let string_tags = vec_tags.join(",");
SortedTags::parse(&string_tags).ok()
}
pub fn increment_invocation_metric(&self, timestamp: i64) {
self.increment_metric(constants::INVOCATIONS_METRIC, timestamp);
}
pub fn increment_errors_metric(&self, timestamp: i64) {
self.increment_metric(constants::ERRORS_METRIC, timestamp);
}
pub fn increment_timeout_metric(&self, timestamp: i64) {
self.increment_metric(constants::TIMEOUTS_METRIC, timestamp);
}
// This function is called in three cases:
// 1. Runtime-specific OOM error (can happen in .NET, Node.js and Java as far as we know)
// 2. PlatformRuntimeDone event reports "error_type: Runtime.OutOfMemory" (can happen in Ruby and Python as far as we know)
// 3. PlatformReport event reports "max_memory_used_mb == memory_size_mb" (can happen in many runtimes, but
// we only call increment_oom_metric() for provided.al runtimes)
// This is our best effort to cover different cases without double counting. We can adjust this if we find more cases.
pub fn increment_oom_metric(&self, timestamp: i64) {
self.increment_metric(constants::OUT_OF_MEMORY_METRIC, timestamp);
}
pub fn set_init_duration_metric(
&mut self,
init_type: InitType,
init_duration_ms: f64,
timestamp: i64,
) {
if !self.config.enhanced_metrics {
return;
}
self.dynamic_value_tags
.insert(String::from("init_type"), init_type.to_string());
let metric = Metric::new(
constants::INIT_DURATION_METRIC.into(),
MetricValue::distribution(init_duration_ms * constants::MS_TO_SEC),
self.get_dynamic_value_tags(),
Some(timestamp),
);
if let Err(e) = self.aggr_handle.insert_batch(vec![metric]) {
error!("failed to insert metric: {}", e);
}
}
pub fn set_snapstart_restore_duration_metric(
&mut self,
restore_duration_ms: f64,
timestamp: i64,
) {
if !self.config.enhanced_metrics {
return;
}
let metric = Metric::new(
constants::SNAPSTART_RESTORE_DURATION_METRIC.into(),
MetricValue::distribution(restore_duration_ms * constants::MS_TO_SEC),
self.get_dynamic_value_tags(),
Some(timestamp),
);
if let Err(e) = self.aggr_handle.insert_batch(vec![metric]) {
error!("failed to insert metric: {}", e);
}
}
pub fn set_invoked_received(&mut self) {
self.invoked_received = true;
}
fn increment_metric(&self, metric_name: &str, timestamp: i64) {
if !self.config.enhanced_metrics {
return;
}
let tags = self.get_dynamic_value_tags();
let metric = Metric::new(
metric_name.into(),
MetricValue::distribution(1f64),
tags,
Some(timestamp),
);
if let Err(e) = self.aggr_handle.insert_batch(vec![metric]) {
error!("failed to insert metric: {}", e);
}
}
pub fn set_runtime_done_metrics(&self, metrics: &RuntimeDoneMetrics, timestamp: i64) {
if !self.config.enhanced_metrics {
return;
}
let metric = Metric::new(
constants::RUNTIME_DURATION_METRIC.into(),
MetricValue::distribution(metrics.duration_ms),
// Datadog expects this value as milliseconds, not seconds
self.get_dynamic_value_tags(),
Some(timestamp),
);
if let Err(e) = self.aggr_handle.insert_batch(vec![metric]) {
error!("failed to insert runtime duration metric: {}", e);
}
if let Some(produced_bytes) = metrics.produced_bytes {
let metric = Metric::new(
constants::PRODUCED_BYTES_METRIC.into(),
MetricValue::distribution(produced_bytes as f64),
// Datadog expects this value as milliseconds, not seconds
self.get_dynamic_value_tags(),
Some(timestamp),
);
if let Err(e) = self.aggr_handle.insert_batch(vec![metric]) {
error!("failed to insert produced bytes metric: {}", e);
}
}
}
pub fn set_shutdown_metric(&self, timestamp: i64) {
if !self.config.enhanced_metrics {
return;
}
self.increment_metric(constants::SHUTDOWNS_METRIC, timestamp);
}
pub fn set_unused_init_metric(&self, timestamp: i64) {
if !self.invoked_received {
self.increment_metric(constants::UNUSED_INIT, timestamp);
}
}
pub fn set_post_runtime_duration_metric(&self, duration_ms: f64, timestamp: i64) {
if !self.config.enhanced_metrics {
return;
}
let metric = metric::Metric::new(
constants::POST_RUNTIME_DURATION_METRIC.into(),
MetricValue::distribution(duration_ms),
// Datadog expects this value as milliseconds, not seconds
self.get_dynamic_value_tags(),
Some(timestamp),
);
if let Err(e) = self.aggr_handle.insert_batch(vec![metric]) {
error!("failed to insert post runtime duration metric: {}", e);
}
}
pub fn generate_network_enhanced_metrics(
network_data_offset: NetworkData,
network_data_end: NetworkData,
aggr: &AggregatorHandle,
tags: Option<SortedTags>,
) {
let now = std::time::UNIX_EPOCH
.elapsed()
.expect("unable to poll clock, unrecoverable")
.as_secs()
.try_into()
.unwrap_or_default();
let rx_bytes = network_data_end.rx_bytes - network_data_offset.rx_bytes;
let tx_bytes = network_data_end.tx_bytes - network_data_offset.tx_bytes;
let total_network = rx_bytes + tx_bytes;
let metric = Metric::new(
constants::RX_BYTES_METRIC.into(),
MetricValue::distribution(rx_bytes),
tags.clone(),
Some(now),
);
if let Err(e) = aggr.insert_batch(vec![metric]) {
error!("Failed to insert rx_bytes metric: {}", e);
}
let metric = Metric::new(
constants::TX_BYTES_METRIC.into(),
MetricValue::distribution(tx_bytes),
tags.clone(),
Some(now),
);
if let Err(e) = aggr.insert_batch(vec![metric]) {
error!("Failed to insert tx_bytes metric: {}", e);
}
let metric = Metric::new(
constants::TOTAL_NETWORK_METRIC.into(),
MetricValue::distribution(total_network),
tags.clone(),
Some(now),
);
if let Err(e) = aggr.insert_batch(vec![metric]) {
error!("Failed to insert total_network metric: {}", e);
}
}
pub fn set_network_enhanced_metrics(&self, network_offset: Option<NetworkData>) {
if !self.config.enhanced_metrics {
return;
}
if let Some(offset) = network_offset {
let aggr_handle = self.aggr_handle.clone();
match proc::get_network_data() {
Ok(data) => {
Self::generate_network_enhanced_metrics(
offset,
data,
&aggr_handle,
self.get_dynamic_value_tags(),
);
}
Err(_e) => {
debug!("Could not find data to generate network enhanced metrics");
}
}
} else {
debug!("Could not find network offset data to generate network enhanced metrics");
}
}
pub(crate) fn generate_cpu_time_enhanced_metrics(
cpu_data_offset: &CPUData,
cpu_data_end: &CPUData,
aggr: &AggregatorHandle,
tags: Option<SortedTags>,
) {
let cpu_user_time = cpu_data_end.total_user_time_ms - cpu_data_offset.total_user_time_ms;
let cpu_system_time =
cpu_data_end.total_system_time_ms - cpu_data_offset.total_system_time_ms;
let cpu_total_time = cpu_user_time + cpu_system_time;
let now = std::time::UNIX_EPOCH
.elapsed()
.expect("unable to poll clock, unrecoverable")
.as_secs()
.try_into()
.unwrap_or_default();
let metric = Metric::new(
constants::CPU_USER_TIME_METRIC.into(),
MetricValue::distribution(cpu_user_time),
tags.clone(),
Some(now),
);
if let Err(e) = aggr.insert_batch(vec![metric]) {
error!("Failed to insert cpu_user_time metric: {}", e);
}
let metric = Metric::new(
constants::CPU_SYSTEM_TIME_METRIC.into(),
MetricValue::distribution(cpu_system_time),
tags.clone(),
Some(now),
);
if let Err(e) = aggr.insert_batch(vec![metric]) {
error!("Failed to insert cpu_system_time metric: {}", e);
}
let metric = Metric::new(
constants::CPU_TOTAL_TIME_METRIC.into(),
MetricValue::distribution(cpu_total_time),
tags.clone(),
Some(now),
);
if let Err(e) = aggr.insert_batch(vec![metric]) {
error!("Failed to insert cpu_total_time metric: {}", e);
}
}
pub fn set_cpu_time_enhanced_metrics(&self, cpu_offset: Option<CPUData>) {
if !self.config.enhanced_metrics {
return;
}
let aggr_handle = self.aggr_handle.clone();
let cpu_data = proc::get_cpu_data();
match (cpu_offset, cpu_data) {
(Some(cpu_offset), Ok(cpu_data)) => {
Self::generate_cpu_time_enhanced_metrics(
&cpu_offset,
&cpu_data,
&aggr_handle,
self.get_dynamic_value_tags(),
);
}
(_, _) => {
debug!("Could not find data to generate cpu time enhanced metrics");
}
}
}
pub(crate) fn generate_cpu_utilization_enhanced_metrics(
cpu_data_offset: &CPUData,
cpu_data_end: &CPUData,
uptime_data_offset: f64,
uptime_data_end: f64,
aggr: &AggregatorHandle,
tags: Option<SortedTags>,
) {
let num_cores = cpu_data_end.individual_cpu_idle_times.len() as f64;
let uptime = uptime_data_end - uptime_data_offset;
let total_idle_time = cpu_data_end.total_idle_time_ms - cpu_data_offset.total_idle_time_ms;
// Validation: uptime should be positive and meaningful
if uptime <= 0.0 {
debug!(
"Invalid uptime delta: {}, skipping CPU utilization metrics",
uptime
);
return;
}
let mut max_idle_time = 0.0;
let mut min_idle_time = f64::MAX;
let now = std::time::UNIX_EPOCH
.elapsed()
.expect("unable to poll clock, unrecoverable")
.as_secs()
.try_into()
.unwrap_or_default();
for (cpu_name, cpu_idle_time) in &cpu_data_end.individual_cpu_idle_times {
if let Some(cpu_idle_time_offset) =
cpu_data_offset.individual_cpu_idle_times.get(cpu_name)
{
let idle_time = cpu_idle_time - cpu_idle_time_offset;
// Prevent negative values but allow overflow
let idle_time = idle_time.max(0.0);
if idle_time < min_idle_time {
min_idle_time = idle_time;
}
if idle_time > max_idle_time {
max_idle_time = idle_time;
}
}
}
// Maximally utilized CPU is the one with the least time spent in the idle process
// Multiply by 100 to report as percentage
// Prevent negative values but allow overflow
let cpu_max_utilization = (((uptime - min_idle_time) / uptime) * 100.0).max(0.0);
// Minimally utilized CPU is the one with the most time spent in the idle process
// Multiply by 100 to report as percentage
// Prevent negative values but allow overflow
let cpu_min_utilization = (((uptime - max_idle_time) / uptime) * 100.0).max(0.0);
// CPU total utilization is the proportion of total non-idle time to the total uptime across all cores
// Prevent negative values but allow overflow
let cpu_total_utilization_decimal =
(((uptime * num_cores) - total_idle_time) / (uptime * num_cores)).max(0.0);
// Multiply by 100 to report as percentage
let cpu_total_utilization_pct = cpu_total_utilization_decimal * 100.0;
// Multiply by num_cores to report in terms of cores
let cpu_total_utilization = cpu_total_utilization_decimal * num_cores;
let metrics = vec![
Metric::new(
constants::CPU_TOTAL_UTILIZATION_PCT_METRIC.into(),
MetricValue::distribution(cpu_total_utilization_pct),
tags.clone(),
Some(now),
),
Metric::new(
constants::CPU_TOTAL_UTILIZATION_METRIC.into(),
MetricValue::distribution(cpu_total_utilization),
tags.clone(),
Some(now),
),
Metric::new(
constants::NUM_CORES_METRIC.into(),
MetricValue::distribution(num_cores),
tags.clone(),
Some(now),
),
Metric::new(
constants::CPU_MAX_UTILIZATION_METRIC.into(),
MetricValue::distribution(cpu_max_utilization),
tags.clone(),
Some(now),
),
Metric::new(
constants::CPU_MIN_UTILIZATION_METRIC.into(),
MetricValue::distribution(cpu_min_utilization),
tags,
Some(now),
),
];
if let Err(e) = aggr.insert_batch(metrics) {
error!("Failed to insert cpu utilization metrics: {}", e);
}
}
pub fn set_cpu_utilization_enhanced_metrics(
&self,
cpu_offset: Option<CPUData>,
uptime_offset: Option<f64>,
) {
if !self.config.enhanced_metrics {
return;
}
let aggr_handle = self.aggr_handle.clone();
let cpu_data = proc::get_cpu_data();
let uptime_data = proc::get_uptime();
match (cpu_offset, cpu_data, uptime_offset, uptime_data) {
(Some(cpu_offset), Ok(cpu_data), Some(uptime_offset), Ok(uptime_data)) => {
Self::generate_cpu_utilization_enhanced_metrics(
&cpu_offset,
&cpu_data,
uptime_offset,
uptime_data,
&aggr_handle,
self.get_dynamic_value_tags(),
);
}
(_, _, _, _) => {
debug!("Could not find data to generate cpu utilization enhanced metrics");
}
}
}
fn calculate_estimated_cost_usd(billed_duration_ms: u64, memory_size_mb: u64) -> f64 {
let gb_seconds = (billed_duration_ms as f64 * constants::MS_TO_SEC)
* (memory_size_mb as f64 / constants::MB_TO_GB);
let price_per_gb = match ARCH {
"x86_64" => constants::X86_LAMBDA_PRICE_PER_GB_SECOND,
"aarch64" => constants::ARM_LAMBDA_PRICE_PER_GB_SECOND,
_ => {
error!("unsupported architecture: {}", ARCH);
return 0.0;
}
};
((BASE_LAMBDA_INVOCATION_PRICE + (gb_seconds * price_per_gb)) * 1e12).round() / 1e12
}
pub fn set_report_log_metrics(&self, metrics: &ReportMetrics, timestamp: i64) {
if !self.config.enhanced_metrics {
return;
}
let metric = metric::Metric::new(
constants::DURATION_METRIC.into(),
MetricValue::distribution(metrics.duration_ms() * constants::MS_TO_SEC),
self.get_dynamic_value_tags(),
Some(timestamp),
);
if let Err(e) = self.aggr_handle.insert_batch(vec![metric]) {
error!("failed to insert duration metric: {}", e);
}
match metrics {
ReportMetrics::ManagedInstance(_) => {
// In Managed Instance mode, we can't track these metrics for a given lambda invocation
// - billed duration
// - max memory used
// - memory size
// - estimated cost
}
ReportMetrics::OnDemand(metrics) => {
let metric = metric::Metric::new(
constants::BILLED_DURATION_METRIC.into(),
MetricValue::distribution(
metrics.billed_duration_ms as f64 * constants::MS_TO_SEC,
),
self.get_dynamic_value_tags(),
Some(timestamp),
);
if let Err(e) = self.aggr_handle.insert_batch(vec![metric]) {
error!("failed to insert billed duration metric: {}", e);
}
let metric = metric::Metric::new(
constants::MAX_MEMORY_USED_METRIC.into(),
MetricValue::distribution(metrics.max_memory_used_mb as f64),
self.get_dynamic_value_tags(),
Some(timestamp),
);
if let Err(e) = self.aggr_handle.insert_batch(vec![metric]) {
error!("failed to insert max memory used metric: {}", e);
}
let metric = metric::Metric::new(
constants::MEMORY_SIZE_METRIC.into(),
MetricValue::distribution(metrics.memory_size_mb as f64),
self.get_dynamic_value_tags(),
Some(timestamp),
);
if let Err(e) = self.aggr_handle.insert_batch(vec![metric]) {
error!("failed to insert memory size metric: {}", e);
}
let cost_usd = Self::calculate_estimated_cost_usd(
metrics.billed_duration_ms,
metrics.memory_size_mb,
);
let metric = metric::Metric::new(
constants::ESTIMATED_COST_METRIC.into(),
MetricValue::distribution(cost_usd),
self.get_dynamic_value_tags(),
Some(timestamp),
);
if let Err(e) = self.aggr_handle.insert_batch(vec![metric]) {
error!("failed to insert estimated cost metric: {}", e);
}
}
}
}
pub fn start_usage_metrics_task(&self) {
if !self.config.enhanced_metrics {
return;
}
let enhanced_metrics_handle = self.enhanced_metrics_handle.clone();
tokio::spawn(async move {
let mut interval = tokio::time::interval(std::time::Duration::from_millis(
constants::MONITORING_INTERVAL,
));
let mut monitoring_state_rx = enhanced_metrics_handle.get_monitoring_state_receiver();
let mut is_active = *monitoring_state_rx.borrow();
loop {
tokio::select! {
biased;
_ = monitoring_state_rx.changed() => {
is_active = *monitoring_state_rx.borrow();
}
_ = interval.tick() => {
if is_active {
let pids = proc::get_pid_list();
let tmp_used = statfs::get_tmp_used().ok();
let fd_use = Some(proc::get_fd_use_data(&pids));
let threads_use = proc::get_threads_use_data(&pids).ok();
if let Err(e) = enhanced_metrics_handle.update_metrics(tmp_used, fd_use, threads_use) {
debug!("Failed to update process enhanced metrics: {}", e);
}
}
}
}
}
});
}
// Reset metrics and resume monitoring for the next invocation
pub fn restart_usage_metrics_monitoring(&self) {
if !self.config.enhanced_metrics {
return;
}
// reset metrics for the new invocation
if let Err(e) = self.enhanced_metrics_handle.reset_metrics() {
debug!("Failed to reset enhanced metrics on new invocation: {}", e);
}
self.enhanced_metrics_handle.resume_monitoring();
}
/// Resume monitoring without resetting metrics. Used in managed instance mode to resume monitoring between invocations.
pub fn resume_usage_metrics_monitoring(&self) {
if !self.config.enhanced_metrics {
return;
}
debug!("Starting sandbox-level usage metrics monitoring (managed instance mode)");
self.enhanced_metrics_handle.resume_monitoring();
}
/// Pause monitoring without emitting metrics. Used in managed instance mode to pause between invocations.
pub fn pause_usage_metrics_monitoring(&self) {
if !self.config.enhanced_metrics {
return;
}
self.enhanced_metrics_handle.pause_monitoring();
}
pub fn set_usage_enhanced_metrics(&self) {
if !self.config.enhanced_metrics {
return;
}
self.enhanced_metrics_handle.pause_monitoring();
let enhanced_metrics_handle = self.enhanced_metrics_handle.clone();
let aggr_handle = self.aggr_handle.clone();
let tags = self.get_dynamic_value_tags();
tokio::spawn(async move {
match enhanced_metrics_handle.get_metrics().await {
Ok(metrics) => {
let now = std::time::UNIX_EPOCH
.elapsed()
.expect("unable to poll clock, unrecoverable")
.as_secs()
.try_into()
.unwrap_or_default();
// Set all tmp metrics - need tmp_max and tmp_used to calculate tmp_free
if metrics.tmp_used > 0.0 {
let metric = Metric::new(
constants::TMP_USED_METRIC.into(),
MetricValue::distribution(metrics.tmp_used),
tags.clone(),
Some(now),
);
if let Err(e) = aggr_handle.insert_batch(vec![metric]) {
error!("Failed to insert tmp_used metric: {}", e);
}
if let Ok(tmp_max) = statfs::get_tmp_max() {
let metric = Metric::new(
constants::TMP_MAX_METRIC.into(),
MetricValue::distribution(tmp_max),
tags.clone(),
Some(now),
);
if let Err(e) = aggr_handle.insert_batch(vec![metric]) {
error!("Failed to insert tmp_max metric: {}", e);
}
let tmp_free = tmp_max - metrics.tmp_used;
let metric = Metric::new(
constants::TMP_FREE_METRIC.into(),
MetricValue::distribution(tmp_free),
tags.clone(),
Some(now),
);
if let Err(e) = aggr_handle.insert_batch(vec![metric]) {
error!("Failed to insert tmp_free metric: {}", e);
}
}
}
// Set file descriptor use
if metrics.fd_use > 0.0 {
let metric = Metric::new(
constants::FD_USE_METRIC.into(),
MetricValue::distribution(metrics.fd_use),
tags.clone(),
Some(now),
);
if let Err(e) = aggr_handle.insert_batch(vec![metric]) {
error!("Failed to insert fd_use metric: {}", e);
}
}
// Set threads use
if metrics.threads_use > 0.0 {
let metric = Metric::new(
constants::THREADS_USE_METRIC.into(),
MetricValue::distribution(metrics.threads_use),
tags.clone(),
Some(now),
);
if let Err(e) = aggr_handle.insert_batch(vec![metric]) {
error!("Failed to insert threads_use metric: {}", e);
}
}
}
Err(e) => {
error!("Failed to get final usage metrics: {}", e);
}
}
});
}
pub fn set_max_enhanced_metrics(&self) {
if !self.config.enhanced_metrics {
return;
}
let pids = proc::get_pid_list();
let fd_max = proc::get_fd_max_data(&pids);
let threads_max = proc::get_threads_max_data(&pids);
let now = std::time::UNIX_EPOCH
.elapsed()
.expect("unable to poll clock, unrecoverable")
.as_secs()
.try_into()
.unwrap_or_default();
let tags = self.get_dynamic_value_tags();
let metric = Metric::new(
constants::FD_MAX_METRIC.into(),
MetricValue::distribution(fd_max),
tags.clone(),
Some(now),
);
if let Err(e) = self.aggr_handle.insert_batch(vec![metric]) {
error!("Failed to insert fd_max metric: {}", e);
}
let metric = Metric::new(
constants::THREADS_MAX_METRIC.into(),
MetricValue::distribution(threads_max),
tags,
Some(now),
);
if let Err(e) = self.aggr_handle.insert_batch(vec![metric]) {
error!("Failed to insert threads_max metric: {}", e);
}
}
}
#[derive(Clone, Debug)]
pub struct EnhancedMetricData {
pub network_offset: Option<NetworkData>,
pub cpu_offset: Option<CPUData>,
pub uptime_offset: Option<f64>,
}
impl PartialEq for EnhancedMetricData {
fn eq(&self, other: &Self) -> bool {
self.network_offset == other.network_offset
&& self.cpu_offset == other.cpu_offset
&& self.uptime_offset == other.uptime_offset
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use std::collections::HashMap;
use super::*;
use crate::config;
use crate::extension::telemetry::events::{OnDemandReportMetrics, ReportMetrics};
use dogstatsd::aggregator::AggregatorService;
use dogstatsd::metric::EMPTY_TAGS;
const PRECISION: f64 = 0.000_000_01;
fn setup() -> (AggregatorHandle, Arc<config::Config>) {
let config = Arc::new(config::Config {
service: Some("test-service".to_string()),
tags: HashMap::from([("test".to_string(), "tags".to_string())]),
..config::Config::default()
});
let (service, handle) =
AggregatorService::new(EMPTY_TAGS, 1024).expect("failed to create aggregator service");
tokio::spawn(service.run());
(handle, config)
}
async fn assert_sketch(handle: &AggregatorHandle, metric_id: &str, value: f64, timestamp: i64) {
let ts = (timestamp / 10) * 10;
if let Some(e) = handle
.get_entry_by_id(metric_id.into(), None, ts)
.await
.unwrap()
{
let metric = e.value.get_sketch().unwrap();
assert!((metric.max().unwrap() - value).abs() < PRECISION);
assert!((metric.min().unwrap() - value).abs() < PRECISION);
assert!((metric.sum().unwrap() - value).abs() < PRECISION);
assert!((metric.avg().unwrap() - value).abs() < PRECISION);
} else {
panic!("{}", format!("{metric_id} not found"));
}
}
#[tokio::test]
async fn test_set_durable_function_tag() {
let (metrics_aggr, my_config) = setup();
let mut lambda = Lambda::new(metrics_aggr.clone(), my_config);
let now: i64 = std::time::UNIX_EPOCH
.elapsed()
.expect("unable to poll clock, unrecoverable")
.as_secs()
.try_into()
.unwrap_or_default();
lambda.set_durable_function_tag();
lambda.increment_invocation_metric(now);
// Verify the metric was emitted with the durable_function:true tag
let ts = (now / 10) * 10;
let durable_tags = SortedTags::parse("durable_function:true").ok();
let entry = metrics_aggr
.get_entry_by_id(constants::INVOCATIONS_METRIC.into(), durable_tags, ts)
.await
.unwrap();
assert!(
entry.is_some(),
"Expected metric with durable_function:true tag"
);
}
#[tokio::test]
#[allow(clippy::float_cmp)]
async fn test_increment_invocation_metric() {
let (metrics_aggr, my_config) = setup();
let lambda = Lambda::new(metrics_aggr.clone(), my_config);
let now: i64 = std::time::UNIX_EPOCH
.elapsed()
.expect("unable to poll clock, unrecoverable")
.as_secs()
.try_into()
.unwrap_or_default();
lambda.increment_invocation_metric(now);
let now: i64 = std::time::UNIX_EPOCH
.elapsed()
.expect("unable to poll clock, unrecoverable")
.as_secs()
.try_into()
.unwrap_or_default();
assert_sketch(&metrics_aggr, constants::INVOCATIONS_METRIC, 1f64, now).await;
}
#[tokio::test]
#[allow(clippy::float_cmp)]
async fn test_increment_errors_metric() {
let (metrics_aggr, my_config) = setup();
let lambda = Lambda::new(metrics_aggr.clone(), my_config);
let now: i64 = std::time::UNIX_EPOCH
.elapsed()
.expect("unable to poll clock, unrecoverable")
.as_secs()
.try_into()
.unwrap_or_default();
lambda.increment_errors_metric(now);
let now: i64 = std::time::UNIX_EPOCH
.elapsed()
.expect("unable to poll clock, unrecoverable")
.as_secs()
.try_into()
.unwrap_or_default();
assert_sketch(&metrics_aggr, constants::ERRORS_METRIC, 1f64, now).await;
}
#[tokio::test]
#[allow(clippy::too_many_lines)]
async fn test_disabled() {
let (metrics_aggr, no_config) = setup();
let my_config = Arc::new(config::Config {
enhanced_metrics: false,
..no_config.as_ref().clone()
});
let mut lambda = Lambda::new(metrics_aggr.clone(), my_config);
let now: i64 = std::time::UNIX_EPOCH
.elapsed()
.expect("unable to poll clock, unrecoverable")
.as_secs()
.try_into()
.unwrap_or_default();
lambda.increment_invocation_metric(now);
lambda.increment_errors_metric(now);
lambda.increment_timeout_metric(now);
lambda.set_init_duration_metric(InitType::OnDemand, 100.0, now);
lambda.set_runtime_done_metrics(
&RuntimeDoneMetrics {
duration_ms: 100.0,
produced_bytes: Some(42_u64),
},
now,
);
lambda.set_post_runtime_duration_metric(100.0, now);
lambda.set_report_log_metrics(
&ReportMetrics::OnDemand(OnDemandReportMetrics {
duration_ms: 100.0,
billed_duration_ms: 100,
max_memory_used_mb: 128,
memory_size_mb: 256,
init_duration_ms: Some(50.0),
restore_duration_ms: None,
}),
now,
);
assert!(
metrics_aggr
.get_entry_by_id(constants::INVOCATIONS_METRIC.into(), None, now)
.await
.unwrap()
.is_none()
);
assert!(
metrics_aggr
.get_entry_by_id(constants::ERRORS_METRIC.into(), None, now)
.await
.unwrap()
.is_none()
);
assert!(
metrics_aggr
.get_entry_by_id(constants::TIMEOUTS_METRIC.into(), None, now)
.await
.unwrap()
.is_none()
);
assert!(
metrics_aggr
.get_entry_by_id(constants::INIT_DURATION_METRIC.into(), None, now)
.await
.unwrap()
.is_none()
);
assert!(
metrics_aggr
.get_entry_by_id(constants::RUNTIME_DURATION_METRIC.into(), None, now)
.await
.unwrap()
.is_none()
);
assert!(
metrics_aggr
.get_entry_by_id(constants::PRODUCED_BYTES_METRIC.into(), None, now)
.await
.unwrap()
.is_none()
);
assert!(
metrics_aggr
.get_entry_by_id(constants::POST_RUNTIME_DURATION_METRIC.into(), None, now)
.await