• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

jtmoon79 / super-speedy-syslog-searcher / 20603980203

30 Dec 2025 07:10PM UTC coverage: 67.773% (-2.0%) from 69.779%
20603980203

push

github

jtmoon79
(CI) s4_* --venv

15621 of 23049 relevant lines covered (67.77%)

123479.17 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

67.09
/src/readers/syslogprocessor.rs
1
// src/readers/syslogprocessor.rs
2
// …
3

4
//! Implements a [`SyslogProcessor`], the driver of the processing stages for
5
//! a "syslog" file using a [`SyslineReader`].
6
//!
7
//! A "syslog" file in this context means any text-based file with logged
8
//! messages with a datetime stamp.
9
//! The file may use a formally defined log message format (e.g. RFC 5424)
10
//! or an ad-hoc log message format (most log files).<br/>
11
//! The two common assumptions are that:
12
//! 1. each log message has a datetime stamp on the first line
13
//! 2. log messages are in chronological order
14
//!
15
//! Sibling of [`FixedStructReader`]. But far more complicated due to the
16
//! ad-hoc nature of log files.
17
//!
18
//! This is an _s4lib_ structure used by the binary program _s4_.
19
//!
20
//! [`FixedStructReader`]: crate::readers::fixedstructreader::FixedStructReader
21
//! [`SyslineReader`]: crate::readers::syslinereader::SyslineReader
22
//! [`SyslogProcessor`]: SyslogProcessor
23

24
#![allow(non_snake_case)]
25

26
use std::fmt;
27
use std::fmt::Debug;
28
use std::io::{
29
    Error,
30
    ErrorKind,
31
    Result,
32
};
33
use std::time::Duration as StdDuration;
34

35
use ::chrono::Datelike;
36
use ::lazy_static::lazy_static;
37
use ::rangemap::RangeMap;
38
use ::si_trace_print::{
39
    def1n,
40
    def1x,
41
    def1ñ,
42
    defn,
43
    defo,
44
    defx,
45
    defñ,
46
};
47

48
use crate::common::{
49
    Count,
50
    FPath,
51
    FileOffset,
52
    FileProcessingResult,
53
    FileSz,
54
    FileType,
55
    SYSLOG_SZ_MAX,
56
};
57
use crate::data::datetime::{
58
    datetime_minus_systemtime,
59
    dt_after_or_before,
60
    systemtime_to_datetime,
61
    DateTimeL,
62
    DateTimeLOpt,
63
    Duration,
64
    FixedOffset,
65
    Result_Filter_DateTime1,
66
    SystemTime,
67
    Year,
68
    UPTIME_DEFAULT_OFFSET,
69
};
70
use crate::data::sysline::SyslineP;
71
#[cfg(test)]
72
use crate::readers::blockreader::SetDroppedBlocks;
73
use crate::readers::blockreader::{
74
    BlockIndex,
75
    BlockOffset,
76
    BlockP,
77
    BlockSz,
78
    ResultFindReadBlock,
79
};
80
#[doc(hidden)]
81
pub use crate::readers::linereader::ResultFindLine;
82
#[cfg(test)]
83
use crate::readers::linereader::SetDroppedLines;
84
use crate::readers::summary::Summary;
85
#[cfg(test)]
86
use crate::readers::syslinereader::SetDroppedSyslines;
87
#[doc(hidden)]
88
pub use crate::readers::syslinereader::{
89
    DateTimePatternCounts,
90
    ResultFindSysline,
91
    SummarySyslineReader,
92
    SyslineReader,
93
};
94
use crate::{
95
    de_err,
96
    de_wrn,
97
    e_err,
98
};
99

100
// ---------------
101
// SyslogProcessor
102

103
/// `SYSLOG_SZ_MAX` as a `BlockSz`.
104
pub(crate) const SYSLOG_SZ_MAX_BSZ: BlockSz = SYSLOG_SZ_MAX as BlockSz;
105

106
/// Typed [`FileProcessingResult`] for "block zero analysis".
107
///
108
/// [`FileProcessingResult`]: crate::common::FileProcessingResult
109
pub type FileProcessingResultBlockZero = FileProcessingResult<std::io::Error>;
110

111
/// Enum for the [`SyslogProcessor`] processing stages. Each file processed
112
/// advances through these stages. Sometimes stages may be skipped.
113
///
114
/// [`SyslogProcessor`]: self::SyslogProcessor
115
#[derive(Debug, Eq, Ord, PartialEq, PartialOrd)]
116
pub enum ProcessingStage {
117
    /// Does the file exist and is it a parseable type?
118
    Stage0ValidFileCheck,
119
    /// Check file can be parsed by trying to parse it. Determine the
120
    /// datetime patterns of any found [`Sysline`s].<br/>
121
    /// If no `Sysline`s are found then advance to `Stage4Summary`.
122
    ///
123
    /// [`Sysline`s]: crate::data::sysline::Sysline
124
    Stage1BlockzeroAnalysis,
125
    /// Find the first [`Sysline`] in the syslog file.<br/>
126
    /// If passed CLI option `--after` then find the first `Sysline` with
127
    /// datetime at or after the user-passed [`DateTimeL`].
128
    ///
129
    /// [`Sysline`]: crate::data::sysline::Sysline
130
    /// [`DateTimeL`]: crate::data::datetime::DateTimeL
131
    Stage2FindDt,
132
    /// Advanced through the syslog file to the end.<br/>
133
    /// If passed CLI option `--before` then process up to
134
    /// the last [`Sysline`] with datetime at or before the user-passed
135
    /// [`DateTimeL`]. Otherwise, process all remaining Syslines.
136
    ///
137
    /// While advancing, try to [`drop`] previously processed data `Block`s,
138
    /// `Line`s, and `Sysline`s to lessen memory allocated.
139
    /// a.k.a. "_streaming stage_".
140
    ///
141
    /// Also see function [`find_sysline`].
142
    ///
143
    /// [`Sysline`]: crate::data::sysline::Sysline
144
    /// [`DateTimeL`]: crate::data::datetime::DateTimeL
145
    /// [`find_sysline`]: self::SyslogProcessor#method.find_sysline
146
    /// [`drop`]: self::SyslogProcessor#method.drop_data_try
147
    Stage3StreamSyslines,
148
    /// If passed CLI option `--summary` then print a summary of
149
    /// various information about the processed file.
150
    Stage4Summary,
151
}
152

153
/// [`BlockSz`] in a [`Range`].
154
///
155
/// [`Range`]: std::ops::Range
156
/// [`BlockSz`]: crate::readers::blockreader::BlockSz
157
type BszRange = std::ops::Range<BlockSz>;
158

159
/// Map [`BlockSz`] to a [`Count`].
160
///
161
/// [`BlockSz`]: crate::readers::blockreader::BlockSz
162
/// [`Count`]: crate::common::Count
163
type MapBszRangeToCount = RangeMap<u64, Count>;
164

165
lazy_static! {
166
    /// For files in `blockzero_analyis`, the number of [`Line`]s needed to
167
    /// be found within block zero.
168
    ///
169
    /// [`Line`]: crate::data::line::Line
170
    pub static ref BLOCKZERO_ANALYSIS_LINE_COUNT_MIN_MAP: MapBszRangeToCount = {
171
        defñ!("lazy_static! BLOCKZERO_ANALYSIS_LINE_COUNT_MIN_MAP::new()");
172

173
        let mut m = MapBszRangeToCount::new();
174
        m.insert(BszRange{start: 0, end: SYSLOG_SZ_MAX_BSZ}, 1);
175
        m.insert(BszRange{start: SYSLOG_SZ_MAX_BSZ, end: SYSLOG_SZ_MAX_BSZ * 3}, 3);
176
        m.insert(BszRange{start: SYSLOG_SZ_MAX_BSZ * 3, end: BlockSz::MAX}, 3);
177

178
        m
179
    };
180

181
    /// For files in `blockzero_analyis`, the number of [`Sysline`]s needed to
182
    /// be found within block zero.
183
    ///
184
    /// [`Sysline`]: crate::data::sysline::Sysline
185
    pub static ref BLOCKZERO_ANALYSIS_SYSLINE_COUNT_MIN_MAP: MapBszRangeToCount = {
186
        defñ!("lazy_static! BLOCKZERO_ANALYSIS_SYSLINE_COUNT_MIN_MAP::new()");
187

188
        let mut m = MapBszRangeToCount::new();
189
        m.insert(BszRange{start: 0, end: SYSLOG_SZ_MAX_BSZ}, 1);
190
        m.insert(BszRange{start: SYSLOG_SZ_MAX_BSZ, end: BlockSz::MAX}, 2);
191

192
        m
193
    };
194
}
195

196

