-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathprocessor.rs
More file actions
1639 lines (1453 loc) · 65.4 KB
/
processor.rs
File metadata and controls
1639 lines (1453 loc) · 65.4 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::error::Error;
use std::sync::Arc;
use tokio::sync::mpsc::Sender;
use tracing::{debug, error};
use crate::LAMBDA_RUNTIME_SLUG;
use crate::config;
use crate::event_bus::Event;
use crate::extension::telemetry::events::ReportMetrics;
use crate::extension::telemetry::events::{Status, TelemetryEvent, TelemetryRecord};
use crate::lifecycle::invocation::context::Context as InvocationContext;
use crate::logs::aggregator_service::AggregatorHandle;
use crate::logs::processor::{Processor, Rule};
use crate::tags::provider;
use crate::logs::lambda::{IntakeLog, Message};
#[allow(clippy::module_name_repetitions)]
#[derive(Clone, Debug)]
pub struct LambdaProcessor {
function_arn: String,
service: String,
tags: String,
// Global Processing Rules
rules: Option<Vec<Rule>>,
// Current Invocation Context
invocation_context: InvocationContext,
// Logs which don't have a `request_id`
orphan_logs: Vec<IntakeLog>,
// Logs which are ready to be aggregated
ready_logs: Vec<String>,
// Main event bus
event_bus: Sender<Event>,
// Logs enabled
logs_enabled: bool,
// Managed Instance mode
is_managed_instance_mode: bool,
}
const OOM_ERRORS: [&str; 7] = [
"fatal error: runtime: out of memory", // Go
"java.lang.OutOfMemoryError", // Java
"JavaScript heap out of memory", // Node
"Runtime exited with error: signal: killed", // Node
"MemoryError", // Python
"failed to allocate memory (NoMemoryError)", // Ruby
"OutOfMemoryException", // .NET
];
fn is_oom_error(error_msg: &str) -> bool {
OOM_ERRORS
.iter()
.any(|&oom_str| error_msg.contains(oom_str))
}
impl Processor<IntakeLog> for LambdaProcessor {}
impl LambdaProcessor {
#[must_use]
pub fn new(
tags_provider: Arc<provider::Provider>,
datadog_config: Arc<config::Config>,
event_bus: Sender<Event>,
is_managed_instance_mode: bool,
) -> Self {
let service = datadog_config
.service
.clone()
.unwrap_or_default()
.to_lowercase();
let tags = tags_provider.get_tags_string();
let function_arn = tags_provider.get_canonical_id().unwrap_or_default();
let processing_rules = &datadog_config.logs_config_processing_rules;
let logs_enabled = datadog_config.serverless_logs_enabled;
let rules = LambdaProcessor::compile_rules(processing_rules);
LambdaProcessor {
function_arn,
service,
tags,
rules,
logs_enabled,
invocation_context: InvocationContext::default(),
orphan_logs: Vec::new(),
ready_logs: Vec::new(),
event_bus,
is_managed_instance_mode,
}
}
#[allow(clippy::too_many_lines)]
async fn get_message(&mut self, event: TelemetryEvent) -> Result<Message, Box<dyn Error>> {
let copy = event.clone();
match event.record {
TelemetryRecord::Function(v) => {
let (request_id, message) = match v {
serde_json::Value::Object(obj) => {
let request_id = if self.is_managed_instance_mode {
obj.get("requestId")
.or_else(|| obj.get("AWSRequestId"))
.and_then(|v| v.as_str())
.map(ToString::to_string)
} else {
None
};
let msg = Some(serde_json::to_string(&obj).unwrap_or_default());
(request_id, msg)
},
serde_json::Value::String(s) => (None, Some(s)),
_ => (None, None),
};
if let Some(message) = message {
if is_oom_error(&message) {
debug!("LOGS | Got a runtime-specific OOM error. Incrementing OOM metric.");
if let Err(e) = self.event_bus.send(Event::OutOfMemory(event.time.timestamp())).await {
error!("LOGS | Failed to send OOM event to the main event bus: {e}");
}
}
return Ok(Message::new(
message,
request_id,
self.function_arn.clone(),
event.time.timestamp_millis(),
None,
));
}
Err("Unable to parse log".into())
}
TelemetryRecord::Extension(v) => {
let message = match v {
serde_json::Value::Object(obj) => Some(serde_json::to_string(&obj).unwrap_or_default()),
serde_json::Value::String(s) => Some(s),
_ => None,
};
if let Some(message) = message {
if is_oom_error(&message) {
debug!("LOGS | Got a runtime-specific OOM error. Incrementing OOM metric.");
if let Err(e) = self.event_bus.send(Event::OutOfMemory(event.time.timestamp())).await {
error!("LOGS | Failed to send OOM event to the main event bus: {e}");
}
}
return Ok(Message::new(
message,
None,
self.function_arn.clone(),
event.time.timestamp_millis(),
None,
));
}
Err("Unable to parse log".into())
}
TelemetryRecord::PlatformInitStart {
runtime_version,
runtime_version_arn,
.. // TODO: check if we could do something with this metrics: `initialization_type` and `phase`
} => {
if let Err(e) = self.event_bus.send(Event::Telemetry(copy)).await {
error!("Failed to send PlatformInitStart to the main event bus: {}", e);
}
let rv = runtime_version.unwrap_or("?".to_string()); // TODO: check what does containers display
let rv_arn = runtime_version_arn.unwrap_or("?".to_string()); // TODO: check what do containers display
Ok(Message::new(
format!("INIT_START Runtime Version: {rv} Runtime Version ARN: {rv_arn}"),
None,
self.function_arn.clone(),
event.time.timestamp_millis(),
None,
))
},
// TODO: check if we could do anything with the fields from `PlatformInitReport`
TelemetryRecord::PlatformInitReport { .. } => {
if let Err(e) = self.event_bus.send(Event::Telemetry(event)).await {
error!("Failed to send PlatformInitReport to the main event bus: {}", e);
}
// We don't need to process any log for this event
Err("Unsupported event type".into())
}
// This is the first log where `request_id` is available
// So we set it here and use it in the unprocessed and following logs.
TelemetryRecord::PlatformStart {
request_id,
version,
} => {
if let Err(e) = self.event_bus.send(Event::Telemetry(copy)).await {
error!("Failed to send PlatformStart to the main event bus: {}", e);
}
// Set request_id for unprocessed and future logs
self.invocation_context.request_id.clone_from(&request_id);
let version = version.unwrap_or("$LATEST".to_string());
Ok(Message::new(
format!("START RequestId: {request_id} Version: {version}"),
Some(request_id),
self.function_arn.clone(),
event.time.timestamp_millis(),
None,
))
},
TelemetryRecord::PlatformRuntimeDone { request_id, status, metrics, error_type, .. } => { // TODO: check what to do with rest of the fields
if let Err(e) = self.event_bus.send(Event::Telemetry(copy)).await {
error!("Failed to send PlatformRuntimeDone to the main event bus: {}", e);
}
let mut message = format!("END RequestId: {request_id}");
let mut result_status = "info".to_string();
if let Some(metrics) = metrics {
self.invocation_context.runtime_duration_ms = metrics.duration_ms;
if status == Status::Timeout {
message.push_str(&format!(" Task timed out after {:.2} seconds", metrics.duration_ms / 1000.0));
result_status = "error".to_string();
} else if status == Status::Error {
message.push_str(&format!(" Task failed: {:?}", error_type.unwrap_or_default()));
result_status = "error".to_string();
}
}
// Remove the `request_id` since no more orphan logs will be processed with this one
self.invocation_context.request_id = String::new();
Ok(Message::new(
message,
Some(request_id),
self.function_arn.clone(),
event.time.timestamp_millis(),
Some(result_status),
))
},
TelemetryRecord::PlatformReport { request_id, metrics, status, error_type, .. } => {
if let Err(e) = self.event_bus.send(Event::Telemetry(copy)).await {
error!("Failed to send PlatformReport to the main event bus: {}", e);
}
match metrics {
ReportMetrics::ManagedInstance(managed_instance_metrics) => {
let (result_status, message) = match status {
Status::Timeout => (
"error",
format!(
"REPORT RequestId: {} Runtime Duration: {:.2} ms Task timed out after {:.2} seconds",
request_id,
managed_instance_metrics.duration_ms,
managed_instance_metrics.duration_ms / 1000.0
)
),
Status::Error => {
let error_detail = error_type
.as_ref()
.map_or_else(|| " Task failed with an unknown error".to_string(), |e| format!(" Task failed: {e}"));
(
"error",
format!(
"REPORT RequestId: {} Runtime Duration: {:.2} ms{}",
request_id,
managed_instance_metrics.duration_ms,
error_detail
)
)
}
_ => (
"info",
format!(
"REPORT RequestId: {} Runtime Duration: {:.2} ms",
request_id,
managed_instance_metrics.duration_ms
)
)
};
self.invocation_context.runtime_duration_ms = managed_instance_metrics.duration_ms;
// Remove the `request_id` since no more orphan logs will be processed with this one
self.invocation_context.request_id = String::new();
Ok(Message::new(
message,
Some(request_id),
self.function_arn.clone(),
event.time.timestamp_millis(),
Some(result_status.to_string()),
))
}
ReportMetrics::OnDemand(metrics) => {
let mut post_runtime_duration_ms = 0.0;
// Calculate `post_runtime_duration_ms` if we've seen a `runtime_duration_ms`.
if self.invocation_context.runtime_duration_ms > 0.0 {
post_runtime_duration_ms = metrics.duration_ms - self.invocation_context.runtime_duration_ms;
}
let mut message = format!(
"REPORT RequestId: {} Duration: {:.2} ms Runtime Duration: {:.2} ms Post Runtime Duration: {:.2} ms Billed Duration: {:.2} ms Memory Size: {} MB Max Memory Used: {} MB",
request_id,
metrics.duration_ms,
self.invocation_context.runtime_duration_ms,
post_runtime_duration_ms,
metrics.billed_duration_ms,
metrics.memory_size_mb,
metrics.max_memory_used_mb,
);
if let Some(init_duration_ms) = metrics.init_duration_ms {
message = format!("{message} Init Duration: {init_duration_ms:.2} ms");
}
Ok(Message::new(
message,
Some(request_id),
self.function_arn.clone(),
event.time.timestamp_millis(),
None,
))
}
}
},
TelemetryRecord::PlatformRestoreStart { .. } => {
if let Err(e) = self.event_bus.send(Event::Telemetry(event)).await {
error!("Failed to send PlatformRestoreStart to the main event bus: {}", e);
}
Err("Unsupported event type".into())
}
TelemetryRecord::PlatformRestoreReport { .. } => {
if let Err(e) = self.event_bus.send(Event::Telemetry(event)).await {
error!("Failed to send PlatformRestoreReport to the main event bus: {}", e);
}
Err("Unsupported event type".into())
}
// TODO: PlatformInitRuntimeDone
// TODO: PlatformExtension
// TODO: PlatformTelemetrySubscription
// TODO: PlatformLogsDropped
_ => Err("Unsupported event type".into()),
}
}
fn get_intake_log(&mut self, mut lambda_message: Message) -> Result<IntakeLog, Box<dyn Error>> {
// Assign request_id from message or context if available
lambda_message.lambda.request_id = match lambda_message.lambda.request_id {
Some(request_id) => Some(request_id.clone()),
None => {
// If there is no request_id available in the current invocation context,
// then set to None, same goes if we are in a Managed Instance – as concurrent
// requests doesn't allow us to infer which invocation the logs belong to.
if self.invocation_context.request_id.is_empty() || self.is_managed_instance_mode {
None
} else {
Some(self.invocation_context.request_id.clone())
}
}
};
// Check if message is a JSON object that might have tags to extract
let parsed_json =
serde_json::from_str::<serde_json::Value>(lambda_message.message.as_str());
let log = if let Ok(serde_json::Value::Object(mut json_obj)) = parsed_json {
let mut tags = self.tags.clone();
let final_message = Self::extract_tags_and_get_message(
&mut json_obj,
&mut tags,
lambda_message.message.clone(),
);
IntakeLog {
hostname: self.function_arn.clone(),
source: LAMBDA_RUNTIME_SLUG.to_string(),
service: self.service.clone(),
tags,
message: Message {
message: final_message,
lambda: lambda_message.lambda,
timestamp: lambda_message.timestamp,
status: lambda_message.status,
},
}
} else {
// Not JSON or not an object - use message as-is
IntakeLog {
hostname: self.function_arn.clone(),
source: LAMBDA_RUNTIME_SLUG.to_string(),
service: self.service.clone(),
tags: self.tags.clone(),
message: lambda_message,
}
};
if log.message.lambda.request_id.is_some() || self.is_managed_instance_mode {
// In On-Demand mode, ship logs with request_id.
// In Managed Instance mode, ship logs without request_id immediately as well.
// These are inter-invocation/sandbox logs that should be aggregated without
// waiting to be attached to the next invocation.
Ok(log)
} else {
// In On-Demand mode, if no request_id is available, queue as orphan log
self.orphan_logs.push(log);
Err("No request_id available, queueing for later".into())
}
}
fn extract_tags_and_get_message(
json_obj: &mut serde_json::Map<String, serde_json::Value>,
tags: &mut String,
original_message: String,
) -> String {
// Check for top-level ddtags
if let Some(serde_json::Value::String(message_tags)) = json_obj.get("ddtags") {
tags.push(',');
tags.push_str(message_tags);
json_obj.remove("ddtags");
return serde_json::to_string(json_obj).unwrap_or(original_message);
}
// Check for nested ddtags inside a "message" field
if let Some(inner_message) = json_obj.get_mut("message") {
if let Some(serde_json::Value::String(message_tags)) = inner_message.get("ddtags") {
tags.push(',');
tags.push_str(message_tags);
if let Some(inner_obj) = inner_message.as_object_mut() {
inner_obj.remove("ddtags");
}
return inner_message.to_string();
}
}
// No ddtags found, use original message
original_message
}
async fn make_log(&mut self, event: TelemetryEvent) -> Result<IntakeLog, Box<dyn Error>> {
match self.get_message(event).await {
Ok(lambda_message) => self.get_intake_log(lambda_message),
// TODO: Check what to do when we can't process the event
Err(e) => Err(e),
}
}
/// Processes a log, applies filtering rules, serializes it, and queues it for aggregation
fn process_and_queue_log(&mut self, mut log: IntakeLog) {
let should_send_log = self.logs_enabled
&& LambdaProcessor::apply_rules(&self.rules, &mut log.message.message);
if should_send_log {
if let Ok(serialized_log) = serde_json::to_string(&log) {
// explicitly drop log so we don't accidentally re-use it and push
// duplicate logs to the aggregator
drop(log);
self.ready_logs.push(serialized_log);
}
}
}
pub async fn process(&mut self, event: TelemetryEvent, aggregator_handle: &AggregatorHandle) {
if let Ok(log) = self.make_log(event).await {
self.process_and_queue_log(log);
// Process orphan logs, since we have a `request_id` now
let orphan_logs = std::mem::take(&mut self.orphan_logs);
for mut orphan_log in orphan_logs {
orphan_log.message.lambda.request_id =
Some(self.invocation_context.request_id.clone());
self.process_and_queue_log(orphan_log);
}
}
if !self.ready_logs.is_empty() {
if let Err(e) = aggregator_handle.insert_batch(std::mem::take(&mut self.ready_logs)) {
debug!("Failed to send logs to aggregator: {}", e);
}
}
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use super::*;
use chrono::{TimeZone, Utc};
use serde_json::{Number, Value};
use std::collections::hash_map::HashMap;
use std::sync::Arc;
use crate::extension::telemetry::events::{
InitPhase, InitType, ManagedInstanceReportMetrics, OnDemandReportMetrics, ReportMetrics,
RuntimeDoneMetrics, Status,
};
use crate::logs::aggregator_service::AggregatorService;
use crate::logs::lambda::Lambda;
macro_rules! get_message_tests {
($($name:ident: $value:expr,)*) => {
$(
#[tokio::test]
async fn $name() {
let (input, expected): (&TelemetryEvent, Message) = $value;
let tags = HashMap::from([("test".to_string(), "tags".to_string())]);
let config = Arc::new(config::Config {
service: Some("test-service".to_string()),
tags: tags.clone(),
..config::Config::default()
});
let tags_provider = Arc::new(
provider::Provider::new(Arc::clone(&config),
LAMBDA_RUNTIME_SLUG.to_string(),
&HashMap::from([("function_arn".to_string(), "test-arn".to_string())])));
let (tx, _) = tokio::sync::mpsc::channel(2);
let mut processor = LambdaProcessor::new(
tags_provider,
Arc::new(config::Config {
service: Some("test-service".to_string()),
tags,
..config::Config::default()}),
tx.clone(),
false, // On-Demand mode
);
let result = processor.get_message(input.clone()).await.unwrap();
assert_eq!(result, expected);
}
)*
}
}
// get_message
get_message_tests! {
// function
function: (
&TelemetryEvent {
time: Utc.with_ymd_and_hms(2023, 1, 7, 3, 23, 47).unwrap(),
record: TelemetryRecord::Function(Value::String("test-function".to_string()))
},
Message {
message: "test-function".to_string(),
lambda: Lambda {
arn: "test-arn".to_string(),
request_id: None,
},
timestamp: 1_673_061_827_000,
status: "info".to_string(),
},
),
// extension
extension: (
&TelemetryEvent {
time: Utc.with_ymd_and_hms(2023, 1, 7, 3, 23, 47).unwrap(),
record: TelemetryRecord::Extension(Value::String("test-extension".to_string()))
},
Message {
message: "test-extension".to_string(),
lambda: Lambda {
arn: "test-arn".to_string(),
request_id: None,
},
timestamp: 1_673_061_827_000,
status: "info".to_string(),
},
),
// platform init start
platform_init_start: (
&TelemetryEvent {
time: Utc.with_ymd_and_hms(2023, 1, 7, 3, 23, 47).unwrap(),
record: TelemetryRecord::PlatformInitStart {
runtime_version: Some("test-runtime-version".to_string()),
runtime_version_arn: Some("test-runtime-version-arn".to_string()),
initialization_type: InitType::OnDemand,
phase: InitPhase::Init,
}
},
Message {
message: "INIT_START Runtime Version: test-runtime-version Runtime Version ARN: test-runtime-version-arn".to_string(),
lambda: Lambda {
arn: "test-arn".to_string(),
request_id: None,
},
timestamp: 1_673_061_827_000,
status: "info".to_string(),
},
),
// platform start
platform_start: (
&TelemetryEvent {
time: Utc.with_ymd_and_hms(2023, 1, 7, 3, 23, 47).unwrap(),
record: TelemetryRecord::PlatformStart {
request_id: "test-request-id".to_string(),
version: Some("test-version".to_string()),
}
},
Message {
message: "START RequestId: test-request-id Version: test-version".to_string(),
lambda: Lambda {
arn: "test-arn".to_string(),
request_id: Some("test-request-id".to_string()),
},
timestamp: 1_673_061_827_000,
status: "info".to_string(),
},
),
// platform runtime done
platform_runtime_done: (
&TelemetryEvent {
time: Utc.with_ymd_and_hms(2023, 1, 7, 3, 23, 47).unwrap(),
record: TelemetryRecord::PlatformRuntimeDone {
request_id: "test-request-id".to_string(),
status: Status::Success,
error_type: None,
metrics: Some(RuntimeDoneMetrics {
duration_ms: 100.0,
produced_bytes: Some(42)
})
}
},
Message {
message: "END RequestId: test-request-id".to_string(),
lambda: Lambda {
arn: "test-arn".to_string(),
request_id: Some("test-request-id".to_string()),
},
timestamp: 1_673_061_827_000,
status: "info".to_string(),
},
),
// platform runtime done
platform_runtime_done_timeout: (
&TelemetryEvent {
time: Utc.with_ymd_and_hms(2023, 1, 7, 3, 23, 47).unwrap(),
record: TelemetryRecord::PlatformRuntimeDone {
request_id: "test-request-id".to_string(),
status: Status::Timeout,
error_type: None,
metrics: Some(RuntimeDoneMetrics {
duration_ms: 5000.0,
produced_bytes: Some(42)
})
}
},
Message {
message: "END RequestId: test-request-id Task timed out after 5.00 seconds".to_string(),
lambda: Lambda {
arn: "test-arn".to_string(),
request_id: Some("test-request-id".to_string()),
},
timestamp: 1_673_061_827_000,
status: "error".to_string(),
},
),
// platform report
platform_report: (
&TelemetryEvent {
time: Utc.with_ymd_and_hms(2023, 1, 7, 3, 23, 47).unwrap(),
record: TelemetryRecord::PlatformReport {
error_type: None,
status: Status::Success,
request_id: "test-request-id".to_string(),
metrics: ReportMetrics::OnDemand(OnDemandReportMetrics {
duration_ms: 100.0,
billed_duration_ms: 128,
memory_size_mb: 256,
max_memory_used_mb: 64,
init_duration_ms: Some(50.0),
restore_duration_ms: None
}),
spans: None,
}
},
Message {
message: "REPORT RequestId: test-request-id Duration: 100.00 ms Runtime Duration: 0.00 ms Post Runtime Duration: 0.00 ms Billed Duration: 128 ms Memory Size: 256 MB Max Memory Used: 64 MB Init Duration: 50.00 ms".to_string(),
lambda: Lambda {
arn: "test-arn".to_string(),
request_id: Some("test-request-id".to_string()),
},
timestamp: 1_673_061_827_000,
status: "info".to_string(),
},
),
// platform report - Managed Instance mode success
platform_report_managed_instance_success: (
&TelemetryEvent {
time: Utc.with_ymd_and_hms(2023, 1, 7, 2, 30, 27).unwrap(),
record: TelemetryRecord::PlatformReport {
request_id: "test-request-id".to_string(),
metrics: ReportMetrics::ManagedInstance(ManagedInstanceReportMetrics {
duration_ms: 123.45,
}),
status: Status::Success,
error_type: None,
spans: None,
}
},
Message {
message: "REPORT RequestId: test-request-id Runtime Duration: 123.45 ms".to_string(),
lambda: Lambda {
arn: "test-arn".to_string(),
request_id: Some("test-request-id".to_string()),
},
timestamp: 1_673_058_627_000,
status: "info".to_string(),
},
),
// platform report - managed instance mode error with error_type
platform_report_managed_instance_error: (
&TelemetryEvent {
time: Utc.with_ymd_and_hms(2023, 1, 7, 2, 30, 27).unwrap(),
record: TelemetryRecord::PlatformReport {
request_id: "test-request-id".to_string(),
metrics: ReportMetrics::ManagedInstance(ManagedInstanceReportMetrics {
duration_ms: 200.0,
}),
status: Status::Error,
error_type: Some("RuntimeError".to_string()),
spans: None,
}
},
Message {
message: "REPORT RequestId: test-request-id Runtime Duration: 200.00 ms Task failed: RuntimeError".to_string(),
lambda: Lambda {
arn: "test-arn".to_string(),
request_id: Some("test-request-id".to_string()),
},
timestamp: 1_673_058_627_000,
status: "error".to_string(),
},
),
// platform report - managed instance mode timeout
platform_report_managed_instance_timeout: (
&TelemetryEvent {
time: Utc.with_ymd_and_hms(2023, 1, 7, 2, 30, 27).unwrap(),
record: TelemetryRecord::PlatformReport {
request_id: "test-request-id".to_string(),
metrics: ReportMetrics::ManagedInstance(ManagedInstanceReportMetrics {
duration_ms: 30000.0,
}),
status: Status::Timeout,
error_type: None,
spans: None,
}
},
Message {
message: "REPORT RequestId: test-request-id Runtime Duration: 30000.00 ms Task timed out after 30.00 seconds".to_string(),
lambda: Lambda {
arn: "test-arn".to_string(),
request_id: Some("test-request-id".to_string()),
},
timestamp: 1_673_058_627_000,
status: "error".to_string(),
},
),
// platform report - managed instance mode error without error_type
platform_report_managed_instance_error_no_type: (
&TelemetryEvent {
time: Utc.with_ymd_and_hms(2023, 1, 7, 2, 30, 27).unwrap(),
record: TelemetryRecord::PlatformReport {
request_id: "test-request-id".to_string(),
metrics: ReportMetrics::ManagedInstance(ManagedInstanceReportMetrics {
duration_ms: 150.0,
}),
status: Status::Error,
error_type: None,
spans: None,
}
},
Message {
message: "REPORT RequestId: test-request-id Runtime Duration: 150.00 ms Task failed with an unknown error".to_string(),
lambda: Lambda {
arn: "test-arn".to_string(),
request_id: Some("test-request-id".to_string()),
},
timestamp: 1_673_058_627_000,
status: "error".to_string(),
},
),
}
#[tokio::test]
async fn test_get_message_function_unsupported_value() {
let config = Arc::new(config::Config {
..config::Config::default()
});
let tags_provider = Arc::new(provider::Provider::new(
Arc::clone(&config),
LAMBDA_RUNTIME_SLUG.to_string(),
&HashMap::from([("function_arn".to_string(), "test-arn".to_string())]),
));
let (tx, _) = tokio::sync::mpsc::channel(2);
let mut processor =
LambdaProcessor::new(tags_provider, Arc::clone(&config), tx.clone(), false);
let event = TelemetryEvent {
time: Utc.with_ymd_and_hms(2023, 1, 7, 3, 23, 47).unwrap(),
record: TelemetryRecord::Function(Value::Number(Number::from(12))),
};
let result = processor.get_message(event).await;
assert!(result.is_err());
assert!(
result
.unwrap_err()
.to_string()
.contains("Unable to parse log")
);
}
// get_intake_log
#[tokio::test]
async fn test_get_intake_log() {
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 tags_provider = Arc::new(provider::Provider::new(
Arc::clone(&config),
LAMBDA_RUNTIME_SLUG.to_string(),
&HashMap::from([("function_arn".to_string(), "test-arn".to_string())]),
));
let (tx, _rx) = tokio::sync::mpsc::channel(2);
let mut processor =
LambdaProcessor::new(tags_provider, Arc::clone(&config), tx.clone(), false);
let event = TelemetryEvent {
time: Utc.with_ymd_and_hms(2023, 1, 7, 3, 23, 47).unwrap(),
record: TelemetryRecord::PlatformStart {
request_id: "test-request-id".to_string(),
version: Some("test".to_string()),
},
};
let lambda_message = processor.get_message(event.clone()).await.unwrap();
let intake_log = processor.get_intake_log(lambda_message).unwrap();
assert_eq!(intake_log.source, LAMBDA_RUNTIME_SLUG.to_string());
assert_eq!(intake_log.hostname, "test-arn".to_string());
assert_eq!(intake_log.service, "test-service".to_string());
assert!(intake_log.tags.contains("test:tags"));
assert_eq!(
intake_log.message,
Message {
message: "START RequestId: test-request-id Version: test".to_string(),
lambda: Lambda {
arn: "test-arn".to_string(),
request_id: Some("test-request-id".to_string()),
},
timestamp: 1_673_061_827_000,
status: "info".to_string(),
},
);
}
#[tokio::test]
async fn test_get_intake_log_errors_with_orphan() {
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 tags_provider = Arc::new(provider::Provider::new(
Arc::clone(&config),
LAMBDA_RUNTIME_SLUG.to_string(),
&HashMap::from([("function_arn".to_string(), "test-arn".to_string())]),
));
let (tx, _rx) = tokio::sync::mpsc::channel(2);
let mut processor =
LambdaProcessor::new(tags_provider, Arc::clone(&config), tx.clone(), false);
let event = TelemetryEvent {
time: Utc.with_ymd_and_hms(2023, 1, 7, 3, 23, 47).unwrap(),
record: TelemetryRecord::Function(Value::String("test-function".to_string())),
};
let lambda_message = processor.get_message(event.clone()).await.unwrap();
assert_eq!(lambda_message.lambda.request_id, None);
let intake_log = processor.get_intake_log(lambda_message).unwrap_err();
assert_eq!(
intake_log.to_string(),
"No request_id available, queueing for later"
);
assert_eq!(processor.orphan_logs.len(), 1);
}
#[tokio::test]
async fn test_get_intake_log_no_orphan_after_seeing_request_id() {
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 tags_provider = Arc::new(provider::Provider::new(
Arc::clone(&config),
LAMBDA_RUNTIME_SLUG.to_string(),
&HashMap::from([("function_arn".to_string(), "test-arn".to_string())]),
));
let (tx, _rx) = tokio::sync::mpsc::channel(2);
let mut processor =
LambdaProcessor::new(tags_provider, Arc::clone(&config), tx.clone(), false);
let start_event = TelemetryEvent {
time: Utc.with_ymd_and_hms(2023, 1, 7, 3, 23, 47).unwrap(),
record: TelemetryRecord::PlatformStart {
request_id: "test-request-id".to_string(),
version: Some("test".to_string()),
},
};
let start_lambda_message = processor.get_message(start_event.clone()).await.unwrap();
processor.get_intake_log(start_lambda_message).unwrap();
// This could be any event that doesn't have a `request_id`
let event = TelemetryEvent {
time: Utc.with_ymd_and_hms(2023, 1, 7, 3, 23, 47).unwrap(),
record: TelemetryRecord::Function(Value::String("test-function".to_string())),
};
let lambda_message = processor.get_message(event.clone()).await.unwrap();
let intake_log = processor.get_intake_log(lambda_message).unwrap();
assert_eq!(
intake_log.message.lambda.request_id,
Some("test-request-id".to_string())
);
}
#[tokio::test]
async fn test_get_intake_log_managed_instance_mode() {
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 tags_provider = Arc::new(provider::Provider::new(
Arc::clone(&config),
LAMBDA_RUNTIME_SLUG.to_string(),
&HashMap::from([("function_arn".to_string(), "test-arn".to_string())]),
));
let (tx, _rx) = tokio::sync::mpsc::channel(2);
// Set is_managed_instance_mode to true
let mut processor =
LambdaProcessor::new(tags_provider.clone(), Arc::clone(&config), tx.clone(), true);
let event = TelemetryEvent {
time: Utc.with_ymd_and_hms(2023, 1, 7, 3, 23, 47).unwrap(),
record: TelemetryRecord::Function(Value::String("test-function".to_string())),
};
let lambda_message = processor.get_message(event.clone()).await.unwrap();
assert_eq!(lambda_message.lambda.request_id, None);
let intake_log = processor.get_intake_log(lambda_message).unwrap();
assert_eq!(intake_log.message.lambda.request_id, None);
assert_eq!(processor.orphan_logs.len(), 0);
assert_eq!(intake_log.source, LAMBDA_RUNTIME_SLUG.to_string());
assert_eq!(intake_log.hostname, "test-arn".to_string());
assert_eq!(intake_log.service, "test-service".to_string());
assert_eq!(intake_log.message.message, "test-function".to_string());
assert_eq!(intake_log.tags, tags_provider.get_tags_string());
}
// process
#[tokio::test]
async fn test_process() {
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 tags_provider = Arc::new(provider::Provider::new(
Arc::clone(&config),
LAMBDA_RUNTIME_SLUG.to_string(),
&HashMap::from([("function_arn".to_string(), "test-arn".to_string())]),
));