-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
mod.rs
1447 lines (1195 loc) · 45.9 KB
/
mod.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 crate::{
event::{self, Event},
topology::config::{DataType, GlobalOptions, SourceConfig, SourceDescription},
trace::{current_span, Instrument},
};
use bytes::Bytes;
use file_source::{FileServer, Fingerprinter};
use futures::{future, sync::mpsc, Future, Sink, Stream};
use regex::bytes::Regex;
use serde::{Deserialize, Serialize};
use snafu::{ResultExt, Snafu};
use std::convert::{TryFrom, TryInto};
use std::path::PathBuf;
use std::thread;
use std::time::{Duration, SystemTime};
mod line_agg;
use line_agg::LineAgg;
#[derive(Debug, Snafu)]
enum BuildError {
#[snafu(display("data_dir option required, but not given here or globally"))]
NoDataDir,
#[snafu(display(
"could not create subdirectory {:?} inside of data_dir {:?}",
subdir,
data_dir
))]
MakeSubdirectoryError {
subdir: PathBuf,
data_dir: PathBuf,
source: std::io::Error,
},
#[snafu(display("data_dir {:?} does not exist", data_dir))]
MissingDataDir { data_dir: PathBuf },
#[snafu(display("data_dir {:?} is not writable", data_dir))]
DataDirNotWritable { data_dir: PathBuf },
#[snafu(display(
"message_start_indicator {:?} is not a valid regex: {}",
indicator,
source
))]
InvalidMessageStartIndicator {
indicator: String,
source: regex::Error,
},
#[snafu(display(
"unable to parse multiline start pattern from {:?}: {}",
start_pattern,
source
))]
InvalidMultilineStartPattern {
start_pattern: String,
source: regex::Error,
},
#[snafu(display(
"unable to parse multiline condition pattern from {:?}: {}",
condition_pattern,
source
))]
InvalidMultilineConditionPattern {
condition_pattern: String,
source: regex::Error,
},
}
#[derive(Deserialize, Serialize, Debug, PartialEq)]
#[serde(deny_unknown_fields, default)]
pub struct FileConfig {
pub include: Vec<PathBuf>,
pub exclude: Vec<PathBuf>,
pub file_key: Option<String>,
pub start_at_beginning: bool,
pub ignore_older: Option<u64>, // secs
#[serde(default = "default_max_line_bytes")]
pub max_line_bytes: usize,
pub host_key: Option<String>,
pub data_dir: Option<PathBuf>,
pub glob_minimum_cooldown: u64, // millis
pub fingerprinting: FingerprintingConfig,
pub message_start_indicator: Option<String>,
pub multi_line_timeout: u64, // millis
pub multiline: Option<MultilineConfig>,
pub max_read_bytes: usize,
pub oldest_first: bool,
}
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct MultilineConfig {
pub start_pattern: String,
pub condition_pattern: String,
pub mode: line_agg::Mode,
pub timeout_ms: u64,
}
impl TryFrom<&MultilineConfig> for line_agg::Config {
type Error = crate::Error;
fn try_from(config: &MultilineConfig) -> crate::Result<Self> {
let MultilineConfig {
start_pattern,
condition_pattern,
mode,
timeout_ms,
} = config;
let start_pattern = Regex::new(start_pattern)
.with_context(|| InvalidMultilineStartPattern { start_pattern })?;
let condition_pattern = Regex::new(condition_pattern)
.with_context(|| InvalidMultilineConditionPattern { condition_pattern })?;
let mode = mode.clone();
let timeout = Duration::from_millis(*timeout_ms);
Ok(Self {
start_pattern,
condition_pattern,
mode,
timeout,
})
}
}
#[derive(Deserialize, Serialize, Clone, Debug, PartialEq)]
#[serde(tag = "strategy", rename_all = "snake_case")]
pub enum FingerprintingConfig {
Checksum {
fingerprint_bytes: usize,
ignored_header_bytes: usize,
},
#[serde(rename = "device_and_inode")]
DevInode,
}
impl From<FingerprintingConfig> for Fingerprinter {
fn from(config: FingerprintingConfig) -> Fingerprinter {
match config {
FingerprintingConfig::Checksum {
fingerprint_bytes,
ignored_header_bytes,
} => Fingerprinter::Checksum {
fingerprint_bytes,
ignored_header_bytes,
},
FingerprintingConfig::DevInode => Fingerprinter::DevInode,
}
}
}
fn default_max_line_bytes() -> usize {
bytesize::kib(100u64) as usize
}
impl Default for FileConfig {
fn default() -> Self {
Self {
include: vec![],
exclude: vec![],
file_key: Some("file".to_string()),
start_at_beginning: false,
ignore_older: None,
max_line_bytes: default_max_line_bytes(),
fingerprinting: FingerprintingConfig::Checksum {
fingerprint_bytes: 256,
ignored_header_bytes: 0,
},
host_key: None,
data_dir: None,
glob_minimum_cooldown: 1000, // millis
message_start_indicator: None,
multi_line_timeout: 1000, // millis
multiline: None,
max_read_bytes: 2048,
oldest_first: false,
}
}
}
inventory::submit! {
SourceDescription::new::<FileConfig>("file")
}
#[typetag::serde(name = "file")]
impl SourceConfig for FileConfig {
fn build(
&self,
name: &str,
globals: &GlobalOptions,
out: mpsc::Sender<Event>,
) -> crate::Result<super::Source> {
// add the source name as a subdir, so that multiple sources can
// operate within the same given data_dir (e.g. the global one)
// without the file servers' checkpointers interfering with each
// other
let data_dir = globals.resolve_and_make_data_subdir(self.data_dir.as_ref(), name)?;
if let Some(ref config) = self.multiline {
let _: line_agg::Config = config.try_into()?;
}
if let Some(ref indicator) = self.message_start_indicator {
Regex::new(indicator).with_context(|| InvalidMessageStartIndicator { indicator })?;
}
Ok(file_source(self, data_dir, out))
}
fn output_type(&self) -> DataType {
DataType::Log
}
fn source_type(&self) -> &'static str {
"file"
}
}
pub fn file_source(
config: &FileConfig,
data_dir: PathBuf,
out: mpsc::Sender<Event>,
) -> super::Source {
let (shutdown_tx, shutdown_rx) = std::sync::mpsc::channel();
let ignore_before = config
.ignore_older
.map(|secs| SystemTime::now() - Duration::from_secs(secs));
let glob_minimum_cooldown = Duration::from_millis(config.glob_minimum_cooldown);
let file_server = FileServer {
include: config.include.clone(),
exclude: config.exclude.clone(),
max_read_bytes: config.max_read_bytes,
start_at_beginning: config.start_at_beginning,
ignore_before,
max_line_bytes: config.max_line_bytes,
data_dir,
glob_minimum_cooldown,
fingerprinter: config.fingerprinting.clone().into(),
oldest_first: config.oldest_first,
};
let file_key = config.file_key.clone();
let host_key = config
.host_key
.clone()
.unwrap_or(event::log_schema().host_key().to_string());
let hostname = hostname::get_hostname();
let include = config.include.clone();
let exclude = config.exclude.clone();
let multiline_config = config.multiline.clone();
let message_start_indicator = config.message_start_indicator.clone();
let multi_line_timeout = config.multi_line_timeout;
Box::new(future::lazy(move || {
info!(message = "Starting file server.", ?include, ?exclude);
// sizing here is just a guess
let (tx, rx) = futures::sync::mpsc::channel(100);
let messages: Box<dyn Stream<Item = (Bytes, String), Error = ()> + Send> =
if let Some(ref multiline_config) = multiline_config {
Box::new(LineAgg::new(
rx,
multiline_config.try_into().unwrap(), // validated in build
))
} else if let Some(msi) = message_start_indicator {
Box::new(LineAgg::new(
rx,
line_agg::Config::for_legacy(
Regex::new(&msi).unwrap(), // validated in build
multi_line_timeout,
),
))
} else {
Box::new(rx)
};
let span = current_span();
let span2 = span.clone();
tokio::spawn(
messages
.map(move |(msg, file): (Bytes, String)| {
let _enter = span2.enter();
trace!(
message = "Received one event.",
file = file.as_str(),
rate_limit_secs = 10
);
create_event(msg, file, &host_key, &hostname, &file_key)
})
.forward(out.sink_map_err(|e| error!(%e)))
.map(|_| ())
.instrument(span),
);
let span = info_span!("file_server");
thread::spawn(move || {
let _enter = span.enter();
file_server.run(tx.sink_map_err(drop), shutdown_rx);
});
// Dropping shutdown_tx is how we signal to the file server that it's time to shut down,
// so it needs to be held onto until the future we return is dropped.
future::empty().inspect(|_| drop(shutdown_tx))
}))
}
fn create_event(
line: Bytes,
file: String,
host_key: &str,
hostname: &Option<String>,
file_key: &Option<String>,
) -> Event {
let mut event = Event::from(line);
if let Some(file_key) = &file_key {
event.as_mut_log().insert(file_key.clone(), file);
}
if let Some(hostname) = &hostname {
event.as_mut_log().insert(host_key, hostname.clone());
}
event
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
event, runtime,
sources::file,
test_util::{block_on, shutdown_on_idle},
topology::Config,
};
use futures::{Future, Stream};
use pretty_assertions::assert_eq;
use std::{
collections::HashSet,
fs::{self, File},
io::{Seek, Write},
};
use stream_cancel::Tripwire;
use tempfile::tempdir;
use tokio::util::FutureExt;
fn test_default_file_config(dir: &tempfile::TempDir) -> file::FileConfig {
file::FileConfig {
fingerprinting: FingerprintingConfig::Checksum {
fingerprint_bytes: 8,
ignored_header_bytes: 0,
},
data_dir: Some(dir.path().to_path_buf()),
glob_minimum_cooldown: 0, // millis
..Default::default()
}
}
fn wait_with_timeout<F, R, E>(future: F) -> R
where
F: Send + 'static + Future<Item = R, Error = E>,
R: Send + 'static,
E: Send + 'static + std::fmt::Debug,
{
let result = block_on(future.timeout(Duration::from_secs(5)));
assert!(
result.is_ok(),
"Unclosed channel: may indicate file-server could not shutdown gracefully."
);
result.unwrap()
}
fn sleep() {
std::thread::sleep(std::time::Duration::from_millis(500));
}
#[test]
fn parse_config() {
let config: FileConfig = toml::from_str(
r#"
"#,
)
.unwrap();
assert_eq!(config, FileConfig::default());
assert_eq!(
config.fingerprinting,
FingerprintingConfig::Checksum {
fingerprint_bytes: 256,
ignored_header_bytes: 0,
}
);
let config: FileConfig = toml::from_str(
r#"
[fingerprinting]
strategy = "device_and_inode"
"#,
)
.unwrap();
assert_eq!(config.fingerprinting, FingerprintingConfig::DevInode);
let config: FileConfig = toml::from_str(
r#"
[fingerprinting]
strategy = "checksum"
fingerprint_bytes = 128
ignored_header_bytes = 512
"#,
)
.unwrap();
assert_eq!(
config.fingerprinting,
FingerprintingConfig::Checksum {
fingerprint_bytes: 128,
ignored_header_bytes: 512,
}
);
}
#[test]
fn resolve_data_dir() {
let global_dir = tempdir().unwrap();
let local_dir = tempdir().unwrap();
let mut config = Config::empty();
config.global.data_dir = global_dir.into_path().into();
// local path given -- local should win
let res = config
.global
.resolve_and_validate_data_dir(test_default_file_config(&local_dir).data_dir.as_ref())
.unwrap();
assert_eq!(res, local_dir.path());
// no local path given -- global fallback should be in effect
let res = config.global.resolve_and_validate_data_dir(None).unwrap();
assert_eq!(res, config.global.data_dir.unwrap());
}
#[test]
fn file_create_event() {
let line = Bytes::from("hello world");
let file = "some_file.rs".to_string();
let host_key = "host".to_string();
let hostname = Some("Some.Machine".to_string());
let file_key = Some("file".to_string());
let event = create_event(line, file, &host_key, &hostname, &file_key);
let log = event.into_log();
assert_eq!(log[&"file".into()], "some_file.rs".into());
assert_eq!(log[&"host".into()], "Some.Machine".into());
assert_eq!(
log[&event::log_schema().message_key()],
"hello world".into()
);
}
#[test]
fn file_happy_path() {
let n = 5;
let (tx, rx) = futures::sync::mpsc::channel(2 * n);
let (trigger, tripwire) = Tripwire::new();
let dir = tempdir().unwrap();
let config = file::FileConfig {
include: vec![dir.path().join("*")],
..test_default_file_config(&dir)
};
let source = file::file_source(&config, config.data_dir.clone().unwrap(), tx);
let mut rt = runtime::Runtime::new().unwrap();
rt.spawn(source.select(tripwire).map(|_| ()).map_err(|_| ()));
let path1 = dir.path().join("file1");
let path2 = dir.path().join("file2");
let mut file1 = File::create(&path1).unwrap();
let mut file2 = File::create(&path2).unwrap();
sleep(); // The files must be observed at their original lengths before writing to them
for i in 0..n {
writeln!(&mut file1, "hello {}", i).unwrap();
writeln!(&mut file2, "goodbye {}", i).unwrap();
}
sleep();
drop(trigger);
shutdown_on_idle(rt);
let received = wait_with_timeout(rx.collect());
let mut hello_i = 0;
let mut goodbye_i = 0;
for event in received {
let line = event.as_log()[&event::log_schema().message_key()].to_string_lossy();
if line.starts_with("hello") {
assert_eq!(line, format!("hello {}", hello_i));
assert_eq!(
event.as_log()[&"file".into()].to_string_lossy(),
path1.to_str().unwrap()
);
hello_i += 1;
} else {
assert_eq!(line, format!("goodbye {}", goodbye_i));
assert_eq!(
event.as_log()[&"file".into()].to_string_lossy(),
path2.to_str().unwrap()
);
goodbye_i += 1;
}
}
assert_eq!(hello_i, n);
assert_eq!(goodbye_i, n);
}
#[test]
fn file_truncate() {
let n = 5;
let (tx, rx) = futures::sync::mpsc::channel(2 * n);
let (trigger, tripwire) = Tripwire::new();
let dir = tempdir().unwrap();
let config = file::FileConfig {
include: vec![dir.path().join("*")],
..test_default_file_config(&dir)
};
let source = file::file_source(&config, config.data_dir.clone().unwrap(), tx);
let mut rt = runtime::Runtime::new().unwrap();
rt.spawn(source.select(tripwire).map(|_| ()).map_err(|_| ()));
let path = dir.path().join("file");
let mut file = File::create(&path).unwrap();
sleep(); // The files must be observed at its original length before writing to it
for i in 0..n {
writeln!(&mut file, "pretrunc {}", i).unwrap();
}
sleep(); // The writes must be observed before truncating
file.set_len(0).unwrap();
file.seek(std::io::SeekFrom::Start(0)).unwrap();
sleep(); // The truncate must be observed before writing again
for i in 0..n {
writeln!(&mut file, "posttrunc {}", i).unwrap();
}
sleep();
drop(trigger);
shutdown_on_idle(rt);
let received = wait_with_timeout(rx.collect());
let mut i = 0;
let mut pre_trunc = true;
for event in received {
assert_eq!(
event.as_log()[&"file".into()].to_string_lossy(),
path.to_str().unwrap()
);
let line = event.as_log()[&event::log_schema().message_key()].to_string_lossy();
if pre_trunc {
assert_eq!(line, format!("pretrunc {}", i));
} else {
assert_eq!(line, format!("posttrunc {}", i));
}
i += 1;
if i == n {
i = 0;
pre_trunc = false;
}
}
}
#[test]
fn file_rotate() {
let n = 5;
let (tx, rx) = futures::sync::mpsc::channel(2 * n);
let (trigger, tripwire) = Tripwire::new();
let dir = tempdir().unwrap();
let config = file::FileConfig {
include: vec![dir.path().join("*")],
..test_default_file_config(&dir)
};
let source = file::file_source(&config, config.data_dir.clone().unwrap(), tx);
let mut rt = runtime::Runtime::new().unwrap();
rt.spawn(source.select(tripwire).map(|_| ()).map_err(|_| ()));
let path = dir.path().join("file");
let archive_path = dir.path().join("file");
let mut file = File::create(&path).unwrap();
sleep(); // The files must be observed at its original length before writing to it
for i in 0..n {
writeln!(&mut file, "prerot {}", i).unwrap();
}
sleep(); // The writes must be observed before rotating
fs::rename(&path, archive_path).expect("could not rename");
let mut file = File::create(&path).unwrap();
sleep(); // The rotation must be observed before writing again
for i in 0..n {
writeln!(&mut file, "postrot {}", i).unwrap();
}
sleep();
drop(trigger);
shutdown_on_idle(rt);
let received = wait_with_timeout(rx.collect());
let mut i = 0;
let mut pre_rot = true;
for event in received {
assert_eq!(
event.as_log()[&"file".into()].to_string_lossy(),
path.to_str().unwrap()
);
let line = event.as_log()[&event::log_schema().message_key()].to_string_lossy();
if pre_rot {
assert_eq!(line, format!("prerot {}", i));
} else {
assert_eq!(line, format!("postrot {}", i));
}
i += 1;
if i == n {
i = 0;
pre_rot = false;
}
}
}
#[test]
fn file_multiple_paths() {
let n = 5;
let (tx, rx) = futures::sync::mpsc::channel(4 * n);
let (trigger, tripwire) = Tripwire::new();
let dir = tempdir().unwrap();
let config = file::FileConfig {
include: vec![dir.path().join("*.txt"), dir.path().join("a.*")],
exclude: vec![dir.path().join("a.*.txt")],
..test_default_file_config(&dir)
};
let source = file::file_source(&config, config.data_dir.clone().unwrap(), tx);
let mut rt = runtime::Runtime::new().unwrap();
rt.spawn(source.select(tripwire).map(|_| ()).map_err(|_| ()));
let path1 = dir.path().join("a.txt");
let path2 = dir.path().join("b.txt");
let path3 = dir.path().join("a.log");
let path4 = dir.path().join("a.ignore.txt");
let mut file1 = File::create(&path1).unwrap();
let mut file2 = File::create(&path2).unwrap();
let mut file3 = File::create(&path3).unwrap();
let mut file4 = File::create(&path4).unwrap();
sleep(); // The files must be observed at their original lengths before writing to them
for i in 0..n {
writeln!(&mut file1, "1 {}", i).unwrap();
writeln!(&mut file2, "2 {}", i).unwrap();
writeln!(&mut file3, "3 {}", i).unwrap();
writeln!(&mut file4, "4 {}", i).unwrap();
}
sleep();
drop(trigger);
shutdown_on_idle(rt);
let received = wait_with_timeout(rx.collect());
let mut is = [0; 3];
for event in received {
let line = event.as_log()[&event::log_schema().message_key()].to_string_lossy();
let mut split = line.split(" ");
let file = split.next().unwrap().parse::<usize>().unwrap();
assert_ne!(file, 4);
let i = split.next().unwrap().parse::<usize>().unwrap();
assert_eq!(is[file - 1], i);
is[file - 1] += 1;
}
assert_eq!(is, [n as usize; 3]);
}
#[test]
fn file_file_key() {
let mut rt = runtime::Runtime::new().unwrap();
let (trigger, tripwire) = Tripwire::new();
// Default
{
let (tx, rx) = futures::sync::mpsc::channel(10);
let dir = tempdir().unwrap();
let config = file::FileConfig {
include: vec![dir.path().join("*")],
..test_default_file_config(&dir)
};
let source = file::file_source(&config, config.data_dir.clone().unwrap(), tx);
rt.spawn(source.select(tripwire.clone()).map(|_| ()).map_err(|_| ()));
let path = dir.path().join("file");
let mut file = File::create(&path).unwrap();
sleep();
writeln!(&mut file, "hello there").unwrap();
sleep();
let received = wait_with_timeout(rx.into_future()).0.unwrap();
assert_eq!(
received.as_log()[&"file".into()].to_string_lossy(),
path.to_str().unwrap()
);
}
// Custom
{
let (tx, rx) = futures::sync::mpsc::channel(10);
let dir = tempdir().unwrap();
let config = file::FileConfig {
include: vec![dir.path().join("*")],
file_key: Some("source".to_string()),
..test_default_file_config(&dir)
};
let source = file::file_source(&config, config.data_dir.clone().unwrap(), tx);
rt.spawn(source.select(tripwire.clone()).map(|_| ()).map_err(|_| ()));
let path = dir.path().join("file");
let mut file = File::create(&path).unwrap();
sleep();
writeln!(&mut file, "hello there").unwrap();
sleep();
let received = wait_with_timeout(rx.into_future()).0.unwrap();
assert_eq!(
received.as_log()[&"source".into()].to_string_lossy(),
path.to_str().unwrap()
);
}
// Hidden
{
let (tx, rx) = futures::sync::mpsc::channel(10);
let dir = tempdir().unwrap();
let config = file::FileConfig {
include: vec![dir.path().join("*")],
file_key: None,
..test_default_file_config(&dir)
};
let source = file::file_source(&config, config.data_dir.clone().unwrap(), tx);
rt.spawn(source.select(tripwire.clone()).map(|_| ()).map_err(|_| ()));
let path = dir.path().join("file");
let mut file = File::create(&path).unwrap();
sleep();
writeln!(&mut file, "hello there").unwrap();
sleep();
let received = wait_with_timeout(rx.into_future()).0.unwrap();
assert_eq!(
received.as_log().keys().cloned().collect::<HashSet<_>>(),
vec![
event::log_schema().host_key().clone(),
event::log_schema().message_key().clone(),
event::log_schema().timestamp_key().clone()
]
.into_iter()
.collect::<HashSet<_>>()
);
}
drop(trigger);
shutdown_on_idle(rt);
}
#[test]
fn file_start_position_server_restart() {
let dir = tempdir().unwrap();
let config = file::FileConfig {
include: vec![dir.path().join("*")],
..test_default_file_config(&dir)
};
let path = dir.path().join("file");
let mut file = File::create(&path).unwrap();
writeln!(&mut file, "zeroth line").unwrap();
sleep();
// First time server runs it picks up existing lines.
{
let (tx, rx) = futures::sync::mpsc::channel(10);
let source = file::file_source(&config, config.data_dir.clone().unwrap(), tx);
let mut rt = runtime::Runtime::new().unwrap();
let (trigger, tripwire) = Tripwire::new();
rt.spawn(source.select(tripwire).map(|_| ()).map_err(|_| ()));
sleep();
writeln!(&mut file, "first line").unwrap();
sleep();
drop(trigger);
shutdown_on_idle(rt);
let received = wait_with_timeout(rx.collect());
let lines = received
.into_iter()
.map(|event| event.as_log()[&event::log_schema().message_key()].to_string_lossy())
.collect::<Vec<_>>();
assert_eq!(lines, vec!["zeroth line", "first line"]);
}
// Restart server, read file from checkpoint.
{
let (tx, rx) = futures::sync::mpsc::channel(10);
let source = file::file_source(&config, config.data_dir.clone().unwrap(), tx);
let mut rt = runtime::Runtime::new().unwrap();
let (trigger, tripwire) = Tripwire::new();
rt.spawn(source.select(tripwire).map(|_| ()).map_err(|_| ()));
sleep();
writeln!(&mut file, "second line").unwrap();
sleep();
drop(trigger);
shutdown_on_idle(rt);
let received = wait_with_timeout(rx.collect());
let lines = received
.into_iter()
.map(|event| event.as_log()[&event::log_schema().message_key()].to_string_lossy())
.collect::<Vec<_>>();
assert_eq!(lines, vec!["second line"]);
}
// Restart server, read files from beginning.
{
let config = file::FileConfig {
include: vec![dir.path().join("*")],
start_at_beginning: true,
..test_default_file_config(&dir)
};
let (tx, rx) = futures::sync::mpsc::channel(10);
let source = file::file_source(&config, config.data_dir.clone().unwrap(), tx);
let mut rt = runtime::Runtime::new().unwrap();
let (trigger, tripwire) = Tripwire::new();
rt.spawn(source.select(tripwire).map(|_| ()).map_err(|_| ()));
sleep();
writeln!(&mut file, "third line").unwrap();
sleep();
drop(trigger);
shutdown_on_idle(rt);
let received = wait_with_timeout(rx.collect());
let lines = received
.into_iter()
.map(|event| event.as_log()[&event::log_schema().message_key()].to_string_lossy())
.collect::<Vec<_>>();
assert_eq!(
lines,
vec!["zeroth line", "first line", "second line", "third line"]
);
}
}
#[test]
fn file_start_position_server_restart_with_file_rotation() {
let dir = tempdir().unwrap();
let config = file::FileConfig {
include: vec![dir.path().join("*")],
..test_default_file_config(&dir)
};
let path = dir.path().join("file");
let path_for_old_file = dir.path().join("file.old");
// Run server first time, collect some lines.
{
let (tx, rx) = futures::sync::mpsc::channel(10);
let source = file::file_source(&config, config.data_dir.clone().unwrap(), tx);
let mut rt = runtime::Runtime::new().unwrap();
let (trigger, tripwire) = Tripwire::new();
rt.spawn(source.select(tripwire).map(|_| ()).map_err(|_| ()));
let mut file = File::create(&path).unwrap();
sleep();
writeln!(&mut file, "first line").unwrap();
sleep();
drop(trigger);
shutdown_on_idle(rt);
let received = wait_with_timeout(rx.collect());
let lines = received
.into_iter()
.map(|event| event.as_log()[&event::log_schema().message_key()].to_string_lossy())
.collect::<Vec<_>>();
assert_eq!(lines, vec!["first line"]);
}
// Perform 'file rotation' to archive old lines.
fs::rename(&path, &path_for_old_file).expect("could not rename");
// Restart the server and make sure it does not re-read the old file
// even though it has a new name.
{
let (tx, rx) = futures::sync::mpsc::channel(10);
let source = file::file_source(&config, config.data_dir.clone().unwrap(), tx);
let mut rt = runtime::Runtime::new().unwrap();
let (trigger, tripwire) = Tripwire::new();
rt.spawn(source.select(tripwire).map(|_| ()).map_err(|_| ()));
let mut file = File::create(&path).unwrap();
sleep();
writeln!(&mut file, "second line").unwrap();
sleep();
drop(trigger);
shutdown_on_idle(rt);
let received = wait_with_timeout(rx.collect());
let lines = received
.into_iter()
.map(|event| event.as_log()[&event::log_schema().message_key()].to_string_lossy())
.collect::<Vec<_>>();
assert_eq!(lines, vec!["second line"]);
}
}
#[cfg(unix)] // this test uses unix-specific function `futimes` during test time
#[test]
fn file_start_position_ignore_old_files() {
use std::os::unix::io::AsRawFd;
use std::time::{Duration, SystemTime};
let mut rt = runtime::Runtime::new().unwrap();
let (tx, rx) = futures::sync::mpsc::channel(10);
let (trigger, tripwire) = Tripwire::new();
let dir = tempdir().unwrap();
let config = file::FileConfig {
include: vec![dir.path().join("*")],
start_at_beginning: true,
ignore_older: Some(5),
..test_default_file_config(&dir)
};
let source = file::file_source(&config, config.data_dir.clone().unwrap(), tx);
rt.spawn(source.select(tripwire).map(|_| ()).map_err(|_| ()));
let before_path = dir.path().join("before");
let mut before_file = File::create(&before_path).unwrap();
let after_path = dir.path().join("after");
let mut after_file = File::create(&after_path).unwrap();