197
/// 25 hours.
198
/// For processing syslog files without a year.
199
/// If there is a datetime jump backwards more than this value then
200
/// a year rollover happened.
201
///
202
/// e.g. given log messages
203
///     Dec 31 23:59:59 [INFO] One!
204
///     Jan 1 00:00:00 [INFO] Happy New Year!!!
205
/// These messages interpreted as the same year would be a jump backwards
206
/// in time.
207
/// Of course, this apparent "jump backwards" means the year changed.
208
// XXX: cannot make `const` because `secs` is a private field
209
const BACKWARDS_TIME_JUMP_MEANS_NEW_YEAR: Duration = Duration::try_seconds(60 * 60 * 25).unwrap();
210

211
/// The `SyslogProcessor` uses [`SyslineReader`] to find [`Sysline`s] in a file.
212
///
213
/// A `SyslogProcessor` has knowledge of:
214
/// - the different stages of processing a syslog file
215
/// - stores optional datetime filters and searches with them
216
/// - handles special cases of a syslog file with a datetime format without a year
217
///
218
/// A `SyslogProcessor` is driven by a thread to fully process one syslog file.
219
///
220
/// During "[streaming stage]", the `SyslogProcessor` will proactively `drop`
221
/// data that has been processed and printed. It does so by calling
222
/// private function [`drop_data_try`] during function [`find_sysline`].
223
///
224
/// A `SyslogProcessor` presumes syslog messages are in chronological order.
225
///
226
/// [`Sysline`s]: crate::data::sysline::Sysline
227
/// [`SyslineReader`]: crate::readers::syslinereader::SyslineReader
228
/// [`LineReader`]: crate::readers::linereader::LineReader
229
/// [`BlockReader`]: crate::readers::blockreader::BlockReader
230
/// [`drop_data_try`]: self::SyslogProcessor#method.drop_data_try
231
/// [`find_sysline`]: self::SyslogProcessor#method.find_sysline
232
/// [streaming stage]: self::ProcessingStage#variant.Stage3StreamSyslines
233
pub struct SyslogProcessor {
234
    syslinereader: SyslineReader,
235
    /// Current `ProcessingStage`.
236
    processingstage: ProcessingStage,
237
    /// `FPath`.
238
    // TODO: remove this, use the `BlockReader` path, (DRY)
239
    path: FPath,
240
    // TODO: remove this, use the `BlockReader` blocksz, (DRY)
241
    blocksz: BlockSz,
242
    /// `FixedOffset` timezone for datetime formats without a timezone.
243
    tz_offset: FixedOffset,
244
    /// Optional filter, syslines _after_ this `DateTimeL`.
245
    filter_dt_after_opt: DateTimeLOpt,
246
    /// Optional filter, syslines _before_ this `DateTimeL`.
247
    filter_dt_before_opt: DateTimeLOpt,
248
    /// Internal sanity check, has `self.blockzero_analysis()` completed?
249
    blockzero_analysis_done: bool,
250
    /// Internal tracking of last `blockoffset` passed to `drop_block`.
251
    drop_block_last: BlockOffset,
252
    /// Optional `Year` value used to start `process_missing_year()`.
253
    /// Only needed for syslog files with datetime format without a year.
254
    missing_year: Option<Year>,
255
    /// The last [`Error`], if any, as a `String`. Set by [`set_error`].
256
    ///
257
    /// Annoyingly, cannot [Clone or Copy `Error`].
258
    ///
259
    /// [`Error`]: std::io::Error
260
    /// [Clone or Copy `Error`]: https://github.com/rust-lang/rust/issues/24135
261
    /// [`set_error`]: self::SyslogProcessor#method.set_error
262
    // TRACKING: https://github.com/rust-lang/rust/issues/24135
263
    error: Option<String>,
264
}
265

266
impl Debug for SyslogProcessor {
267
    fn fmt(
300✔
268
        &self,
300✔
269
        f: &mut fmt::Formatter,
300✔
270
    ) -> fmt::Result {
300✔
271
        f.debug_struct("SyslogProcessor")
300✔
272
            .field("Path", &self.path)
300✔
273
            .field("Processing Stage", &self.processingstage)
300✔
274
            .field("BlockSz", &self.blocksz)
300✔
275
            .field("TimeOffset", &self.tz_offset)
300✔
276
            .field("filter_dt_after_opt", &self.filter_dt_after_opt)
300✔
277
            .field("filter_dt_before_opt", &self.filter_dt_before_opt)
300✔
278
            .field("BO Analysis done?", &self.blockzero_analysis_done)
300✔
279
            .field("filetype", &self.filetype())
300✔
280
            .field("Reprocessed missing year?", &self.did_process_missing_year())
300✔
281
            .field("Missing Year", &self.missing_year)
300✔
282
            .field("Error?", &self.error)
300✔
283
            .finish()
300✔
284
    }
300✔
285
}
286

287
// TODO: [2023/04] remove redundant variable prefix name `syslogprocessor_`
288
#[derive(Clone, Debug, Default, Eq, PartialEq)]
289
pub struct SummarySyslogProcessor {
290
    /// `SyslogProcessor::missing_year`
291
    pub syslogprocessor_missing_year: Option<Year>,
292
}
293

