-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
remap.rs
2049 lines (1845 loc) · 70.3 KB
/
remap.rs
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;
use std::sync::Mutex;
use std::{
collections::BTreeMap,
fs::File,
io::{self, Read},
path::PathBuf,
};
use snafu::{ResultExt, Snafu};
use vector_lib::codecs::MetricTagValues;
use vector_lib::compile_vrl;
use vector_lib::config::LogNamespace;
use vector_lib::configurable::configurable_component;
use vector_lib::enrichment::TableRegistry;
use vector_lib::lookup::{metadata_path, owned_value_path, PathPrefix};
use vector_lib::schema::Definition;
use vector_lib::TimeZone;
use vector_vrl_functions::set_semantic_meaning::MeaningList;
use vrl::compiler::runtime::{Runtime, Terminate};
use vrl::compiler::state::ExternalEnv;
use vrl::compiler::{CompileConfig, ExpressionError, Program, TypeState, VrlRuntime};
use vrl::diagnostic::{DiagnosticMessage, Formatter, Note};
use vrl::path;
use vrl::path::ValuePath;
use vrl::value::{Kind, Value};
use crate::config::OutputId;
use crate::{
config::{
log_schema, ComponentKey, DataType, Input, TransformConfig, TransformContext,
TransformOutput,
},
event::{Event, TargetEvents, VrlTarget},
internal_events::{RemapMappingAbort, RemapMappingError},
schema,
transforms::{SyncTransform, Transform, TransformOutputsBuf},
Result,
};
const DROPPED: &str = "dropped";
type CacheKey = (TableRegistry, schema::Definition);
type CacheValue = (Program, String, MeaningList);
/// Configuration for the `remap` transform.
#[configurable_component(transform(
"remap",
"Modify your observability data as it passes through your topology using Vector Remap Language (VRL)."
))]
#[derive(Derivative)]
#[serde(deny_unknown_fields)]
#[derivative(Default, Debug)]
pub struct RemapConfig {
/// The [Vector Remap Language][vrl] (VRL) program to execute for each event.
///
/// Required if `file` is missing.
///
/// [vrl]: https://vector.dev/docs/reference/vrl
#[configurable(metadata(
docs::examples = ". = parse_json!(.message)\n.new_field = \"new value\"\n.status = to_int!(.status)\n.duration = parse_duration!(.duration, \"s\")\n.new_name = del(.old_name)",
docs::syntax_override = "remap_program"
))]
pub source: Option<String>,
/// File path to the [Vector Remap Language][vrl] (VRL) program to execute for each event.
///
/// If a relative path is provided, its root is the current working directory.
///
/// Required if `source` is missing.
///
/// [vrl]: https://vector.dev/docs/reference/vrl
#[configurable(metadata(docs::examples = "./my/program.vrl"))]
pub file: Option<PathBuf>,
/// File paths to the [Vector Remap Language][vrl] (VRL) programs to execute for each event.
///
/// If a relative path is provided, its root is the current working directory.
///
/// Required if `source` or `file` are missing.
///
/// [vrl]: https://vector.dev/docs/reference/vrl
#[configurable(metadata(docs::examples = "['./my/program.vrl', './my/program2.vrl']"))]
pub files: Option<Vec<PathBuf>>,
/// When set to `single`, metric tag values are exposed as single strings, the
/// same as they were before this config option. Tags with multiple values show the last assigned value, and null values
/// are ignored.
///
/// When set to `full`, all metric tags are exposed as arrays of either string or null
/// values.
#[serde(default)]
pub metric_tag_values: MetricTagValues,
/// The name of the timezone to apply to timestamp conversions that do not contain an explicit
/// time zone.
///
/// This overrides the [global `timezone`][global_timezone] option. The time zone name may be
/// any name in the [TZ database][tz_database], or `local` to indicate system local time.
///
/// [global_timezone]: https://vector.dev/docs/reference/configuration//global-options#timezone
/// [tz_database]: https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
#[serde(default)]
#[configurable(metadata(docs::advanced))]
pub timezone: Option<TimeZone>,
/// Drops any event that encounters an error during processing.
///
/// Normally, if a VRL program encounters an error when processing an event, the original,
/// unmodified event is sent downstream. In some cases, you may not want to send the event
/// any further, such as if certain transformation or enrichment is strictly required. Setting
/// `drop_on_error` to `true` allows you to ensure these events do not get processed any
/// further.
///
/// Additionally, dropped events can potentially be diverted to a specially named output for
/// further logging and analysis by setting `reroute_dropped`.
#[serde(default = "crate::serde::default_false")]
#[configurable(metadata(docs::human_name = "Drop Event on Error"))]
pub drop_on_error: bool,
/// Drops any event that is manually aborted during processing.
///
/// If a VRL program is manually aborted (using [`abort`][vrl_docs_abort]) when
/// processing an event, this option controls whether the original, unmodified event is sent
/// downstream without any modifications or if it is dropped.
///
/// Additionally, dropped events can potentially be diverted to a specially-named output for
/// further logging and analysis by setting `reroute_dropped`.
///
/// [vrl_docs_abort]: https://vector.dev/docs/reference/vrl/expressions/#abort
#[serde(default = "crate::serde::default_true")]
#[configurable(metadata(docs::human_name = "Drop Event on Abort"))]
pub drop_on_abort: bool,
/// Reroutes dropped events to a named output instead of halting processing on them.
///
/// When using `drop_on_error` or `drop_on_abort`, events that are "dropped" are processed no
/// further. In some cases, it may be desirable to keep the events around for further analysis,
/// debugging, or retrying.
///
/// In these cases, `reroute_dropped` can be set to `true` which forwards the original event
/// to a specially-named output, `dropped`. The original event is annotated with additional
/// fields describing why the event was dropped.
#[serde(default = "crate::serde::default_false")]
#[configurable(metadata(docs::human_name = "Reroute Dropped Events"))]
pub reroute_dropped: bool,
#[configurable(derived, metadata(docs::hidden))]
#[serde(default)]
pub runtime: VrlRuntime,
#[configurable(derived, metadata(docs::hidden))]
#[serde(skip)]
#[derivative(Debug = "ignore")]
/// Cache can't be `BTreeMap` or `HashMap` because of `TableRegistry`, which doesn't allow us to inspect tables inside it.
/// And even if we allowed the inspection, the tables can be huge, resulting in a long comparison or hash computation
/// while using `Vec` allows us to use just a shallow comparison
pub cache: Mutex<Vec<(CacheKey, std::result::Result<CacheValue, String>)>>,
}
impl Clone for RemapConfig {
fn clone(&self) -> Self {
Self {
source: self.source.clone(),
file: self.file.clone(),
files: self.files.clone(),
metric_tag_values: self.metric_tag_values,
timezone: self.timezone,
drop_on_error: self.drop_on_error,
drop_on_abort: self.drop_on_abort,
reroute_dropped: self.reroute_dropped,
runtime: self.runtime,
cache: Mutex::new(Default::default()),
}
}
}
impl RemapConfig {
fn compile_vrl_program(
&self,
enrichment_tables: TableRegistry,
merged_schema_definition: schema::Definition,
) -> Result<(Program, String, MeaningList)> {
if let Some((_, res)) = self
.cache
.lock()
.expect("Data poisoned")
.iter()
.find(|v| v.0 .0 == enrichment_tables && v.0 .1 == merged_schema_definition)
{
return res.clone().map_err(Into::into);
}
let source = match (&self.source, &self.file, &self.files) {
(Some(source), None, None) => source.to_owned(),
(None, Some(path), None) => Self::read_file(path)?,
(None, None, Some(paths)) => {
let mut combined_source = String::new();
for path in paths {
let content = Self::read_file(path)?;
combined_source.push_str(&content);
combined_source.push('\n');
}
combined_source
}
_ => return Err(Box::new(BuildError::SourceAndOrFileOrFiles)),
};
let mut functions = vrl::stdlib::all();
functions.append(&mut vector_lib::enrichment::vrl_functions());
functions.append(&mut vector_vrl_functions::all());
let state = TypeState {
local: Default::default(),
external: ExternalEnv::new_with_kind(
merged_schema_definition.event_kind().clone(),
merged_schema_definition.metadata_kind().clone(),
),
};
let mut config = CompileConfig::default();
config.set_custom(enrichment_tables.clone());
config.set_custom(MeaningList::default());
let res = compile_vrl(&source, &functions, &state, config)
.map_err(|diagnostics| Formatter::new(&source, diagnostics).colored().to_string())
.map(|result| {
(
result.program,
Formatter::new(&source, result.warnings).to_string(),
result.config.get_custom::<MeaningList>().unwrap().clone(),
)
});
self.cache
.lock()
.expect("Data poisoned")
.push(((enrichment_tables, merged_schema_definition), res.clone()));
res.map_err(Into::into)
}
fn read_file(path: &PathBuf) -> Result<String> {
let mut buffer = String::new();
File::open(path)
.with_context(|_| FileOpenFailedSnafu { path })?
.read_to_string(&mut buffer)
.with_context(|_| FileReadFailedSnafu { path })?;
Ok(buffer)
}
}
impl_generate_config_from_default!(RemapConfig);
#[async_trait::async_trait]
#[typetag::serde(name = "remap")]
impl TransformConfig for RemapConfig {
async fn build(&self, context: &TransformContext) -> Result<Transform> {
let (transform, warnings) = match self.runtime {
VrlRuntime::Ast => {
let (remap, warnings) = Remap::new_ast(self.clone(), context)?;
(Transform::synchronous(remap), warnings)
}
};
// TODO: We could improve on this by adding support for non-fatal error
// messages in the topology. This would make the topology responsible
// for printing warnings (including potentially emitting metrics),
// instead of individual transforms.
if !warnings.is_empty() {
warn!(message = "VRL compilation warning.", %warnings);
}
Ok(transform)
}
fn input(&self) -> Input {
Input::all()
}
fn outputs(
&self,
enrichment_tables: vector_lib::enrichment::TableRegistry,
input_definitions: &[(OutputId, schema::Definition)],
_: LogNamespace,
) -> Vec<TransformOutput> {
let merged_definition: Definition = input_definitions
.iter()
.map(|(_output, definition)| definition.clone())
.reduce(Definition::merge)
.unwrap_or_else(Definition::any);
// We need to compile the VRL program in order to know the schema definition output of this
// transform. We ignore any compilation errors, as those are caught by the transform build
// step.
let compiled = self
.compile_vrl_program(enrichment_tables, merged_definition)
.map(|(program, _, meaning_list)| (program.final_type_info().state, meaning_list.0))
.map_err(|_| ());
let mut dropped_definitions = HashMap::new();
let mut default_definitions = HashMap::new();
for (output_id, input_definition) in input_definitions {
let default_definition = compiled
.clone()
.map(|(state, meaning)| {
let mut new_type_def = Definition::new(
state.external.target_kind().clone(),
state.external.metadata_kind().clone(),
input_definition.log_namespaces().clone(),
);
for (id, path) in input_definition.meanings() {
// Attempt to copy over the meanings from the input definition.
// The function will fail if the meaning that now points to a field that no longer exists,
// this is fine since we will no longer want that meaning in the output definition.
let _ = new_type_def.try_with_meaning(path.clone(), id);
}
// Apply any semantic meanings set in the VRL program
for (id, path) in meaning {
// currently only event paths are supported
new_type_def = new_type_def.with_meaning(path, &id);
}
new_type_def
})
.unwrap_or_else(|_| {
Definition::new_with_default_metadata(
// The program failed to compile, so it can "never" return a value
Kind::never(),
input_definition.log_namespaces().clone(),
)
});
// When a message is dropped and re-routed, we keep the original event, but also annotate
// it with additional metadata.
let dropped_definition = Definition::combine_log_namespaces(
input_definition.log_namespaces(),
input_definition.clone().with_event_field(
log_schema().metadata_key().expect("valid metadata key"),
Kind::object(BTreeMap::from([
("reason".into(), Kind::bytes()),
("message".into(), Kind::bytes()),
("component_id".into(), Kind::bytes()),
("component_type".into(), Kind::bytes()),
("component_kind".into(), Kind::bytes()),
])),
Some("metadata"),
),
input_definition
.clone()
.with_metadata_field(&owned_value_path!("reason"), Kind::bytes(), None)
.with_metadata_field(&owned_value_path!("message"), Kind::bytes(), None)
.with_metadata_field(&owned_value_path!("component_id"), Kind::bytes(), None)
.with_metadata_field(&owned_value_path!("component_type"), Kind::bytes(), None)
.with_metadata_field(&owned_value_path!("component_kind"), Kind::bytes(), None),
);
default_definitions.insert(
output_id.clone(),
VrlTarget::modify_schema_definition_for_into_events(default_definition),
);
dropped_definitions.insert(
output_id.clone(),
VrlTarget::modify_schema_definition_for_into_events(dropped_definition),
);
}
let default_output = TransformOutput::new(DataType::all_bits(), default_definitions);
if self.reroute_dropped {
vec![
default_output,
TransformOutput::new(DataType::all_bits(), dropped_definitions).with_port(DROPPED),
]
} else {
vec![default_output]
}
}
fn enable_concurrency(&self) -> bool {
true
}
}
#[derive(Debug, Clone)]
pub struct Remap<Runner>
where
Runner: VrlRunner,
{
component_key: Option<ComponentKey>,
program: Program,
timezone: TimeZone,
drop_on_error: bool,
drop_on_abort: bool,
reroute_dropped: bool,
runner: Runner,
metric_tag_values: MetricTagValues,
}
pub trait VrlRunner {
fn run(
&mut self,
target: &mut VrlTarget,
program: &Program,
timezone: &TimeZone,
) -> std::result::Result<Value, Terminate>;
}
#[derive(Debug)]
pub struct AstRunner {
pub runtime: Runtime,
}
impl Clone for AstRunner {
fn clone(&self) -> Self {
Self {
runtime: Runtime::default(),
}
}
}
impl VrlRunner for AstRunner {
fn run(
&mut self,
target: &mut VrlTarget,
program: &Program,
timezone: &TimeZone,
) -> std::result::Result<Value, Terminate> {
let result = self.runtime.resolve(target, program, timezone);
self.runtime.clear();
result
}
}
impl Remap<AstRunner> {
pub fn new_ast(
config: RemapConfig,
context: &TransformContext,
) -> crate::Result<(Self, String)> {
let (program, warnings, _) = config.compile_vrl_program(
context.enrichment_tables.clone(),
context.merged_schema_definition.clone(),
)?;
let runtime = Runtime::default();
let runner = AstRunner { runtime };
Self::new(config, context, program, runner).map(|remap| (remap, warnings))
}
}
impl<Runner> Remap<Runner>
where
Runner: VrlRunner,
{
fn new(
config: RemapConfig,
context: &TransformContext,
program: Program,
runner: Runner,
) -> crate::Result<Self> {
Ok(Remap {
component_key: context.key.clone(),
program,
timezone: config
.timezone
.unwrap_or_else(|| context.globals.timezone()),
drop_on_error: config.drop_on_error,
drop_on_abort: config.drop_on_abort,
reroute_dropped: config.reroute_dropped,
runner,
metric_tag_values: config.metric_tag_values,
})
}
#[cfg(test)]
const fn runner(&self) -> &Runner {
&self.runner
}
fn dropped_data(&self, reason: &str, error: ExpressionError) -> serde_json::Value {
let message = error
.notes()
.iter()
.filter(|note| matches!(note, Note::UserErrorMessage(_)))
.last()
.map(|note| note.to_string())
.unwrap_or_else(|| error.to_string());
serde_json::json!({
"reason": reason,
"message": message,
"component_id": self.component_key,
"component_type": "remap",
"component_kind": "transform",
})
}
fn annotate_dropped(&self, event: &mut Event, reason: &str, error: ExpressionError) {
match event {
Event::Log(ref mut log) => match log.namespace() {
LogNamespace::Legacy => {
if let Some(metadata_key) = log_schema().metadata_key() {
log.insert(
(PathPrefix::Event, metadata_key.concat(path!("dropped"))),
self.dropped_data(reason, error),
);
}
}
LogNamespace::Vector => {
log.insert(
metadata_path!("vector", "dropped"),
self.dropped_data(reason, error),
);
}
},
Event::Metric(ref mut metric) => {
if let Some(metadata_key) = log_schema().metadata_key() {
metric.replace_tag(format!("{}.dropped.reason", metadata_key), reason.into());
metric.replace_tag(
format!("{}.dropped.component_id", metadata_key),
self.component_key
.as_ref()
.map(ToString::to_string)
.unwrap_or_default(),
);
metric.replace_tag(
format!("{}.dropped.component_type", metadata_key),
"remap".into(),
);
metric.replace_tag(
format!("{}.dropped.component_kind", metadata_key),
"transform".into(),
);
}
}
Event::Trace(ref mut trace) => {
trace.maybe_insert(log_schema().metadata_key_target_path(), || {
self.dropped_data(reason, error).into()
});
}
}
}
fn run_vrl(&mut self, target: &mut VrlTarget) -> std::result::Result<Value, Terminate> {
self.runner.run(target, &self.program, &self.timezone)
}
}
impl<Runner> SyncTransform for Remap<Runner>
where
Runner: VrlRunner + Clone + Send + Sync,
{
fn transform(&mut self, event: Event, output: &mut TransformOutputsBuf) {
// If a program can fail or abort at runtime and we know that we will still need to forward
// the event in that case (either to the main output or `dropped`, depending on the
// config), we need to clone the original event and keep it around, to allow us to discard
// any mutations made to the event while the VRL program runs, before it failed or aborted.
//
// The `drop_on_{error, abort}` transform config allows operators to remove events from the
// main output if they're failed or aborted, in which case we can skip the cloning, since
// any mutations made by VRL will be ignored regardless. If they hav configured
// `reroute_dropped`, however, we still need to do the clone to ensure that we can forward
// the event to the `dropped` output.
let forward_on_error = !self.drop_on_error || self.reroute_dropped;
let forward_on_abort = !self.drop_on_abort || self.reroute_dropped;
let original_event = if (self.program.info().fallible && forward_on_error)
|| (self.program.info().abortable && forward_on_abort)
{
Some(event.clone())
} else {
None
};
let log_namespace = event
.maybe_as_log()
.map(|log| log.namespace())
.unwrap_or(LogNamespace::Legacy);
let mut target = VrlTarget::new(
event,
self.program.info(),
match self.metric_tag_values {
MetricTagValues::Single => false,
MetricTagValues::Full => true,
},
);
let result = self.run_vrl(&mut target);
match result {
Ok(_) => match target.into_events(log_namespace) {
TargetEvents::One(event) => push_default(event, output),
TargetEvents::Logs(events) => events.for_each(|event| push_default(event, output)),
TargetEvents::Traces(events) => {
events.for_each(|event| push_default(event, output))
}
},
Err(reason) => {
let (reason, error, drop) = match reason {
Terminate::Abort(error) => {
if !self.reroute_dropped {
emit!(RemapMappingAbort {
event_dropped: self.drop_on_abort,
});
}
("abort", error, self.drop_on_abort)
}
Terminate::Error(error) => {
if !self.reroute_dropped {
emit!(RemapMappingError {
error: error.to_string(),
event_dropped: self.drop_on_error,
});
}
("error", error, self.drop_on_error)
}
};
if !drop {
let event = original_event.expect("event will be set");
push_default(event, output);
} else if self.reroute_dropped {
let mut event = original_event.expect("event will be set");
self.annotate_dropped(&mut event, reason, error);
push_dropped(event, output);
}
}
}
}
}
#[inline]
fn push_default(event: Event, output: &mut TransformOutputsBuf) {
output.push(None, event)
}
#[inline]
fn push_dropped(event: Event, output: &mut TransformOutputsBuf) {
output.push(Some(DROPPED), event);
}
#[derive(Debug, Snafu)]
pub enum BuildError {
#[snafu(display("must provide exactly one of `source` or `file` or `files` configuration"))]
SourceAndOrFileOrFiles,
#[snafu(display("Could not open vrl program {:?}: {}", path, source))]
FileOpenFailed { path: PathBuf, source: io::Error },
#[snafu(display("Could not read vrl program {:?}: {}", path, source))]
FileReadFailed { path: PathBuf, source: io::Error },
}
#[cfg(test)]
mod tests {
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use indoc::{formatdoc, indoc};
use vector_lib::{config::GlobalOptions, event::EventMetadata, metric_tags};
use vrl::value::kind::Collection;
use vrl::{btreemap, event_path};
use super::*;
use crate::metrics::Controller;
use crate::{
config::{build_unit_tests, ConfigBuilder},
event::{
metric::{MetricKind, MetricValue},
LogEvent, Metric, Value,
},
schema,
test_util::components::{
assert_transform_compliance, init_test, COMPONENT_MULTIPLE_OUTPUTS_TESTS,
},
transforms::test::create_topology,
transforms::OutputBuffer,
};
use chrono::DateTime;
use tokio::sync::mpsc;
use tokio_stream::wrappers::ReceiverStream;
use vector_lib::enrichment::TableRegistry;
fn test_default_schema_definition() -> schema::Definition {
schema::Definition::empty_legacy_namespace().with_event_field(
&owned_value_path!("a default field"),
Kind::integer().or_bytes(),
Some("default"),
)
}
fn test_dropped_schema_definition() -> schema::Definition {
schema::Definition::empty_legacy_namespace().with_event_field(
&owned_value_path!("a dropped field"),
Kind::boolean().or_null(),
Some("dropped"),
)
}
fn remap(config: RemapConfig) -> Result<Remap<AstRunner>> {
let schema_definitions = HashMap::from([
(
None,
[("source".into(), test_default_schema_definition())].into(),
),
(
Some(DROPPED.to_owned()),
[("source".into(), test_dropped_schema_definition())].into(),
),
]);
Remap::new_ast(config, &TransformContext::new_test(schema_definitions))
.map(|(remap, _)| remap)
}
#[test]
fn generate_config() {
crate::test_util::test_generate_config::<RemapConfig>();
}
#[test]
fn config_missing_source_and_file() {
let config = RemapConfig {
source: None,
file: None,
..Default::default()
};
let err = remap(config).unwrap_err().to_string();
assert_eq!(
&err,
"must provide exactly one of `source` or `file` or `files` configuration"
)
}
#[test]
fn config_both_source_and_file() {
let config = RemapConfig {
source: Some("".to_owned()),
file: Some("".into()),
..Default::default()
};
let err = remap(config).unwrap_err().to_string();
assert_eq!(
&err,
"must provide exactly one of `source` or `file` or `files` configuration"
)
}
fn get_field_string(event: &Event, field: &str) -> String {
event
.as_log()
.get(field)
.unwrap()
.to_string_lossy()
.into_owned()
}
#[test]
fn check_remap_doesnt_share_state_between_events() {
let conf = RemapConfig {
source: Some(".foo = .sentinel".to_string()),
file: None,
drop_on_error: true,
drop_on_abort: false,
..Default::default()
};
let mut tform = remap(conf).unwrap();
assert!(tform.runner().runtime.is_empty());
let event1 = {
let mut event1 = LogEvent::from("event1");
event1.insert("sentinel", "bar");
Event::from(event1)
};
let result1 = transform_one(&mut tform, event1).unwrap();
assert_eq!(get_field_string(&result1, "message"), "event1");
assert_eq!(get_field_string(&result1, "foo"), "bar");
assert!(tform.runner().runtime.is_empty());
let event2 = {
let event2 = LogEvent::from("event2");
Event::from(event2)
};
let result2 = transform_one(&mut tform, event2).unwrap();
assert_eq!(get_field_string(&result2, "message"), "event2");
assert_eq!(result2.as_log().get("foo"), Some(&Value::Null));
assert!(tform.runner().runtime.is_empty());
}
#[test]
fn remap_return_raw_string_vector_namespace() {
let initial_definition = Definition::default_for_namespace(&[LogNamespace::Vector].into());
let event = {
let mut metadata = EventMetadata::default()
.with_schema_definition(&Arc::new(initial_definition.clone()));
// the Vector metadata field is required for an event to correctly detect the namespace at runtime
metadata
.value_mut()
.insert(&owned_value_path!("vector"), BTreeMap::new());
let mut event = LogEvent::new_with_metadata(metadata);
event.insert("copy_from", "buz");
Event::from(event)
};
let conf = RemapConfig {
source: Some(r#" . = "root string";"#.to_string()),
file: None,
drop_on_error: true,
drop_on_abort: false,
..Default::default()
};
let mut tform = remap(conf.clone()).unwrap();
let result = transform_one(&mut tform, event).unwrap();
assert_eq!(get_field_string(&result, "."), "root string");
let mut outputs = conf.outputs(
TableRegistry::default(),
&[(OutputId::dummy(), initial_definition)],
LogNamespace::Vector,
);
assert_eq!(outputs.len(), 1);
let output = outputs.pop().unwrap();
assert_eq!(output.port, None);
let actual_schema_def = output.schema_definitions(true)[&OutputId::dummy()].clone();
let expected_schema =
Definition::new(Kind::bytes(), Kind::any_object(), [LogNamespace::Vector]);
assert_eq!(actual_schema_def, expected_schema);
}
#[test]
fn check_remap_adds() {
let event = {
let mut event = LogEvent::from("augment me");
event.insert("copy_from", "buz");
Event::from(event)
};
let conf = RemapConfig {
source: Some(
r#" .foo = "bar"
.bar = "baz"
.copy = .copy_from
"#
.to_string(),
),
file: None,
drop_on_error: true,
drop_on_abort: false,
..Default::default()
};
let mut tform = remap(conf).unwrap();
let result = transform_one(&mut tform, event).unwrap();
assert_eq!(get_field_string(&result, "message"), "augment me");
assert_eq!(get_field_string(&result, "copy_from"), "buz");
assert_eq!(get_field_string(&result, "foo"), "bar");
assert_eq!(get_field_string(&result, "bar"), "baz");
assert_eq!(get_field_string(&result, "copy"), "buz");
}
#[test]
fn check_remap_emits_multiple() {
let event = {
let mut event = LogEvent::from("augment me");
event.insert(
"events",
vec![btreemap!("message" => "foo"), btreemap!("message" => "bar")],
);
Event::from(event)
};
let conf = RemapConfig {
source: Some(
indoc! {r#"
. = .events
"#}
.to_owned(),
),
file: None,
drop_on_error: true,
drop_on_abort: false,
..Default::default()
};
let mut tform = remap(conf).unwrap();
let out = collect_outputs(&mut tform, event);
assert_eq!(2, out.primary.len());
let mut result = out.primary.into_events();
let r = result.next().unwrap();
assert_eq!(get_field_string(&r, "message"), "foo");
let r = result.next().unwrap();
assert_eq!(get_field_string(&r, "message"), "bar");
}
#[test]
fn check_remap_error() {
let event = {
let mut event = Event::Log(LogEvent::from("augment me"));
event.as_mut_log().insert("bar", "is a string");
event
};
let conf = RemapConfig {
source: Some(formatdoc! {r#"
.foo = "foo"
.not_an_int = int!(.bar)
.baz = 12
"#}),
file: None,
drop_on_error: false,
drop_on_abort: false,
..Default::default()
};
let mut tform = remap(conf).unwrap();
let event = transform_one(&mut tform, event).unwrap();
assert_eq!(event.as_log().get("bar"), Some(&Value::from("is a string")));
assert!(event.as_log().get("foo").is_none());
assert!(event.as_log().get("baz").is_none());
}
#[test]
fn check_remap_error_drop() {
let event = {
let mut event = Event::Log(LogEvent::from("augment me"));
event.as_mut_log().insert("bar", "is a string");
event
};
let conf = RemapConfig {
source: Some(formatdoc! {r#"
.foo = "foo"
.not_an_int = int!(.bar)
.baz = 12
"#}),
file: None,
drop_on_error: true,
drop_on_abort: false,
..Default::default()
};
let mut tform = remap(conf).unwrap();
assert!(transform_one(&mut tform, event).is_none())
}
#[test]
fn check_remap_error_infallible() {
let event = {
let mut event = Event::Log(LogEvent::from("augment me"));
event.as_mut_log().insert("bar", "is a string");
event
};
let conf = RemapConfig {
source: Some(formatdoc! {r#"
.foo = "foo"
.baz = 12
"#}),
file: None,
drop_on_error: false,
drop_on_abort: false,
..Default::default()
};
let mut tform = remap(conf).unwrap();
let event = transform_one(&mut tform, event).unwrap();
assert_eq!(event.as_log().get("foo"), Some(&Value::from("foo")));
assert_eq!(event.as_log().get("bar"), Some(&Value::from("is a string")));
assert_eq!(event.as_log().get("baz"), Some(&Value::from(12)));
}
#[test]
fn check_remap_abort() {
let event = {
let mut event = Event::Log(LogEvent::from("augment me"));
event.as_mut_log().insert("bar", "is a string");
event
};
let conf = RemapConfig {
source: Some(formatdoc! {r#"
.foo = "foo"
abort
.baz = 12
"#}),
file: None,
drop_on_error: false,
drop_on_abort: false,
..Default::default()
};
let mut tform = remap(conf).unwrap();