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
extern crate memmap;
extern crate chrono;
extern crate time;
extern crate glob;
extern crate fancy_regex;
use std::fs::File;
use std::str;
use memmap::Mmap;
use fancy_regex::Regex;
use chrono::prelude::*;
use std::time::{SystemTime, UNIX_EPOCH};
use std::fs;
use glob::glob;
pub struct Config {
pub interval_to_check: u64,
pub search_pattern: String,
pub filename: String,
pub max_critical_matches: u64,
pub max_warning_matches: u64,
pub date_pattern: String,
pub timeposition: usize,
pub debug: bool,
pub verbose: bool,
pub re: Regex,
}
impl Config {
pub fn new(
interval_to_check: u64,
search_pattern: String,
filename: String,
max_critical_matches: u64,
max_warning_matches: u64,
mut date_pattern: String,
timeposition: usize,
debug: bool,
verbose: bool,
) -> Result<Config, String> {
if filename == "-" {
return Err("stdin as path is not supported".to_owned());
}
if date_pattern.len() == 0 {
date_pattern = String::from("%Y-%m-%d %H:%M:%S");
}
Ok(Config {
interval_to_check,
search_pattern: search_pattern.to_owned(),
filename,
max_critical_matches,
max_warning_matches,
date_pattern,
timeposition,
debug,
verbose,
re: Regex::new(&search_pattern.to_owned()).expect("regex cannot be created"),
})
}
}
pub fn run(conf: &Config) -> Result<(u64, u64), String> {
let mut files_processed = 0;
let mut exp = conf.filename.to_owned();
let star = String::from("*");
exp.push_str(&star);
let mut matches = 0;
let pattern_spaces: Vec<&str> = conf.date_pattern.split_whitespace().collect();
let whitespaces_in_date = pattern_spaces.len();
if conf.debug {
println!("looking for files matching {}", exp);
}
let now = SystemTime::now();
let oldest_ts = get_oldest_allowed_local_ts(conf, now);
if conf.debug {
let oldest_date_no_tz_offset = NaiveDateTime::from_timestamp(get_oldest_allowed_utc_ts(conf, now) as i64, 0);
let adjusted_date = NaiveDateTime::from_timestamp(get_oldest_allowed_local_ts(conf, now) as i64, 0);
println!("oldest allowed date in utc: {} and with tz offset: {}", oldest_date_no_tz_offset, adjusted_date);
}
for entry in glob(&exp).expect("failed to read glob pattern") {
match entry {
Ok(path) => {
let p = path.to_str().expect("path not available");
if !check_file_age(&conf, p) {
if conf.debug {
println!("skipping {:?} because too old", conf.filename);
}
continue;
}
let local_matches = process_file(p, &conf, whitespaces_in_date, oldest_ts);
match local_matches {
Ok(matches_in_file) => {
files_processed += 1;
matches += matches_in_file;
},
Err((err, matches_in_file)) => {
matches += matches_in_file;
continue;
}
}
},
Err(e) => eprintln!("ERROR: {:?}", e),
}
}
Ok((matches, files_processed))
}
fn get_oldest_allowed_utc_ts(conf: &Config, now: std::time::SystemTime) -> u64 {
let since_the_epoch = now.duration_since(UNIX_EPOCH).expect("Time went backwards");
let now_unix_ts = since_the_epoch.as_secs();
let go_back_secs = 60 * conf.interval_to_check;
if go_back_secs > now_unix_ts {
0
} else {
now_unix_ts - go_back_secs
}
}
fn get_oldest_allowed_local_ts(conf: &Config, now: std::time::SystemTime) -> u64 {
let oldest_ts_utc = get_oldest_allowed_utc_ts(conf, now);
let oldest_date_no_tz_offset = NaiveDateTime::from_timestamp(oldest_ts_utc as i64, 0);
let adjusted_date = adjust_to_local_tz(oldest_date_no_tz_offset);
get_timestamp_from_local(adjusted_date)
}
fn process_file(path: &str, conf: &Config, whitespaces_in_date: usize, oldest_ts: u64) -> Result<u64, (String, u64)> {
let mmap;
let mut matches = 0;
let file_in = File::open(path).expect("cannot open file");
let metadata = file_in.metadata().expect("cannot get metadata");
if !metadata.is_file() {
if conf.debug {
eprintln!("{} is not a file", path);
}
return Err(("not a file".to_owned(), 0));
} else if metadata.len() > isize::max_value() as u64 {
panic!("the file {} is too large to be safely mapped to memory:
https://github.com/danburkert/memmap-rs/issues/69", path);
} else if metadata.len() == 0 {
if conf.debug {
eprintln!("{} is empty", path);
}
return Err(("file empty".to_owned(), 0));
}
let (file, len) = {
mmap = Mmap::open_path(path, memmap::Protection::Read).expect("cannot memmap");
let bytes = unsafe { mmap.as_slice() };
(bytes, mmap.len())
};
let mut last_printed = len as i64;
let mut index = last_printed - 1;
while index >= -1 {
if index == -1 || file[index as usize] == '\n' as u8 {
let line = &file[(index + 1) as usize..last_printed as usize];
let is_match = process_line(line, whitespaces_in_date, oldest_ts, &conf);
match is_match {
Ok(v) => {
if v {
matches += 1;
}
},
Err(err) => {
if conf.debug {
eprintln!("ERROR while searching the file {}: {}
There were {} matches until the error appeared.", path, err, matches);
}
return Ok(matches);
}
}
last_printed = index + 1;
}
index -= 1;
}
Ok(matches)
}
fn process_line(bytes: &[u8], whitespaces_in_datefields: usize, oldest_ts: u64, conf: &Config) -> Result<bool, String> {
if bytes.len() == 0 {
return Ok(false);
}
let l = str::from_utf8(bytes);
if l.is_err() {
if conf.debug {
eprintln!("skipping file because not utf8 parseable!");
}
return Err("file not utf8".to_owned());
}
let line = l.unwrap().trim();
if line.len() == 0 {
return Ok(false);
}
if conf.debug {
println!("processing line: {}", line);
}
let split: Vec<&str> = line.split_whitespace().collect();
let datefields_ = split.get(conf.timeposition..(conf.timeposition + whitespaces_in_datefields));
let datefields;
match datefields_ {
None => return Ok(false),
Some(fields) => {
datefields = fields.join(" ");
}
};
let date = parse_date(&datefields, &conf.date_pattern);
match date {
None => Ok(false),
Some(date) => {
if conf.debug {
println!("parsed {} to date {}", datefields, date);
}
let ts_line = get_timestamp(date);
if oldest_ts > ts_line {
return Err("timestamp in line too old".to_owned());
}
let is_match = conf.re.captures_from_pos(&line, 0).unwrap();
let is_match = is_match.is_some();
if is_match && conf.verbose {
print!("{}", line);
}
Ok(is_match)
}
}
}
fn check_file_age(conf: &Config, path: &str) -> bool {
let secs_allowed = conf.interval_to_check * 60;
let attr = fs::metadata(&path).expect("cannot get metadata");
let last_modified = attr.modified().unwrap();
let elapsed_secs = last_modified.elapsed().unwrap().as_secs();
if conf.debug {
println!("found file {} is {} seconds old", path, elapsed_secs);
}
if elapsed_secs <= secs_allowed {
return true;
}
false
}
fn adjust_to_local_tz(date: NaiveDateTime) -> DateTime<chrono::Local> {
let dt = chrono::Local::now();
let local_offset = dt.offset();
let off = TimeZone::from_offset(local_offset);
DateTime::<chrono::Local>::from_utc(date, off)
}
fn parse_date(datefields: &str, pattern: &str) -> Option<DateTime<Utc>> {
let p = match Utc.datetime_from_str(&datefields, pattern) {
Ok(v) => v,
Err(e) => {
let err_desc = e.to_string();
if err_desc == "trailing input" {
let comma_pos = datefields.find(',').unwrap_or(datefields.len());
let (before_comma, _) = datefields.split_at(comma_pos);
return parse_date(&before_comma, pattern);
}
let mut new_pattern = String::from("%Y ");
new_pattern.push_str(&pattern);
let mut datestring = String::from("2018 ");
datestring.push_str(&datefields);
match Utc.datetime_from_str(&datestring, &new_pattern) {
Ok(v) => v,
Err(_) => {
return None;
},
}
},
};
Some(p)
}
fn get_timestamp_from_local(date: DateTime<chrono::Local>) -> u64 {
date.naive_local().timestamp() as u64
}
fn get_timestamp(date: DateTime<chrono::Utc>) -> u64 {
date.naive_local().timestamp() as u64
}
#[cfg(test)]
mod tests {
extern crate tempfile;
extern crate filetime;
use super::*;
use time as t;
use self::tempfile::NamedTempFile;
use self::filetime::FileTime;
use std::io::Write;
const EMPTY_SEARCH_PATTERN: &str = "";
const SOME_LOG_FILE: &str = "";
const CHECK_LAST_MINUTE: u64 = 1;
fn get_dummy_conf(interval_to_check: u64, search_pattern: String, logfile: String) -> Config {
get_dummy_conf_format(interval_to_check, search_pattern, logfile, "".to_owned(), 0)
}
fn get_dummy_conf_format(interval_to_check: u64, search_pattern: String, logfile: String, date_pattern: String, timeposition: usize) -> Config {
Config::new(
interval_to_check,
search_pattern,
logfile,
1,
1,
date_pattern,
timeposition,
true ,
true,
).unwrap()
}
fn create_temp_file(content: &str) -> (NamedTempFile, String) {
let mut file = NamedTempFile::new().expect("not able to create tempfile");
if content.len() > 0 {
writeln!(file, "{}", content).expect("tempfile cannot be written");
}
let path = file.path().to_str().expect("oh no").to_string();
(file, path)
}
fn get_now_secs() -> u64 {
let now = std::time::SystemTime::now();
let since_the_epoch = now.duration_since(UNIX_EPOCH).expect("Time went backwards");
since_the_epoch.as_secs()
}
fn reset_tz() {
std::env::set_var("TZ", "Africa/Abidjan");
t::tzset();
}
fn str_to_filetime(format: &str, s: &str) -> FileTime {
let mut tm = time::strptime(s, format).unwrap();
tm.tm_utcoff = time::now().tm_utcoff;
let ts = tm.to_timespec();
FileTime::from_unix_time(ts.sec as i64, ts.nsec as u32)
}
#[test]
fn should_prepend_current_year() {
let pattern = "%b %d %H:%M:%S";
let datefields = "Aug 8 11:28:21";
let date = parse_date(datefields, pattern);
let ts = date.unwrap().timestamp() as u64;
assert_eq!(ts, 1533727701);
}
#[test]
fn should_not_prepend_year_if_already_present() {
let pattern = "%Y %b %d %H:%M:%S";
let datefields = "2018 Aug 8 11:28:21";
let date = parse_date(datefields, pattern);
let ts = date.unwrap().timestamp() as u64;
assert_eq!(ts, 1533727701);
}
#[test]
fn should_correctly_calculate_oldest_allowed_ts_utc() {
let now = std::time::SystemTime::now();
let interval_to_check: u64 = 1;
let conf = get_dummy_conf(interval_to_check,
EMPTY_SEARCH_PATTERN.to_owned(),
SOME_LOG_FILE.to_owned());
let oldest_allowed_ts = get_oldest_allowed_utc_ts(&conf, now);
let since_the_epoch = now.duration_since(UNIX_EPOCH).expect("Time went backwards");
assert_eq!(oldest_allowed_ts, since_the_epoch.as_secs() - (interval_to_check * 60));
}
#[test]
fn should_correctly_calculate_oldest_allowed_ts_adjusted_to_local_tz() {
std::env::set_var("TZ", "America/Los_Angeles");
t::tzset();
let now = std::time::SystemTime::now();
let interval_to_check: u64 = 13;
let conf = get_dummy_conf(interval_to_check,
EMPTY_SEARCH_PATTERN.to_owned(),
SOME_LOG_FILE.to_owned());
let oldest_ts = get_oldest_allowed_local_ts(&conf, now);
let since_the_epoch = now.duration_since(UNIX_EPOCH).expect("Time went backwards");
let offset = 7 * 60 * 60;
assert_eq!(oldest_ts, since_the_epoch.as_secs() - (interval_to_check * 60) - offset);
}
#[test]
fn should_search_in_file() {
reset_tz();
let now_unix_ts = get_now_secs();
let format = "%b %d %H:%M:%S";
let dt = NaiveDateTime::from_timestamp(now_unix_ts as i64, 0);
let now_formatted = dt.format(format).to_string();
let five_minutes = now_unix_ts - (5 * 60);
let dt_five_minutes_ago = NaiveDateTime::from_timestamp(five_minutes as i64, 0);
let five_minutes_ago = dt_five_minutes_ago.format(format).to_string();
let content = format!("{} foo_bar\n{} bar\n{} foo-bar\n{} foo_bar",
five_minutes_ago, now_formatted, now_formatted, now_formatted);
let (_file, path) = create_temp_file(&content);
let interval_to_check: u64 = 2;
let conf = get_dummy_conf_format(interval_to_check, "foo[-_]+bar".to_owned(), path, format.to_owned(), 0);
let res = run(&conf);
let matches = 2;
let files_processed = 1;
assert_eq!(res, Ok((matches, files_processed)));
}
#[test]
fn should_handle_timeposition() {
reset_tz();
let now_unix_ts = get_now_secs();
let format = "%b %d %H:%M:%S";
let dt = NaiveDateTime::from_timestamp(now_unix_ts as i64, 0);
let now_formatted = dt.format(format).to_string();
let five_minutes = now_unix_ts - (5 * 60);
let dt_five_minutes_ago = NaiveDateTime::from_timestamp(five_minutes as i64, 0);
let five_minutes_ago = dt_five_minutes_ago.format(format).to_string();
let content = format!("foo_bar {}\nbar {}\nfoo-bar {}\nfoo_bar {}",
five_minutes_ago, now_formatted, now_formatted, now_formatted);
let (_file, path) = create_temp_file(&content);
let interval_to_check: u64 = 2;
let conf = get_dummy_conf_format(interval_to_check, "foo[-_]+bar".to_owned(), path, format.to_owned(), 1);
let res = run(&conf);
let matches = 2;
let files_processed = 1;
assert_eq!(res, Ok((matches, files_processed)));
}
#[test]
fn should_handle_empty_file_correctly() {
let (_file, path) = create_temp_file("");
let conf = get_dummy_conf(CHECK_LAST_MINUTE, EMPTY_SEARCH_PATTERN.to_owned(), path);
let res = run(&conf);
let matches = 0;
let files_processed = 0;
assert_eq!(res, Ok((matches, files_processed)));
}
#[test]
fn should_skip_binary_files() {
let path = "./fixtures/1x1.png";
let conf = get_dummy_conf(CHECK_LAST_MINUTE, EMPTY_SEARCH_PATTERN.to_owned(), path.to_owned());
let res = run(&conf);
let matches = 0;
let files_processed = 0;
assert_eq!(res, Ok((matches, files_processed)));
}
#[test]
fn should_handle_utf8_file_content_correctly() {
let (_file, path) = create_temp_file("2018-09-13 00:03:01 🐱");
let conf = get_dummy_conf(999999, "🐱".to_owned(), path);
let res = run(&conf);
let matches = 1;
let files_processed = 1;
assert_eq!(res, Ok((matches, files_processed)));
}
#[test]
fn should_handle_files_with_lines_without_dates() {
let (_file, path) = create_temp_file("2018-09-13 00:03:01 foo\nsome\nsome\nsomefoo\n2018-09-13 00:03:01 bar\n");
let conf = get_dummy_conf(999999, "bar".to_owned(), path);
let res = run(&conf);
let matches = 1;
let files_processed = 1;
assert_eq!(res, Ok((matches, files_processed)));
}
#[test]
fn should_ignore_trailing_comma() {
let format = "%Y-%m-%d %H:%M:%S";
let (_file, path) = create_temp_file("2018-09-13 00:01:51,079 foo\n2018-09-13 00:01:51,079 foobar\n");
let conf = get_dummy_conf_format(999999, "foo".to_owned(), path, format.to_owned(), 0);
let res = run(&conf);
let matches = 2;
let files_processed = 1;
assert_eq!(res, Ok((matches, files_processed)));
}
#[test]
fn should_handle_non_default_date_format() {
reset_tz();
let now_unix_ts = get_now_secs();
let format = "%b %d %H:%M:%S";
let dt = NaiveDateTime::from_timestamp(now_unix_ts as i64, 0);
let now_formatted = dt.format(format).to_string();
let five_minutes = now_unix_ts - (5 * 60);
let dt_five_minutes_ago = NaiveDateTime::from_timestamp(five_minutes as i64, 0);
let five_minutes_ago = dt_five_minutes_ago.format(format).to_string();
let content = format!("{} foo\n{} bar\n{} foobar",
five_minutes_ago, now_formatted, now_formatted);
let (_file, path) = create_temp_file(&content);
let interval_to_check: u64 = 2;
let conf = get_dummy_conf_format(interval_to_check, "foo".to_owned(), path, format.to_owned(), 0);
let res = run(&conf);
let matches = 1;
let files_processed = 1;
assert_eq!(res, Ok((matches, files_processed)));
}
#[test]
fn should_handle_non_default_date_format_and_trailing_comma_and_different_timeposition() {
reset_tz();
let now_unix_ts = get_now_secs();
let format = "%b %d %H:%M:%S";
let dt = NaiveDateTime::from_timestamp(now_unix_ts as i64, 0);
let now_formatted = dt.format(format).to_string();
let five_minutes = now_unix_ts - (5 * 60);
let dt_five_minutes_ago = NaiveDateTime::from_timestamp(five_minutes as i64, 0);
let five_minutes_ago = dt_five_minutes_ago.format(format).to_string();
let content = format!("foo {},123\nbar{},345\nfoo {},567",
five_minutes_ago, now_formatted, now_formatted);
let (_file, path) = create_temp_file(&content);
let interval_to_check: u64 = 2;
let conf = get_dummy_conf_format(interval_to_check, "foo".to_owned(), path, format.to_owned(), 1);
let res = run(&conf);
let matches = 1;
let files_processed = 1;
assert_eq!(res, Ok((matches, files_processed)));
}
#[test]
fn should_skip_old_files() {
let (file, path) = create_temp_file("2018-09-13 00:03:01 foo");
let five_minutes = 5;
let conf = get_dummy_conf(five_minutes, "foo".to_owned(), path);
let start_of_year = str_to_filetime("%Y%m%d%H%M", "201501010000");
let path = file.path();
filetime::set_file_times(path, start_of_year, start_of_year).unwrap();
let res = run(&conf);
let matches = 0;
let files_processed = 0;
assert_eq!(res, Ok((matches, files_processed)));
}
#[test]
fn should_handle_file_age_correctly() {
let (file, path) = create_temp_file("2018-09-13 00:03:01 foo");
let conf = get_dummy_conf(999999, "foo".to_owned(), path);
let start_of_year = str_to_filetime("%Y%m%d%H%M", "201809130000");
let path = file.path();
filetime::set_file_times(path, start_of_year, start_of_year).unwrap();
let res = run(&conf);
let matches = 1;
let files_processed = 1;
assert_eq!(res, Ok((matches, files_processed)));
}
#[test]
fn should_search_matching_files() {
let conf = get_dummy_conf(999999, "foobar".to_owned(), "./fixtures/logfile".to_owned());
let res = run(&conf);
let matches = 2;
let files_processed = 2;
assert_eq!(res, Ok((matches, files_processed)));
}
#[test]
fn should_abort_when_stdin_used_as_logfile() {
let stdin = "-".to_owned();
let conf = Config::new(
999999,
"foobar".to_owned(),
stdin,
1,
1,
"".to_owned(),
0,
true,
true,
);
assert_eq!(conf.is_err(), true);
}
}