294
impl SyslogProcessor {
295
    /// `SyslogProcessor` has it's own miminum requirements for `BlockSz`.
296
    ///
297
    /// Necessary for `blockzero_analysis` functions to have chance at success.
298
    #[doc(hidden)]
299
    #[cfg(any(debug_assertions, test))]
300
    pub const BLOCKSZ_MIN: BlockSz = 0x2;
301

302
    /// Maximum number of datetime patterns for matching the remainder of a
303
    /// syslog file.
304
    const DT_PATTERN_MAX: usize = SyslineReader::DT_PATTERN_MAX;
305

306
    /// `SyslogProcessor` has it's own miminum requirements for `BlockSz`.
307
    ///
308
    /// Necessary for `blockzero_analysis` functions to have chance at success.
309
    #[cfg(not(any(debug_assertions, test)))]
310
    pub const BLOCKSZ_MIN: BlockSz = 0x40;
311

312
    /// Minimum number of bytes needed to perform `blockzero_analysis_bytes`.
313
    ///
314
    /// Pretty sure this is smaller than the smallest possible timestamp that
315
    /// can be processed by the `DTPD!` in `DATETIME_PARSE_DATAS`.
316
    /// In other words, a file that only has a datetimestamp followed by an
317
    /// empty log message.
318
    ///
319
    /// It's okay if this is too small as the later processing stages will
320
    /// be certain of any possible datetime patterns.
321
    pub const BLOCKZERO_ANALYSIS_BYTES_MIN: BlockSz = 6;
322

323
    /// If the first number of bytes are zero bytes (NULL bytes) then
324
    /// stop processing the file. It's extremely unlikely this is a syslog
325
    /// file and more likely it's some sort of binary data file.
326
    pub const BLOCKZERO_ANALYSIS_BYTES_NULL_MAX: usize = 128;
327

328
    /// Allow "streaming stage" to drop data?
329
    /// Compile-time "option" to aid manual debugging.
330
    #[doc(hidden)]
331
    const STREAM_STAGE_DROP: bool = true;
332

333
    /// Use LRU caches in underlying components?
334
    ///
335
    /// XXX: For development and testing experiments!
336
    #[doc(hidden)]
337
    const LRU_CACHE_ENABLE: bool = true;
338

339
    /// Create a new `SyslogProcessor`.
340
    ///
341
    /// **NOTE:** should not attempt any block reads here,
342
    /// similar to other `*Readers::new()`
343
    pub fn new(
398✔
344
        path: FPath,
398✔
345
        filetype: FileType,
398✔
346
        blocksz: BlockSz,
398✔
347
        tz_offset: FixedOffset,
398✔
348
        filter_dt_after_opt: DateTimeLOpt,
398✔
349
        filter_dt_before_opt: DateTimeLOpt,
398✔
350
    ) -> Result<SyslogProcessor> {
398✔
351
        def1n!("({:?}, {:?}, {:?}, {:?})", path, filetype, blocksz, tz_offset);
398✔
352
        if blocksz < SyslogProcessor::BLOCKSZ_MIN {
398✔
353
            return Result::Err(Error::new(
×
354
                ErrorKind::InvalidInput,
×
355
                format!(
×
356
                    "BlockSz {0} (0x{0:08X}) is too small, SyslogProcessor has BlockSz minimum {1} (0x{1:08X}) file {2:?}",
×
357
                    blocksz,
×
358
                    SyslogProcessor::BLOCKSZ_MIN,
×
359
                    &path,
×
360
                ),
×
361
            ));
×
362
        }
398✔
363
        let path_ = path.clone();
398✔
364
        let mut slr = match SyslineReader::new(path, filetype, blocksz, tz_offset) {
398✔
365
            Ok(val) => val,
396✔
366
            Err(err) => {
2✔
367
                def1x!();
2✔
368
                return Result::Err(err);
2✔
369
            }
370
        };
371

372
        if !SyslogProcessor::LRU_CACHE_ENABLE {
396✔
373
            slr.LRU_cache_disable();
×
374
            slr.linereader
×
375
                .LRU_cache_disable();
×
376
            slr.linereader
×
377
                .blockreader
×
378
                .LRU_cache_disable();
×
379
        }
396✔
380

381
        def1x!("return Ok(SyslogProcessor)");
396✔
382

383
        Result::Ok(SyslogProcessor {
396✔
384
            syslinereader: slr,
396✔
385
            processingstage: ProcessingStage::Stage0ValidFileCheck,
396✔
386
            path: path_,
396✔
387
            blocksz,
396✔
388
            tz_offset,
396✔
389
            filter_dt_after_opt,
396✔
390
            filter_dt_before_opt,
396✔
391
            blockzero_analysis_done: false,
396✔
392
            drop_block_last: 0,
396✔
393
            missing_year: None,
396✔
394
            error: None,
396✔
395
        })
396✔
396
    }
398✔
397

398
    /// `Count` of [`Line`s] processed.
399
    ///
400
    /// [`Line`s]: crate::data::line::Line
401
    #[inline(always)]
402
    #[allow(dead_code)]
403
    pub fn count_lines(&self) -> Count {
×
404
        self.syslinereader
×
405
            .linereader
×
406
            .count_lines_processed()
×
407
    }
×
408

409
    /// See [`Sysline::count_syslines_stored`].
410
    ///
411
    /// [`Sysline::count_syslines_stored`]: crate::data::sysline::Sysline::count_syslines_stored
412
    #[cfg(test)]
413
    pub fn count_syslines_stored(&self) -> Count {
4✔
414
        self.syslinereader.count_syslines_stored()
4✔
415
    }
4✔
416

417
    /// See [`BlockReader::blocksz`].
418
    ///
419
    /// [`BlockReader::blocksz`]: crate::readers::blockreader::BlockReader#method.blocksz
420
    #[inline(always)]
421
    pub const fn blocksz(&self) -> BlockSz {
377✔
422
        self.syslinereader.blocksz()
377✔
423
    }
377✔
424

425
    /// See [`BlockReader::filesz`].
426
    ///
427
    /// [`BlockReader::filesz`]: crate::readers::blockreader::BlockReader#method.filesz
428
    #[inline(always)]
429
    pub const fn filesz(&self) -> FileSz {
380✔
430
        self.syslinereader.filesz()
380✔
431
    }
380✔
432

433
    /// See [`BlockReader::filetype`].
434
    ///
435
    /// [`BlockReader::filetype`]: crate::readers::blockreader::BlockReader#method.filetype
436
    #[inline(always)]
437
    pub const fn filetype(&self) -> FileType {
834✔
438
        self.syslinereader.filetype()
834✔
439
    }
834✔
440

441
    /// See [`BlockReader::path`].
442
    ///
443
    /// [`BlockReader::path`]: crate::readers::blockreader::BlockReader#method.path
444
    #[inline(always)]
445
    #[allow(dead_code)]
446
    pub const fn path(&self) -> &FPath {
534✔
447
        self.syslinereader.path()
534✔
448
    }
534✔
449

450
    /// See [`BlockReader::block_offset_at_file_offset`].
451
    ///
452
    /// [`BlockReader::block_offset_at_file_offset`]: crate::readers::blockreader::BlockReader#method.block_offset_at_file_offset
453
    #[allow(dead_code)]
454
    pub const fn block_offset_at_file_offset(
×
455
        &self,
×
456
        fileoffset: FileOffset,
×
457
    ) -> BlockOffset {
×
458
        self.syslinereader
×
459
            .block_offset_at_file_offset(fileoffset)
×
460
    }
×
461

462
    /// See [`BlockReader::file_offset_at_block_offset`].
463
    ///
464
    /// [`BlockReader::file_offset_at_block_offset`]: crate::readers::blockreader::BlockReader#method.file_offset_at_block_offset
465
    #[allow(dead_code)]
466
    pub const fn file_offset_at_block_offset(
×
467
        &self,
×
468
        blockoffset: BlockOffset,
×
469
    ) -> FileOffset {
×
470
        self.syslinereader
×
471
            .file_offset_at_block_offset(blockoffset)
×
472
    }
×
473

474
    /// See [`BlockReader::file_offset_at_block_offset_index`].
475
    ///
476
    /// [`BlockReader::file_offset_at_block_offset_index`]: crate::readers::blockreader::BlockReader#method.file_offset_at_block_offset_index
477
    #[allow(dead_code)]
478
    pub const fn file_offset_at_block_offset_index(
×
479
        &self,
×
480
        blockoffset: BlockOffset,
×
481
        blockindex: BlockIndex,
×
482
    ) -> FileOffset {
×
483
        self.syslinereader
×
484
            .file_offset_at_block_offset_index(blockoffset, blockindex)
×
485
    }
×
486

487
    /// See [`BlockReader::block_index_at_file_offset`].
488
    ///
489
    /// [`BlockReader::block_index_at_file_offset`]: crate::readers::blockreader::BlockReader#method.block_index_at_file_offset
490
    #[allow(dead_code)]
491
    pub const fn block_index_at_file_offset(
×
492
        &self,
×
493
        fileoffset: FileOffset,
×
494
    ) -> BlockIndex {
×
495
        self.syslinereader
×
496
            .block_index_at_file_offset(fileoffset)
×
497
    }
×
498

499
    /// See [`BlockReader::count_blocks`].
500
    ///
501
    /// [`BlockReader::count_blocks`]: crate::readers::blockreader::BlockReader#method.count_blocks
502
    #[allow(dead_code)]
503
    pub const fn count_blocks(&self) -> Count {
×
504
        self.syslinereader
×
505
            .count_blocks()
×
506
    }
×
507

508
    /// See [`BlockReader::blockoffset_last`].
509
    ///
510
    /// [`BlockReader::blockoffset_last`]: crate::readers::blockreader::BlockReader#method.blockoffset_last
511
    #[allow(dead_code)]
512
    pub const fn blockoffset_last(&self) -> BlockOffset {
×
513
        self.syslinereader
×
514
            .blockoffset_last()
×
515
    }
×
516

517
    /// See [`BlockReader::fileoffset_last`].
518
    ///
519
    /// [`BlockReader::fileoffset_last`]: crate::readers::blockreader::BlockReader#method.fileoffset_last
520
    pub const fn fileoffset_last(&self) -> FileOffset {
25✔
521
        self.syslinereader
25✔
522
            .fileoffset_last()
25✔
523
    }
25✔
524

525
    /// See [`LineReader::charsz`].
526
    ///
527
    /// [`LineReader::charsz`]: crate::readers::linereader::LineReader#method.charsz
528
    #[allow(dead_code)]
529
    pub const fn charsz(&self) -> usize {
25✔
530
        self.syslinereader.charsz()
25✔
531
    }
25✔
532

533
    /// See [`BlockReader::mtime`].
534
    ///
535
    /// [`BlockReader::mtime`]: crate::readers::blockreader::BlockReader#method.mtime
536
    pub fn mtime(&self) -> SystemTime {
324✔
537
        self.syslinereader.mtime()
324✔
538
    }
324✔
539

540
    /// Did this `SyslogProcessor` run `process_missing_year()` ?
541
    fn did_process_missing_year(&self) -> bool {
325✔
542
        self.missing_year.is_some()
325✔
543
    }
325✔
544

545
    /// Did this `SyslogProcessor` run `process_uptime()` ?
546
    fn did_process_uptime(&self) -> bool {
×
547
        self.systemtime_at_uptime_zero().is_some()
×
548
    }
×
549

550
    /// Return `drop_data` value.
551
    pub const fn is_drop_data(&self) -> bool {
3,678✔
552
        self.syslinereader.is_drop_data()
3,678✔
553
    }
3,678✔
554

555
    /// store an `Error` that occurred. For later printing during `--summary`.
556
    // XXX: duplicates `FixedStructReader.set_error`
557
    fn set_error(
×
558
        &mut self,
×
559
        error: &Error,
×
560
    ) {
×
561
        def1ñ!("{:?}", error);
×
562
        let mut error_string: String = error.kind().to_string();
×
563
        error_string.push_str(": ");
×
564
        error_string.push_str(error.kind().to_string().as_str());
×
565
        // print the error but avoid printing the same error more than once
566
        // XXX: This is somewhat a hack as it's possible the same error, with the
567
        //      the same error message, could occur more than once.
568
        //      Considered another way, this function `set_error` may get called
569
        //      too often. The responsibility for calling `set_error` is haphazard.
570
        match &self.error {
×
571
            Some(err_s) => {
×
572
                if err_s != &error_string {
×
573
                    e_err!("{}", error);
×
574
                }
×
575
            }
576
            None => {
×
577
                e_err!("{}", error);
×
578
            }
×
579
        }
580
        if let Some(ref _err) = self.error {
×
581
            de_wrn!("skip overwrite of previous Error {:?} with Error ({:?})", _err, error);
×
582
            return;
×
583
        }
×
584
        self.error = Some(error_string);
×
585
    }
×
586

587
    /// Syslog files wherein the datetime format that does not include a year
588
    /// must have special handling.
589
    ///
590
    /// The last [`Sysline`] in the file is presumed to share the same year as
591
    /// the `mtime` (stored by the underlying [`BlockReader`] instance).
592
    /// The entire file is read from end to beginning (in reverse) (unless
593
    /// a `filter_dt_after_opt` is passed that coincides with the found
594
    /// syslines). The year is tracked and updated for each sysline.
595
    /// If there is jump backwards in time, that is presumed to be a
596
    /// year changeover.
597
    ///
598
    /// For example, given syslog contents
599
    ///
600
    /// ```text
601
    /// Nov 1 12:00:00 hello
602
    /// Dec 1 12:00:00 good morning
603
    /// Jan 1 12:00:00 goodbye
604
    /// ```
605
    ///
606
    /// and file `mtime` that is datetime _January 1 12:00:00 2015_,
607
    /// then the last `Sysline` "Jan 1 12:00:00 goodbye" is presumed to be in
608
    /// year 2015.
609
    /// The preceding `Sysline` "Dec 1 12:00:00 goodbye" is then processed.
610
    /// An apparent backwards jump is seen _Jan 1_ to _Dec 1_.
611
    /// From this, it can be concluded the _Dec 1_ refers to a prior year, 2014.
612
    ///
613
    /// Typically, when a datetime filter is passed, a special binary search is
614
    /// done to find the desired syslog line, reducing resource usage. Whereas,
615
    /// files processed here must be read linearly and in their entirety
616
    /// Or, if `filter_dt_after_opt` is passed then the file is read to the
617
    /// first `sysline.dt()` (datetime) that is
618
    /// `Result_Filter_DateTime1::OccursBefore` the
619
    /// `filter_dt_after_opt`.
620
    ///
621
    /// [`Sysline`]: crate::data::sysline::Sysline
622
    /// [`BlockReader`]: crate::readers::blockreader::BlockReader
623
    /// [`DateTimeL`]: crate::data::datetime::DateTimeL
624
    // BUG: does not revise year guesstimation based on encountering leap date February 29
625
    //      See Issue #245
626
    pub fn process_missing_year(
25✔
627
        &mut self,
25✔
628
        mtime: SystemTime,
25✔
629
        filter_dt_after_opt: &DateTimeLOpt,
25✔
630
    ) -> FileProcessingResultBlockZero {
25✔
631
        defn!("({:?}, {:?})", mtime, filter_dt_after_opt);
25✔
632
        debug_assert!(!self.did_process_missing_year(), "process_missing_year() must only be called once");
25✔
633
        let dt_mtime: DateTimeL = systemtime_to_datetime(&self.tz_offset, &mtime);
25✔
634
        defo!("converted dt_mtime {:?}", dt_mtime);
25✔
635
        let year: Year = dt_mtime.date_naive().year() as Year;
25✔
636
        self.missing_year = Some(year);
25✔
637
        defo!("converted missing_year {:?}", self.missing_year);
25✔
638
        let mut year_opt: Option<Year> = Some(year);
25✔
639
        defo!("year_opt {:?}", year_opt);
25✔
640
        let charsz_fo: FileOffset = self.charsz() as FileOffset;
25✔
641

642
        // The previously stored `Sysline`s have a filler year that is most likely
643
        // incorrect. The underlying `Sysline` instance cannot be updated behind
644
        // an `Arc`. Those syslines must be dropped and the entire file
645
        // processed again. However, underlying `Line` and `Block` are still
646
        // valid; do not reprocess those.
647
        self.syslinereader
25✔
648
            .clear_syslines();
25✔
649

650
        // read all syslines in reverse
651
        let mut fo_prev: FileOffset = self.fileoffset_last();
25✔
652
        let mut syslinep_prev_opt: Option<SyslineP> = None;
25✔
653
        loop {
654
            let syslinep: SyslineP = match self
826✔
655
                .syslinereader
826✔
656
                .find_sysline_year(fo_prev, &year_opt)
826✔
657
            {
658
                ResultFindSysline::Found((_fo, syslinep)) => {
826✔
659
                    defo!(
826✔
660
                        "Found {} Sysline @[{}, {}] datetime: {:?})",
826✔
661
                        _fo,
662
                        (*syslinep).fileoffset_begin(),
826✔
663
                        (*syslinep).fileoffset_end(),
826✔
664
                        (*syslinep).dt()
826✔
665
                    );
666
                    syslinep
826✔
667
                }
668
                ResultFindSysline::Done => {
×
669
                    defo!("Done, break;");
×
670
                    break;
×
671
                }
672
                ResultFindSysline::Err(err) => {
×
673
                    self.set_error(&err);
×
674
                    defx!("return FileErrIo({:?})", err);
×
675
                    return FileProcessingResultBlockZero::FileErrIoPath(err);
×
676
                }
677
            };
678
            // TODO: [2022/07/27] add fn `syslinereader.find_sysline_year_rev` to hide these char offset
679
            //       details (put them into a struct that is meant to understand these details)
680
            let fo_prev_prev: FileOffset = fo_prev;
826✔
681
            fo_prev = (*syslinep).fileoffset_begin();
826✔
682
            // check if datetime has suddenly jumped backwards.
683
            // if date has jumped backwards, then remove sysline, update the year, and
684
            // process the file from that fileoffset again
685
            if let Some(syslinep_prev) = syslinep_prev_opt {
826✔
686
                // normally `dt_cur` should have a datetime *before or equal* to `dt_prev`
687
                // but if not, then there was probably a year rollover
688
                if (*syslinep).dt() > (*syslinep_prev).dt() {
801✔
689
                    let diff: Duration = *(*syslinep).dt() - *(*syslinep_prev).dt();
×
690
                    if diff > BACKWARDS_TIME_JUMP_MEANS_NEW_YEAR {
×
691
                        year_opt = Some(year_opt.unwrap() - 1);
×
692
                        defo!("year_opt updated {:?}", year_opt);
×
693
                        self.syslinereader
×
694
                            .remove_sysline(fo_prev);
×
695
                        fo_prev = fo_prev_prev;
×
696
                        syslinep_prev_opt = Some(syslinep_prev.clone());
×
697
                        continue;
×
698
                    }
×
699
                }
801✔
700
            }
25✔
701
            if fo_prev < charsz_fo {
826✔
702
                defo!("fo_prev {} break;", fo_prev);
23✔
703
                // fileoffset is at the beginning of the file (or, cannot be moved back any more)
704
                break;
23✔
705
            }
803✔
706
            // if user-passed `--dt-after` and the sysline is prior to that filter then
707
            // stop processing
708
            match dt_after_or_before(syslinep.dt(), filter_dt_after_opt) {
803✔
709
                Result_Filter_DateTime1::OccursBefore => {
710
                    defo!("dt_after_or_before({:?},  {:?}) returned OccursBefore; break", syslinep.dt(), filter_dt_after_opt);
2✔
711
                    break;
2✔
712
                }
713
                Result_Filter_DateTime1::OccursAtOrAfter | Result_Filter_DateTime1::Pass => {},
801✔
714
            }
715
            // search for preceding sysline
716
            fo_prev -= charsz_fo;
801✔
717
            if fo_prev >= fo_prev_prev {
801✔
718
                // This will happen in case where the very first line of the file
719
                // holds a sysline with datetime pattern without a year, and that
720
                // sysline datetime pattern is different than all
721
                // proceeding syslines that have a year. (and it should only happen then)
722
                // Elicited by example in Issue #74
723
                de_err!("fo_prev {} ≥ {} fo_prev_prev, expected <; something is wrong", fo_prev, fo_prev_prev);
×
724
                // must break otherwise end up in an infinite loop
725
                break;
×
726
            }
801✔
727
            syslinep_prev_opt = Some(syslinep.clone());
801✔
728
        } // end loop
729
        defx!("return FileOk");
25✔
730

731
        FileProcessingResultBlockZero::FileOk
25✔
732
    }
25✔
733

734
    fn systemtime_at_uptime_zero(&self) -> Option<SystemTime>{
×
735
        self.syslinereader.systemtime_at_uptime_zero
×
736
    }
×
737

738
    pub fn process_uptime(
×
739
        &mut self,
×
740
    ) -> FileProcessingResultBlockZero {
×
741
        defn!();
×
742
        debug_assert!(!self.did_process_uptime(), "did_process_uptime() must only be called once");
×
743

744
        let fo_last = self.fileoffset_last();
×
745
        defo!("find_sysline(fo_last={})", fo_last);
×
746
        let syslinep = match self.find_sysline(fo_last) {
×
747
            ResultFindSysline::Found((_fo, syslinep_)) => {
×
748
                defo!("found sysline at fo_last={} {:?}", fo_last, syslinep_);
×
749

750
                syslinep_
×
751
            }
752
            ResultFindSysline::Done => {
×
753
                defx!("No sysline found");
×
754
                return FileProcessingResultBlockZero::FileErrNoSyslinesFound;
×
755
            }
756
            ResultFindSysline::Err(err) => {
×
757
                defx!("error finding sysline: {:?}", err);
×
758
                return FileProcessingResultBlockZero::FileErrIo(err);
×
759
            }
760
        };
761
        let dt = syslinep.dt();
×
762
        let diff_ = datetime_minus_systemtime(&dt, &UPTIME_DEFAULT_OFFSET);
×
763
        defo!("diff_ from UPTIME_DEFAULT_OFFSET {:?}", diff_);
×
764
        let diff_secs = diff_.num_seconds();
×
765
        defo!("diff_secs {:?}", diff_secs);
×
766
        let mut diff_nanos = diff_.subsec_nanos();
×
767
        defo!("diff_nanos {:?}", diff_nanos);
×
768
        if diff_nanos < 0 {
×
769
            diff_nanos = 0;
×
770
        }
×
771
        let diffs: StdDuration = StdDuration::new(diff_secs as u64, diff_nanos as u32);
×
772
        defo!("diffs {:?}", diffs);
×
773
        defo!("mtime()");
×
774
        let mtime = self.mtime();
×
775
        defo!("mtime {:?} (as DateTime {:?})", mtime, systemtime_to_datetime(&self.tz_offset, &mtime));
×
776
        // std::time::Duration is unsigned whereas chrono::Duration is signed.
777
        let st_at_zero = if diff_secs > 0 {
×
778
            defo!("checked_sub({:?})", diffs);
×
779
            match mtime.checked_sub(diffs) {
×
780
                Some(st) => st,
×
781
                None => {
782
                    defx!("failed to calculate systemtime at uptime zero");
×
783
                    return FileProcessingResultBlockZero::FileErrIo(std::io::Error::new(
×
784
                        std::io::ErrorKind::Other,
×
785
                        "failed to calculate systemtime at uptime zero",
×
786
                    ));
×
787
                }
788
            }
789
        } else {
790
            defo!("checked_add({:?})", diffs);
×
791
            match mtime.checked_add(diffs) {
×
792
                Some(st) => st,
×
793
                None => {
794
                    defx!("failed to calculate systemtime at uptime zero");
×
795
                    return FileProcessingResultBlockZero::FileErrIo(std::io::Error::new(
×
796
                        std::io::ErrorKind::Other,
×
797
                        "failed to calculate systemtime at uptime zero",
×
798
                    ));
×
799
                }
800
            }
801
        };
802
        self.syslinereader.systemtime_at_uptime_zero = Some(st_at_zero);
×
803
        defo!("systemtime_at_uptime_zero is  {:?}", self.syslinereader.systemtime_at_uptime_zero);
×
804
        #[cfg(debug_assertions)]
805
        {
806
            let d = systemtime_to_datetime(
×
807
                &self.tz_offset,
×
808
                &st_at_zero,
×
809
            );
810
            defo!("systemtime_at_uptime_zero as DateTime {:?}", d);
×
811
        }
812

813
        // The systemtime at uptime zero has been discovered.
814
        // So clear the lines that previously used the stand-in value for
815
        // `systemtime_at_uptime_zero`.
816
        self.syslinereader.clear_syslines();
×
817
        // The syslines gathered after this point will use the
818
        // correct `systemtime_at_uptime_zero`.
819

820
        defx!("return FileOk");
×
821

822
        FileProcessingResultBlockZero::FileOk
×
823
    }
×
824

825
    /// See [`SyslineReader::is_sysline_last`].
826
    ///
827
    /// [`SyslineReader::is_sysline_last`]: crate::readers::syslinereader::SyslineReader#method.is_sysline_last
828
    pub fn is_sysline_last(
4,180✔
829
        &self,
4,180✔
830
        syslinep: &SyslineP,
4,180✔
831
    ) -> bool {
4,180✔
832
        self.syslinereader
4,180✔
833
            .is_sysline_last(syslinep)
4,180✔
834
    }
4,180✔
835

836
    /// Try to `drop` data associated with the [`Block`] at [`BlockOffset`].
837
    /// This includes dropping associated [`Sysline`]s and [`Line`]s.
838
    /// This calls [`SyslineReader::drop_data`].
839
    ///
840
    /// _The caller must know what they are doing!_
841
    ///
842
    /// [`BlockOffset`]: crate::readers::blockreader::BlockOffset
843
    /// [`Sysline`]: crate::data::sysline::Sysline
844
    /// [`Line`]: crate::data::line::Line
845
    /// [`Block`]: crate::readers::blockreader::Block
846
    pub fn drop_data(
14✔
847
        &mut self,
14✔
848
        blockoffset: BlockOffset,
14✔
849
    ) -> bool {
14✔
850
        def1n!("({})", blockoffset);
14✔
851
        self.assert_stage(ProcessingStage::Stage3StreamSyslines);
14✔
852

853
        if !self.is_drop_data() {
14✔
854
            def1x!("return false; is_drop_data() is false");
×
855
            return false;
×
856
        }
14✔
857

858
        // `syslinereader.drop_data` is an expensive function, skip if possible.
859
        if blockoffset == self.drop_block_last {
14✔
860
            def1x!("({}) skip block, return true", blockoffset);
5✔
861
            return false;
5✔
862
        }
9✔
863

864
        if self
9✔
865
            .syslinereader
9✔
866
            .drop_data(blockoffset)
9✔
867
        {
868
            self.drop_block_last = blockoffset;
4✔
869
            def1x!("({}) return true", blockoffset);
4✔
870
            return true;
4✔
871
        }
5✔
872

873
        def1x!("({}) return false", blockoffset);
5✔
874
        false
5✔
875
    }
14✔
876

877
    /// Call [`drop_data`] for the data assocaited with the [`Block`]
878
    /// *preceding* the first block of the passed [`Sysline`].
879
    ///
880
    /// _The caller must know what they are doing!_
881
    ///
882
    /// [`drop_data`]: Self#method.drop_data
883
    /// [`Block`]: crate::readers::blockreader::Block
884
    /// [`Sysline`]: crate::data::sysline::Sysline
885
    pub fn drop_data_try(
3,664✔
886
        &mut self,
3,664✔
887
        syslinep: &SyslineP,
3,664✔
888
    ) -> bool {
3,664✔
889
        if !SyslogProcessor::STREAM_STAGE_DROP {
3,664✔
890
            de_wrn!("drop_data_try() called but SyslogProcessor::STREAM_STAGE_DROP is false");
×
891
            return false;
×
892
        }
3,664✔
893
        if !self.is_drop_data() {
3,664✔
894
            def1ñ!("is_drop_data() is false; return false");
×
895
            return false;
×
896
        }
3,664✔
897

898
        let bo_first: BlockOffset = (*syslinep).blockoffset_first();
3,664✔
899
        if bo_first > 1 {
3,664✔
900
            def1ñ!();
14✔
901
            return self.drop_data(bo_first - 2);
14✔
902
        }
3,650✔
903

904
        false
3,650✔
905
    }
3,664✔
906

907
    /// Calls [`self.syslinereader.find_sysline(fileoffset)`],
908
    /// and in some cases calls private function `drop_block` to drop
909
    /// previously processed [`Sysline`], [`Line`], and [`Block`s].
910
    ///
911
    /// This is what implements the "streaming" in "[streaming stage]".
912
    ///
913
    /// [`self.syslinereader.find_sysline(fileoffset)`]: crate::readers::syslinereader::SyslineReader#method.find_sysline
914
    /// [`Block`s]: crate::readers::blockreader::Block
915
    /// [`Line`]: crate::data::line::Line
916
    /// [`Sysline`]: crate::data::sysline::Sysline
917
    /// [streaming stage]: crate::readers::syslogprocessor::ProcessingStage#variant.Stage3StreamSyslines
918
    pub fn find_sysline(
88✔
919
        &mut self,
88✔
920
        fileoffset: FileOffset,
88✔
921
    ) -> ResultFindSysline {
88✔
922
        defn!("({})", fileoffset);
88✔
923
        let result: ResultFindSysline = self
88✔
924
            .syslinereader
88✔
925
            .find_sysline(fileoffset);
88✔
926
        match result {
88✔
927
            ResultFindSysline::Found(_) => {}
74✔
928
            ResultFindSysline::Done => {}
14✔
929
            ResultFindSysline::Err(ref err) => {
×
930
                self.set_error(err);
×
931
            }
×
932
        }
933
        defx!();
88✔
934

935
        result
88✔
936
    }
88✔
937

938
    /// Wrapper function for [`SyslineReader::find_sysline_between_datetime_filters`].
939
    /// Keeps a custom copy of any returned `Error` at `self.error`.
940
    ///
941
    /// [`SyslineReader::find_sysline_between_datetime_filters`]: crate::readers::syslinereader::SyslineReader#method.find_sysline_between_datetime_filters
942
    //
943
    // TODO: [2022/06/20] the `find` functions need consistent naming,
944
    //       `find_next`, `find_between`, `find_…` . The current design has
945
    //       the public-facing `find_` functions falling back on potential file-wide binary-search
946
    //       The binary-search only needs to be done during the stage 2. During stage 3, a simpler
947
    //       linear sequential search is more suitable, and more intuitive.
948
    //       More refactoring is in order.
949
    //       Also, a linear search can better detect rollover (i.e. when sysline datetime is missing year).
950
    // TODO: [2023/03/06] add stats tracking in `find` functions for number of
951
    //       "jumps" or bounces or fileoffset changes to confirm big-O
952
    #[inline(always)]
953
    pub fn find_sysline_between_datetime_filters(
4,185✔
954
        &mut self,
4,185✔
955
        fileoffset: FileOffset,
4,185✔
956
    ) -> ResultFindSysline {
4,185✔
957
        defn!("({})", fileoffset);
4,185✔
958

959
        let result = match self
4,185✔
960
            .syslinereader
4,185✔
961
            .find_sysline_between_datetime_filters(
4,185✔
962
                fileoffset,
4,185✔
963
                &self.filter_dt_after_opt,
4,185✔
964
                &self.filter_dt_before_opt,
4,185✔
965
            ) {
4,185✔
966
            ResultFindSysline::Err(err) => {
×
967
                self.set_error(&err);
×
968

969
                ResultFindSysline::Err(err)
×
970
            }
971
            val => val,
4,185✔
972
        };
973

974
        defx!("({})", fileoffset);
4,185✔
975

976
        result
4,185✔
977
    }
4,185✔
978

979
    /// Wrapper function for a recurring sanity check.
980
    ///
981
    /// Good for checking functions `process_stage…` are called in
982
    /// the correct order.
983
    // XXX: is there a rust-ic way to enforce stage procession behavior
984
    //      at compile-time? It's a fairly simple enumerated type. Could a
985
    //      `match` tree (or something like that) be used?
986
    //      run-time checks of rust enum values seems hacky.
987
    #[inline(always)]
988
    fn assert_stage(
2,729✔
989
        &self,
2,729✔
990
        stage_expact: ProcessingStage,
2,729✔
991
    ) {
2,729✔
992
        debug_assert_eq!(
2,729✔
993
            self.processingstage, stage_expact,
994
            "Unexpected Processing Stage {:?}, expected Processing Stage {:?}",
×
995
            self.processingstage, stage_expact,
996
        );
997
    }
2,729✔
998

999
    /// Stage 0 does some sanity checks on the file.
1000
    // TODO: this is redundant and has already been performed by functions in
1001
    //       `filepreprocessor` and `BlockReader::new`.
1002
    pub fn process_stage0_valid_file_check(&mut self) -> FileProcessingResultBlockZero {
380✔
1003
        defn!();
380✔
1004
        // sanity check calls are in correct order
1005
        self.assert_stage(ProcessingStage::Stage0ValidFileCheck);
380✔
1006
        self.processingstage = ProcessingStage::Stage0ValidFileCheck;
380✔
1007

1008
        if self.filesz() == 0 {
380✔
1009
            defx!("filesz 0; return {:?}", FileProcessingResultBlockZero::FileErrEmpty);
2✔
1010
            return FileProcessingResultBlockZero::FileErrEmpty;
2✔
1011
        }
378✔
1012
        defx!("return {:?}", FileProcessingResultBlockZero::FileOk);
378✔
1013

1014
        FileProcessingResultBlockZero::FileOk
378✔
1015
    }
380✔
1016

1017
    /// Stage 1: Can [`Line`s] and [`Sysline`s] be parsed from the first block
1018
    /// (block zero)?
1019
    ///
1020
    /// [`Sysline`s]: crate::data::sysline::Sysline
1021
    /// [`Line`s]: crate::data::line::Line
1022
    pub fn process_stage1_blockzero_analysis(&mut self) -> FileProcessingResultBlockZero {
377✔
1023
        defn!();
377✔
1024
        self.assert_stage(ProcessingStage::Stage0ValidFileCheck);
377✔
1025
        self.processingstage = ProcessingStage::Stage1BlockzeroAnalysis;
377✔
1026

1027
        let result: FileProcessingResultBlockZero = self.blockzero_analysis();
377✔
1028
        // stored syslines may be zero if a "partial" `Line` was examined
1029
        // e.g. an incomplete and temporary `Line` instance was examined.
1030
        defo!(
377✔
1031
            "blockzero_analysis() stored syslines {}",
377✔
1032
            self.syslinereader
377✔
1033
                .count_syslines_stored()
377✔
1034
        );
1035
        match result {
377✔
1036
            FileProcessingResult::FileOk => {}
269✔
1037
            // skip further processing if not `FileOk`
1038
            _ => {
1039
                defx!("return {:?}", result);
108✔
1040
                return result;
108✔
1041
            }
1042
        }
1043

1044
        defx!("return {:?}", result);
269✔
1045

1046
        result
269✔
1047
    }
377✔
1048

1049
    /// Stage 2: Given the an optional datetime filter (user-passed
1050
    /// `--dt-after`), can a log message with a datetime after that filter be
1051
    /// found?
1052
    pub fn process_stage2_find_dt(
238✔
1053
        &mut self,
238✔
1054
        filter_dt_after_opt: &DateTimeLOpt,
238✔
1055
    ) -> FileProcessingResultBlockZero {
238✔
1056
        defn!();
238✔
1057
        self.assert_stage(ProcessingStage::Stage1BlockzeroAnalysis);
238✔
1058
        self.processingstage = ProcessingStage::Stage2FindDt;
238✔
1059

1060
        // datetime formats without a year requires special handling
1061
        if !self.syslinereader.dt_pattern_has_year() &&
238✔
1062
            !self.syslinereader.dt_pattern_uptime()
24✔
1063
        {
1064
            defo!("!dt_pattern_has_year() && !dt_pattern_uptime()");
24✔
1065
            let mtime: SystemTime = self.mtime();
24✔
1066
            match self.process_missing_year(mtime, filter_dt_after_opt) {
24✔
1067
                FileProcessingResultBlockZero::FileOk => {}
24✔
1068
                result => {
×
1069
                    defx!("Bad result {:?}", result);
×
1070
                    return result;
×
1071
                }
1072
            }
1073
        } else if self.syslinereader.dt_pattern_uptime() {
214✔
1074
            defo!("dt_pattern_uptime()");
×
1075
            match self.process_uptime() {
×
1076
                FileProcessingResultBlockZero::FileOk => {}
×
1077
                result => {
×
1078
                    defx!("Bad result {:?}", result);
×
1079
                    return result;
×
1080
                }
1081
            }
1082
        }
214✔
1083

1084
        defx!();
238✔
1085

1086
        FileProcessingResultBlockZero::FileOk
238✔
1087
    }
238✔
1088

1089
    /// Stage 3: during "[streaming]", processed and printed data stored by
1090
    /// underlying "Readers" is proactively dropped
1091
    /// (removed from process memory).
1092
    ///
1093
    /// Also see [`find_sysline`].
1094
    ///
1095
    /// [streaming]: ProcessingStage#variant.Stage3StreamSyslines
1096
    /// [`find_sysline`]: self::SyslogProcessor#method.find_sysline
1097
    pub fn process_stage3_stream_syslines(&mut self) -> FileProcessingResultBlockZero {
234✔
1098
        defñ!();
234✔
1099
        self.assert_stage(ProcessingStage::Stage2FindDt);
234✔
1100
        self.processingstage = ProcessingStage::Stage3StreamSyslines;
234✔
1101

1102
        FileProcessingResultBlockZero::FileOk
234✔
1103
    }
234✔
1104

1105
    /// Stage 4: no more [`Sysline`s] to process. Create and return a
1106
    /// [`Summary`].
1107
    ///
1108
    /// [`Summary`]: crate::readers::summary::Summary
1109
    /// [`Sysline`s]: crate::data::sysline::Sysline
1110
    pub fn process_stage4_summary(&mut self) -> Summary {
231✔
1111
        defñ!();
231✔
1112
        // XXX: this can be called from various stages, no need to assert
1113
        self.processingstage = ProcessingStage::Stage4Summary;
231✔
1114

1115
        self.summary_complete()
231✔
1116
    }
231✔
1117

1118
    /// Review bytes in the first block ("zero block").
1119
    /// If enough `Line` found then return [`FileOk`]
1120
    /// else return [`FileErrNoLinesFound`].
1121
    ///
1122
    /// [`FileOk`]: self::FileProcessingResultBlockZero
1123
    /// [`FileErrNoLinesFound`]: self::FileProcessingResultBlockZero
1124
    pub(super) fn blockzero_analysis_bytes(&mut self) -> FileProcessingResultBlockZero {
377✔
1125
        defn!();
377✔
1126
        self.assert_stage(ProcessingStage::Stage1BlockzeroAnalysis);
377✔
1127

1128
        let blockp: BlockP = match self
377✔
1129
            .syslinereader
377✔
1130
            .linereader
377✔
1131
            .blockreader
377✔
1132
            .read_block(0)
377✔
1133
        {
1134
            ResultFindReadBlock::Found(blockp_) => blockp_,
377✔
1135
            ResultFindReadBlock::Done => {
×
1136
                defx!("return FileErrEmpty");
×
1137
                return FileProcessingResultBlockZero::FileErrEmpty;
×
1138
            }
1139
            ResultFindReadBlock::Err(err) => {
×
1140
                self.set_error(&err);
×
1141
                defx!("return FileErrIo({:?})", err);
×
1142
                return FileProcessingResultBlockZero::FileErrIoPath(err);
×
1143
            }
1144
        };
1145
        // if the first block is too small then there will not be enough
1146
        // data to parse a `Line` or `Sysline`
1147
        let blocksz0: BlockSz = (*blockp).len() as BlockSz;
377✔
1148
        let require_sz: BlockSz = std::cmp::min(Self::BLOCKZERO_ANALYSIS_BYTES_MIN, self.blocksz());
377✔
1149
        defo!("blocksz0 {} < {} require_sz", blocksz0, require_sz);
377✔
1150
        if blocksz0 < require_sz {
377✔
1151
            defx!("return FileErrTooSmall");
9✔
1152
            return FileProcessingResultBlockZero::FileErrTooSmall;
9✔
1153
        }
368✔
1154
        // if the first `BLOCKZERO_ANALYSIS_BYTES_NULL_MAX` bytes are all
1155
        // zero then this is not a text file and processing should stop.
1156
        if (*blockp).iter().take(Self::BLOCKZERO_ANALYSIS_BYTES_NULL_MAX).all(|&b| b == 0) {
510✔
1157
            defx!("return FileErrNullBytes");
2✔
1158
            return FileProcessingResultBlockZero::FileErrNullBytes;
2✔
1159
        }
366✔
1160

1161
        defx!("return FileOk");
366✔
1162

1163
        FileProcessingResultBlockZero::FileOk
366✔
1164
    }
377✔
1165

1166
    /// Attempt to find a minimum number of [`Line`s] within the first block
1167
    /// (block zero).
1168
    /// If enough `Line` found then return [`FileOk`]
1169
    /// else return [`FileErrNoLinesFound`].
1170
    ///
1171
    /// [`Line`s]: crate::data::line::Line
1172
    /// [`FileOk`]: self::FileProcessingResultBlockZero
1173
    /// [`FileErrNoLinesFound`]: self::FileProcessingResultBlockZero
1174
    pub(super) fn blockzero_analysis_lines(&mut self) -> FileProcessingResultBlockZero {
366✔
1175
        defn!();
366✔
1176
        self.assert_stage(ProcessingStage::Stage1BlockzeroAnalysis);
366✔
1177

1178
        let blockp: BlockP = match self
366✔
1179
            .syslinereader
366✔
1180
            .linereader
366✔
1181
            .blockreader
366✔
1182
            .read_block(0)
366✔
1183
        {
1184
            ResultFindReadBlock::Found(blockp_) => blockp_,
366✔
1185
            ResultFindReadBlock::Done => {
×
1186
                defx!("return FileErrEmpty");
×
1187
                return FileProcessingResultBlockZero::FileErrEmpty;
×
1188
            }
1189
            ResultFindReadBlock::Err(err) => {
×
1190
                self.set_error(&err);
×
1191
                defx!("return FileErrIo({:?})", err);
×
1192
                return FileProcessingResultBlockZero::FileErrIoPath(err);
×
1193
            }
1194
        };
1195
        let blocksz0: BlockSz = (*blockp).len() as BlockSz;
366✔
1196
        let mut _partial_found = false;
366✔
1197
        let mut fo: FileOffset = 0;
366✔
1198
        // how many lines have been found?
1199
        let mut found: Count = 0;
366✔
1200
        // must find at least this many lines in block zero to be FileOk
1201
        let found_min: Count = *BLOCKZERO_ANALYSIS_LINE_COUNT_MIN_MAP
366✔
1202
            .get(&blocksz0)
366✔
1203
            .unwrap();
366✔
1204
        defx!("block zero blocksz {} found_min {}", blocksz0, found_min);
366✔
1205
        // find `found_min` Lines or whatever can be found within block 0
1206
        while found < found_min {
741✔
1207
            fo = match self
406✔
1208
                .syslinereader
406✔
1209
                .linereader
406✔
1210
                .find_line_in_block(fo)
406✔
1211
            {
1212
                (ResultFindLine::Found((fo_next, _linep)), _) => {
379✔
1213
                    found += 1;
379✔
1214

1215
                    fo_next
379✔
1216
                }
1217
                (ResultFindLine::Done, partial) => {
27✔
1218
                    if partial.is_some() {
27✔
1219
                        found += 1;
27✔
1220
                        _partial_found = true;
27✔
1221
                    }
27✔
1222
                    break;
27✔
1223
                }
1224
                (ResultFindLine::Err(err), _) => {
×
1225
                    self.set_error(&err);
×
1226
                    defx!("return FileErrIo({:?})", err);
×
1227
                    return FileProcessingResultBlockZero::FileErrIoPath(err);
×
1228
                }
1229
            };
1230
            if 0 != self
379✔
1231
                .syslinereader
379✔
1232
                .linereader
379✔
1233
                .block_offset_at_file_offset(fo)
379✔
1234
            {
1235
                break;
4✔
1236
            }
375✔
1237
        }
1238

1239
        let fpr: FileProcessingResultBlockZero = if found >= found_min {
366✔
1240
            FileProcessingResultBlockZero::FileOk
366✔
1241
        } else {
1242
            FileProcessingResultBlockZero::FileErrNoLinesFound
×
1243
        };
1244

1245
        defx!("found {} lines, partial_found {}, require {} lines, return {:?}", found, _partial_found, found_min, fpr);
366✔
1246

1247
        fpr
366✔
1248
    }
366✔
1249

1250
    /// Attempt to find a minimum number of [`Sysline`] within the first block.
1251
    /// If enough `Sysline` found then return [`FileOk`]
1252
    /// else return [`FileErrNoSyslinesFound`].
1253
    ///
1254
    /// [`Sysline`]: crate::data::sysline::Sysline
1255
    /// [`FileOk`]: self::FileProcessingResultBlockZero
1256
    /// [`FileErrNoSyslinesFound`]: self::FileProcessingResultBlockZero
1257
    pub(super) fn blockzero_analysis_syslines(&mut self) -> FileProcessingResultBlockZero {
366✔
1258
        defn!();
366✔
1259
        self.assert_stage(ProcessingStage::Stage1BlockzeroAnalysis);
366✔
1260

1261
        let blockp: BlockP = match self
366✔
1262
            .syslinereader
366✔
1263
            .linereader
366✔
1264
            .blockreader
366✔
1265
            .read_block(0)
366✔
1266
        {
1267
            ResultFindReadBlock::Found(blockp_) => blockp_,
366✔
1268
            ResultFindReadBlock::Done => {
×
1269
                defx!("return FileErrEmpty");
×
1270
                return FileProcessingResultBlockZero::FileErrEmpty;
×
1271
            }
1272
            ResultFindReadBlock::Err(err) => {
×
1273
                self.set_error(&err);
×
1274
                defx!("return FileErrIo({:?})", err);
×
1275
                return FileProcessingResultBlockZero::FileErrIoPath(err);
×
1276
            }
1277
        };
1278
        let blocksz0: BlockSz = (*blockp).len() as BlockSz;
366✔
1279
        let mut fo: FileOffset = 0;
366✔
1280
        // how many syslines have been found?
1281
        let mut found: Count = 0;
366✔
1282
        // must find at least this many syslines in block zero to be FileOk
1283
        let found_min: Count = *BLOCKZERO_ANALYSIS_SYSLINE_COUNT_MIN_MAP
366✔
1284
            .get(&blocksz0)
366✔
1285
            .unwrap();
366✔
1286
        defo!("block zero blocksz {} found_min {:?}", blocksz0, found_min);
366✔
1287

1288
        // find `at_max` Syslines within block zero
1289
        while found < found_min
647✔
1290
            && self.syslinereader.block_offset_at_file_offset(fo) == 0
386✔
1291
        {
1292
            fo = match self
386✔
1293
                .syslinereader
386✔
1294
                .find_sysline_in_block(fo)
386✔
1295
            {
1296
                (ResultFindSysline::Found((fo_next, _slinep)), _) => {
281✔
1297
                    found += 1;
281✔
1298
                    defo!("Found; found {} syslines, fo_next {}", found, fo_next);
281✔
1299

1300
                    fo_next
281✔
1301
                }
1302
                (ResultFindSysline::Done, partial_found) => {
105✔
1303
                    defo!("Done; found {} syslines, partial_found {}", found, partial_found);
105✔
1304
                    if partial_found {
105✔
1305
                        found += 1;
8✔
1306
                    }
97✔
1307
                    break;
105✔
1308
                }
1309
                (ResultFindSysline::Err(err), _) => {
×
1310
                    self.set_error(&err);
×
1311
                    defx!("return FileErrIo({:?})", err);
×
1312
                    return FileProcessingResultBlockZero::FileErrIoPath(err);
×
1313
                }
1314
            };
1315
        }
1316

1317
        if found == 0 {
366✔
1318
            defx!("found {} syslines, require {} syslines, return FileErrNoSyslinesFound", found, found_min);
97✔
1319
            return FileProcessingResultBlockZero::FileErrNoSyslinesFound;
97✔
1320
        }
269✔
1321

1322
        let patt_count_a = self.syslinereader.dt_patterns_counts_in_use();
269✔
1323
        defo!("dt_patterns_counts_in_use {}", patt_count_a);
269✔
1324

1325
        if !self.syslinereader.dt_patterns_analysis() {
269✔
1326
            de_err!("dt_patterns_analysis() failed which is unexpected; return FileErrNoSyslinesFound");
×
1327
            return FileProcessingResultBlockZero::FileErrNoSyslinesFound;
×
1328
        }
269✔
1329

1330
        let _patt_count_b = self.syslinereader.dt_patterns_counts_in_use();
269✔
1331
        debug_assert_eq!(
269✔
1332
            _patt_count_b,
1333
            SyslogProcessor::DT_PATTERN_MAX,
1334
            "expected patterns to be reduced to {}, found {:?}",
×
1335
            SyslogProcessor::DT_PATTERN_MAX,
1336
            _patt_count_b,
1337
        );
1338

1339
        // if more than one `DateTimeParseInstr` was used then the syslines
1340
        // must be reparsed using the one chosen `DateTimeParseInstr`
1341
        if patt_count_a > 1 {
269✔
1342
            defo!("must reprocess all syslines using limited patterns (used {} DateTimeParseInstr; must only use {})!", patt_count_a, 1);
8✔
1343

1344
            self.syslinereader.clear_syslines();
8✔
1345
            // find `at_max` Syslines within block zero
1346
            found = 0;
8✔
1347
            fo = 0;
8✔
1348
            while found < found_min
11✔
1349
                && self.syslinereader.block_offset_at_file_offset(fo) == 0
8✔
1350
            {
1351
                fo = match self
8✔
1352
                    .syslinereader
8✔
1353
                    .find_sysline_in_block(fo)
8✔
1354
                {
1355
                    (ResultFindSysline::Found((fo_next, _slinep)), _) => {
3✔
1356
                        found += 1;
3✔
1357
                        defo!("Found; found {} syslines, fo_next {}", found, fo_next);
3✔
1358

1359
                        fo_next
3✔
1360
                    }
1361
                    (ResultFindSysline::Done, partial_found) => {
5✔
1362
                        defo!("Done; found {} syslines, partial_found {}", found, partial_found);
5✔
1363
                        if partial_found {
5✔
1364
                            found += 1;
5✔
1365
                        }
5✔
1366
                        break;
5✔
1367
                    }
1368
                    (ResultFindSysline::Err(err), _) => {
×
1369
                        self.set_error(&err);
×
1370
                        defx!("return FileErrIo({:?})", err);
×
1371
                        return FileProcessingResultBlockZero::FileErrIoPath(err);
×
1372
                    }
1373
                };
1374
            }
1375
            defo!("done reprocessing.");
8✔
1376
        } else {
1377
            defo!("no reprocess needed ({} DateTimeParseInstr)!", patt_count_a);
261✔
1378
        }
1379

1380
        let fpr: FileProcessingResultBlockZero = match found >= found_min {
269✔
1381
            true => FileProcessingResultBlockZero::FileOk,
269✔
1382
            false => FileProcessingResultBlockZero::FileErrNoSyslinesFound,
×
1383
        };
1384

1385
        // sanity check that only one `DateTimeParseInstr` is in use
1386
        if cfg!(debug_assertions) && self.syslinereader.dt_patterns_counts_in_use() != 1 {
269✔
1387
            de_wrn!(
×
1388
                "dt_patterns_counts_in_use() = {}, expected 1; for {:?}",
×
1389
                self.syslinereader.dt_patterns_counts_in_use(), self.path()
×
1390
            );
×
1391
        }
269✔
1392

1393
        if self.syslinereader.is_streamed_file()
269✔
1394
            && !self.syslinereader.dt_pattern_has_year()
50✔
1395
        {
1396
            self.syslinereader.linereader.blockreader.disable_drop_data();
×
1397
            debug_assert!(!self.is_drop_data(), "is_drop_data() should be false");
×
1398
        }
269✔
1399

1400
        defx!("found {} syslines, require {} syslines, return {:?}", found, found_min, fpr);
269✔
1401

1402
        fpr
269✔
1403
    }
366✔
1404

1405
    /// Call `self.blockzero_analysis_lines`.
1406
    /// If that passes then call `self.blockzero_analysis_syslines`.
1407
    pub(super) fn blockzero_analysis(&mut self) -> FileProcessingResultBlockZero {
377✔
1408
        defn!();
377✔
1409
        assert!(!self.blockzero_analysis_done, "blockzero_analysis_lines should only be completed once.");
377✔
1410
        self.blockzero_analysis_done = true;
377✔
1411
        self.assert_stage(ProcessingStage::Stage1BlockzeroAnalysis);
377✔
1412

1413
        if self.syslinereader.filesz() == 0 {
377✔
1414
            defx!("return FileErrEmpty");
×
1415
            return FileProcessingResultBlockZero::FileErrEmpty;
×
1416
        }
377✔
1417

1418
        let result: FileProcessingResultBlockZero = self.blockzero_analysis_bytes();
377✔
1419
        if !result.is_ok() {
377✔
1420
            defx!("syslinereader.blockzero_analysis_bytes() was !is_ok(), return {:?}", result);
11✔
1421
            return result;
11✔
1422
        };
366✔
1423

1424
        let result: FileProcessingResultBlockZero = self.blockzero_analysis_lines();
366✔
1425
        if !result.is_ok() {
366✔
1426
            defx!("syslinereader.blockzero_analysis() was !is_ok(), return {:?}", result);
×
1427
            return result;
×
1428
        };
366✔
1429

1430
        let result: FileProcessingResultBlockZero = self.blockzero_analysis_syslines();
366✔
1431
        defx!("return {:?}", result);
366✔
1432

1433
        result
366✔
1434
    }
377✔
1435

1436
    #[cfg(test)]
1437
    pub(crate) fn dropped_blocks(&self) -> SetDroppedBlocks {
3✔
1438
        self.syslinereader
3✔
1439
            .linereader
3✔
1440
            .blockreader
3✔
1441
            .dropped_blocks
3✔
1442
            .clone()
3✔
1443
    }
3✔
1444

1445
    #[cfg(test)]
1446
    pub(crate) fn dropped_lines(&self) -> SetDroppedLines {
3✔
1447
        self.syslinereader
3✔
1448
            .linereader
3✔
1449
            .dropped_lines
3✔
1450
            .clone()
3✔
1451
    }
3✔
1452

1453
    #[cfg(test)]
1454
    pub(crate) fn dropped_syslines(&self) -> SetDroppedSyslines {
3✔
1455
        self.syslinereader
3✔
1456
            .dropped_syslines
3✔
1457
            .clone()
3✔
1458
    }
3✔
1459

1460
    pub fn summary(&self) -> SummarySyslogProcessor {
537✔
1461
        let syslogprocessor_missing_year = self.missing_year;
537✔
1462

1463
        SummarySyslogProcessor {
537✔
1464
            syslogprocessor_missing_year,
537✔
1465
        }
537✔
1466
    }
537✔
1467

1468
    /// Return an up-to-date [`Summary`] instance for this `SyslogProcessor`.
1469
    ///
1470
    /// Probably not useful or interesting before
1471
    /// `ProcessingStage::Stage4Summary`.
1472
    ///
1473
    /// [`Summary`]: crate::readers::summary::Summary
1474
    pub fn summary_complete(&self) -> Summary {
534✔
1475
        let path = self.path().clone();
534✔
1476
        let path_ntf = None;
534✔
1477
        let filetype = self.filetype();
534✔
1478
        let logmessagetype = filetype.to_logmessagetype();
534✔
1479
        let summaryblockreader = self.syslinereader.linereader.blockreader.summary();
534✔
1480
        let summarylinereader = self.syslinereader.linereader.summary();
534✔
1481
        let summarysyslinereader = self.syslinereader.summary();
534✔
1482
        let summarysyslogprocessor = self.summary();
534✔
1483
        let error: Option<String> = self.error.clone();
534✔
1484

1485
        Summary::new(
534✔
1486
            path,
534✔
1487
            path_ntf,
534✔
1488
            filetype,
534✔
1489
            logmessagetype,
534✔
1490
            Some(summaryblockreader),
534✔
1491
            Some(summarylinereader),
534✔
1492
            Some(summarysyslinereader),
534✔
1493
            Some(summarysyslogprocessor),
534✔
1494
            None,
534✔
1495
            None,
534✔
1496
            None,
534✔
1497
            None,
534✔
1498
            error,
534✔
1499
        )
1500
    }
534✔
1501
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc