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

jtmoon79 / super-speedy-syslog-searcher / 24063228216

07 Apr 2026 03:45AM UTC coverage: 68.152% (-1.6%) from 69.783%
24063228216

push

github

web-flow
dependabot: bump cargo-msrv from 0.15.1 to 0.18.4

Bumps [cargo-msrv](https://github.com/foresterre/cargo-msrv) from 0.15.1 to 0.18.4.
- [Release notes](https://github.com/foresterre/cargo-msrv/releases)
- [Changelog](https://github.com/foresterre/cargo-msrv/blob/main/CHANGELOG.md)
- [Commits](https://github.com/foresterre/cargo-msrv/compare/v0.15.1...v0.18.4)

---
updated-dependencies:
- dependency-name: cargo-msrv
  dependency-version: 0.18.4
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

15527 of 22783 relevant lines covered (68.15%)

137090.76 hits per line

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

67.05
/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
    /// `FixedOffset` timezone for datetime formats without a timezone.
238
    tz_offset: FixedOffset,
239
    /// Optional filter, syslines _after_ this `DateTimeL`.
240
    filter_dt_after_opt: DateTimeLOpt,
241
    /// Optional filter, syslines _before_ this `DateTimeL`.
242
    filter_dt_before_opt: DateTimeLOpt,
243
    /// Internal sanity check, has `self.blockzero_analysis()` completed?
244
    blockzero_analysis_done: bool,
245
    /// Internal tracking of last `blockoffset` passed to `drop_block`.
246
    drop_block_last: BlockOffset,
247
    /// Optional `Year` value used to start `process_missing_year()`.
248
    /// Only needed for syslog files with datetime format without a year.
249
    missing_year: Option<Year>,
250
    /// The last [`Error`], if any, as a `String`. Set by [`set_error`].
251
    ///
252
    /// Annoyingly, cannot [Clone or Copy `Error`].
253
    ///
254
    /// [`Error`]: std::io::Error
255
    /// [Clone or Copy `Error`]: https://github.com/rust-lang/rust/issues/24135
256
    /// [`set_error`]: self::SyslogProcessor#method.set_error
257
    // TRACKING: https://github.com/rust-lang/rust/issues/24135
258
    error: Option<String>,
259
}
260

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

282
// TODO: [2023/04] remove redundant variable prefix name `syslogprocessor_`
283
#[derive(Clone, Debug, Default, Eq, PartialEq)]
284
pub struct SummarySyslogProcessor {
285
    /// `SyslogProcessor::missing_year`
286
    pub syslogprocessor_missing_year: Option<Year>,
287
}
288

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

297
    /// Maximum number of datetime patterns for matching the remainder of a
298
    /// syslog file.
299
    const DT_PATTERN_MAX: usize = SyslineReader::DT_PATTERN_MAX;
300

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

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

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

323
    /// Allow "streaming stage" to drop data?
324
    /// Compile-time "option" to aid manual debugging.
325
    #[doc(hidden)]
326
    const STREAM_STAGE_DROP: bool = true;
327

328
    /// Use LRU caches in underlying components?
329
    ///
330
    /// XXX: For development and testing experiments!
331
    #[doc(hidden)]
332
    const LRU_CACHE_ENABLE: bool = true;
333

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

366
        if !SyslogProcessor::LRU_CACHE_ENABLE {
396✔
367
            slr.LRU_cache_disable();
×
368
            slr.linereader
×
369
                .LRU_cache_disable();
×
370
            slr.linereader
×
371
                .blockreader
×
372
                .LRU_cache_disable();
×
373
        }
396✔
374

375
        def1x!("return Ok(SyslogProcessor)");
396✔
376

377
        Result::Ok(SyslogProcessor {
396✔
378
            syslinereader: slr,
396✔
379
            processingstage: ProcessingStage::Stage0ValidFileCheck,
396✔
380
            tz_offset,
396✔
381
            filter_dt_after_opt,
396✔
382
            filter_dt_before_opt,
396✔
383
            blockzero_analysis_done: false,
396✔
384
            drop_block_last: 0,
396✔
385
            missing_year: None,
396✔
386
            error: None,
396✔
387
        })
396✔
388
    }
398✔
389

390
    /// `Count` of [`Line`s] processed.
391
    ///
392
    /// [`Line`s]: crate::data::line::Line
393
    #[inline(always)]
394
    #[allow(dead_code)]
395
    pub fn count_lines(&self) -> Count {
×
396
        self.syslinereader
×
397
            .linereader
×
398
            .count_lines_processed()
×
399
    }
×
400

401
    /// See [`Sysline::count_syslines_stored`].
402
    ///
403
    /// [`Sysline::count_syslines_stored`]: crate::data::sysline::Sysline::count_syslines_stored
404
    #[cfg(test)]
405
    pub fn count_syslines_stored(&self) -> Count {
4✔
406
        self.syslinereader.count_syslines_stored()
4✔
407
    }
4✔
408

409
    /// See [`BlockReader::blocksz`].
410
    ///
411
    /// [`BlockReader::blocksz`]: crate::readers::blockreader::BlockReader#method.blocksz
412
    #[inline(always)]
413
    pub const fn blocksz(&self) -> BlockSz {
677✔
414
        self.syslinereader.blocksz()
677✔
415
    }
677✔
416

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

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

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

442
    /// See [`BlockReader::block_offset_at_file_offset`].
443
    ///
444
    /// [`BlockReader::block_offset_at_file_offset`]: crate::readers::blockreader::BlockReader#method.block_offset_at_file_offset
445
    #[allow(dead_code)]
446
    pub const fn block_offset_at_file_offset(
×
447
        &self,
×
448
        fileoffset: FileOffset,
×
449
    ) -> BlockOffset {
×
450
        self.syslinereader
×
451
            .block_offset_at_file_offset(fileoffset)
×
452
    }
×
453

454
    /// See [`BlockReader::file_offset_at_block_offset`].
455
    ///
456
    /// [`BlockReader::file_offset_at_block_offset`]: crate::readers::blockreader::BlockReader#method.file_offset_at_block_offset
457
    #[allow(dead_code)]
458
    pub const fn file_offset_at_block_offset(
×
459
        &self,
×
460
        blockoffset: BlockOffset,
×
461
    ) -> FileOffset {
×
462
        self.syslinereader
×
463
            .file_offset_at_block_offset(blockoffset)
×
464
    }
×
465

466
    /// See [`BlockReader::file_offset_at_block_offset_index`].
467
    ///
468
    /// [`BlockReader::file_offset_at_block_offset_index`]: crate::readers::blockreader::BlockReader#method.file_offset_at_block_offset_index
469
    #[allow(dead_code)]
470
    pub const fn file_offset_at_block_offset_index(
×
471
        &self,
×
472
        blockoffset: BlockOffset,
×
473
        blockindex: BlockIndex,
×
474
    ) -> FileOffset {
×
475
        self.syslinereader
×
476
            .file_offset_at_block_offset_index(blockoffset, blockindex)
×
477
    }
×
478

479
    /// See [`BlockReader::block_index_at_file_offset`].
480
    ///
481
    /// [`BlockReader::block_index_at_file_offset`]: crate::readers::blockreader::BlockReader#method.block_index_at_file_offset
482
    #[allow(dead_code)]
483
    pub const fn block_index_at_file_offset(
×
484
        &self,
×
485
        fileoffset: FileOffset,
×
486
    ) -> BlockIndex {
×
487
        self.syslinereader
×
488
            .block_index_at_file_offset(fileoffset)
×
489
    }
×
490

491
    /// See [`BlockReader::count_blocks`].
492
    ///
493
    /// [`BlockReader::count_blocks`]: crate::readers::blockreader::BlockReader#method.count_blocks
494
    #[allow(dead_code)]
495
    pub const fn count_blocks(&self) -> Count {
×
496
        self.syslinereader
×
497
            .count_blocks()
×
498
    }
×
499

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

509
    /// See [`BlockReader::fileoffset_last`].
510
    ///
511
    /// [`BlockReader::fileoffset_last`]: crate::readers::blockreader::BlockReader#method.fileoffset_last
512
    pub const fn fileoffset_last(&self) -> FileOffset {
25✔
513
        self.syslinereader
25✔
514
            .fileoffset_last()
25✔
515
    }
25✔
516

517
    /// See [`LineReader::charsz`].
518
    ///
519
    /// [`LineReader::charsz`]: crate::readers::linereader::LineReader#method.charsz
520
    #[allow(dead_code)]
521
    pub const fn charsz(&self) -> usize {
25✔
522
        self.syslinereader.charsz()
25✔
523
    }
25✔
524

525
    /// See [`BlockReader::mtime`].
526
    ///
527
    /// [`BlockReader::mtime`]: crate::readers::blockreader::BlockReader#method.mtime
528
    pub fn mtime(&self) -> SystemTime {
324✔
529
        self.syslinereader.mtime()
324✔
530
    }
324✔
531

532
    /// Did this `SyslogProcessor` run `process_missing_year()` ?
533
    fn did_process_missing_year(&self) -> bool {
325✔
534
        self.missing_year.is_some()
325✔
535
    }
325✔
536

537
    /// Did this `SyslogProcessor` run `process_uptime()` ?
538
    fn did_process_uptime(&self) -> bool {
×
539
        self.systemtime_at_uptime_zero().is_some()
×
540
    }
×
541

542
    /// Return `drop_data` value.
543
    pub const fn is_drop_data(&self) -> bool {
3,678✔
544
        self.syslinereader.is_drop_data()
3,678✔
545
    }
3,678✔
546

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

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

634
        // The previously stored `Sysline`s have a filler year that is most likely
635
        // incorrect. The underlying `Sysline` instance cannot be updated behind
636
        // an `Arc`. Those syslines must be dropped and the entire file
637
        // processed again. However, underlying `Line` and `Block` are still
638
        // valid; do not reprocess those.
639
        self.syslinereader
25✔
640
            .clear_syslines();
25✔
641

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

723
        FileProcessingResultBlockZero::FileOk
25✔
724
    }
25✔
725

726
    fn systemtime_at_uptime_zero(&self) -> Option<SystemTime>{
×
727
        self.syslinereader.systemtime_at_uptime_zero
×
728
    }
×
729

730
    pub fn process_uptime(
×
731
        &mut self,
×
732
    ) -> FileProcessingResultBlockZero {
×
733
        defn!();
×
734
        debug_assert!(!self.did_process_uptime(), "did_process_uptime() must only be called once");
×
735

736
        let fo_last = self.fileoffset_last();
×
737
        defo!("find_sysline(fo_last={})", fo_last);
×
738
        let syslinep = match self.find_sysline(fo_last) {
×
739
            ResultFindSysline::Found((_fo, syslinep_)) => {
×
740
                defo!("found sysline at fo_last={} {:?}", fo_last, syslinep_);
×
741

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

805
        // The systemtime at uptime zero has been discovered.
806
        // So clear the lines that previously used the stand-in value for
807
        // `systemtime_at_uptime_zero`.
808
        self.syslinereader.clear_syslines();
×
809
        // The syslines gathered after this point will use the
810
        // correct `systemtime_at_uptime_zero`.
811

812
        defx!("return FileOk");
×
813

814
        FileProcessingResultBlockZero::FileOk
×
815
    }
×
816

817
    /// See [`SyslineReader::is_sysline_last`].
818
    ///
819
    /// [`SyslineReader::is_sysline_last`]: crate::readers::syslinereader::SyslineReader#method.is_sysline_last
820
    pub fn is_sysline_last(
4,180✔
821
        &self,
4,180✔
822
        syslinep: &SyslineP,
4,180✔
823
    ) -> bool {
4,180✔
824
        self.syslinereader
4,180✔
825
            .is_sysline_last(syslinep)
4,180✔
826
    }
4,180✔
827

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

845
        if !self.is_drop_data() {
14✔
846
            def1x!("return false; is_drop_data() is false");
×
847
            return false;
×
848
        }
14✔
849

850
        // `syslinereader.drop_data` is an expensive function, skip if possible.
851
        if blockoffset == self.drop_block_last {
14✔
852
            def1x!("({}) skip block, return true", blockoffset);
5✔
853
            return false;
5✔
854
        }
9✔
855

856
        if self
9✔
857
            .syslinereader
9✔
858
            .drop_data(blockoffset)
9✔
859
        {
860
            self.drop_block_last = blockoffset;
4✔
861
            def1x!("({}) return true", blockoffset);
4✔
862
            return true;
4✔
863
        }
5✔
864

865
        def1x!("({}) return false", blockoffset);
5✔
866
        false
5✔
867
    }
14✔
868

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

890
        let bo_first: BlockOffset = (*syslinep).blockoffset_first();
3,664✔
891
        if bo_first > 1 {
3,664✔
892
            def1ñ!();
14✔
893
            return self.drop_data(bo_first - 2);
14✔
894
        }
3,650✔
895

896
        false
3,650✔
897
    }
3,664✔
898

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

927
        result
88✔
928
    }
88✔
929

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

951
        let result = match self
4,185✔
952
            .syslinereader
4,185✔
953
            .find_sysline_between_datetime_filters(
4,185✔
954
                fileoffset,
4,185✔
955
                &self.filter_dt_after_opt,
4,185✔
956
                &self.filter_dt_before_opt,
4,185✔
957
            ) {
4,185✔
958
            ResultFindSysline::Err(err) => {
×
959
                self.set_error(&err);
×
960

961
                ResultFindSysline::Err(err)
×
962
            }
963
            val => val,
4,185✔
964
        };
965

966
        defx!("({})", fileoffset);
4,185✔
967

968
        result
4,185✔
969
    }
4,185✔
970

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

991
    /// Stage 0 does some sanity checks on the file.
992
    // TODO: this is redundant and has already been performed by functions in
993
    //       `filepreprocessor` and `BlockReader::new`.
994
    pub fn process_stage0_valid_file_check(&mut self) -> FileProcessingResultBlockZero {
380✔
995
        defn!();
380✔
996
        // sanity check calls are in correct order
997
        self.assert_stage(ProcessingStage::Stage0ValidFileCheck);
380✔
998
        self.processingstage = ProcessingStage::Stage0ValidFileCheck;
380✔
999

1000
        if self.filesz() == 0 {
380✔
1001
            defx!("filesz 0; return {:?}", FileProcessingResultBlockZero::FileErrEmpty);
2✔
1002
            return FileProcessingResultBlockZero::FileErrEmpty;
2✔
1003
        }
378✔
1004
        defx!("return {:?}", FileProcessingResultBlockZero::FileOk);
378✔
1005

1006
        FileProcessingResultBlockZero::FileOk
378✔
1007
    }
380✔
1008

1009
    /// Stage 1: Can [`Line`s] and [`Sysline`s] be parsed from the first block
1010
    /// (block zero)?
1011
    ///
1012
    /// [`Sysline`s]: crate::data::sysline::Sysline
1013
    /// [`Line`s]: crate::data::line::Line
1014
    pub fn process_stage1_blockzero_analysis(&mut self) -> FileProcessingResultBlockZero {
377✔
1015
        defn!();
377✔
1016
        self.assert_stage(ProcessingStage::Stage0ValidFileCheck);
377✔
1017
        self.processingstage = ProcessingStage::Stage1BlockzeroAnalysis;
377✔
1018

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

1036
        defx!("return {:?}", result);
269✔
1037

1038
        result
269✔
1039
    }
377✔
1040

1041
    /// Stage 2: Given the an optional datetime filter (user-passed
1042
    /// `--dt-after`), can a log message with a datetime after that filter be
1043
    /// found?
1044
    pub fn process_stage2_find_dt(
238✔
1045
        &mut self,
238✔
1046
        filter_dt_after_opt: &DateTimeLOpt,
238✔
1047
    ) -> FileProcessingResultBlockZero {
238✔
1048
        defn!();
238✔
1049
        self.assert_stage(ProcessingStage::Stage1BlockzeroAnalysis);
238✔
1050
        self.processingstage = ProcessingStage::Stage2FindDt;
238✔
1051

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

1076
        defx!();
238✔
1077

1078
        FileProcessingResultBlockZero::FileOk
238✔
1079
    }
238✔
1080

1081
    /// Stage 3: during "[streaming]", processed and printed data stored by
1082
    /// underlying "Readers" is proactively dropped
1083
    /// (removed from process memory).
1084
    ///
1085
    /// Also see [`find_sysline`].
1086
    ///
1087
    /// [streaming]: ProcessingStage#variant.Stage3StreamSyslines
1088
    /// [`find_sysline`]: self::SyslogProcessor#method.find_sysline
1089
    pub fn process_stage3_stream_syslines(&mut self) -> FileProcessingResultBlockZero {
234✔
1090
        defñ!();
234✔
1091
        self.assert_stage(ProcessingStage::Stage2FindDt);
234✔
1092
        self.processingstage = ProcessingStage::Stage3StreamSyslines;
234✔
1093

1094
        FileProcessingResultBlockZero::FileOk
234✔
1095
    }
234✔
1096

1097
    /// Stage 4: no more [`Sysline`s] to process. Create and return a
1098
    /// [`Summary`].
1099
    ///
1100
    /// [`Summary`]: crate::readers::summary::Summary
1101
    /// [`Sysline`s]: crate::data::sysline::Sysline
1102
    pub fn process_stage4_summary(&mut self) -> Summary {
231✔
1103
        defñ!();
231✔
1104
        // XXX: this can be called from various stages, no need to assert
1105
        self.processingstage = ProcessingStage::Stage4Summary;
231✔
1106

1107
        self.summary_complete()
231✔
1108
    }
231✔
1109

1110
    /// Review bytes in the first block ("zero block").
1111
    /// If enough `Line` found then return [`FileOk`]
1112
    /// else return [`FileErrNoLinesFound`].
1113
    ///
1114
    /// [`FileOk`]: self::FileProcessingResultBlockZero
1115
    /// [`FileErrNoLinesFound`]: self::FileProcessingResultBlockZero
1116
    pub(super) fn blockzero_analysis_bytes(&mut self) -> FileProcessingResultBlockZero {
377✔
1117
        defn!();
377✔
1118
        self.assert_stage(ProcessingStage::Stage1BlockzeroAnalysis);
377✔
1119

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

1153
        defx!("return FileOk");
366✔
1154

1155
        FileProcessingResultBlockZero::FileOk
366✔
1156
    }
377✔
1157

1158
    /// Attempt to find a minimum number of [`Line`s] within the first block
1159
    /// (block zero).
1160
    /// If enough `Line` found then return [`FileOk`]
1161
    /// else return [`FileErrNoLinesFound`].
1162
    ///
1163
    /// [`Line`s]: crate::data::line::Line
1164
    /// [`FileOk`]: self::FileProcessingResultBlockZero
1165
    /// [`FileErrNoLinesFound`]: self::FileProcessingResultBlockZero
1166
    pub(super) fn blockzero_analysis_lines(&mut self) -> FileProcessingResultBlockZero {
366✔
1167
        defn!();
366✔
1168
        self.assert_stage(ProcessingStage::Stage1BlockzeroAnalysis);
366✔
1169

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

1207
                    fo_next
379✔
1208
                }
1209
                (ResultFindLine::Done, partial) => {
27✔
1210
                    if partial.is_some() {
27✔
1211
                        found += 1;
27✔
1212
                        _partial_found = true;
27✔
1213
                    }
27✔
1214
                    break;
27✔
1215
                }
1216
                (ResultFindLine::Err(err), _) => {
×
1217
                    self.set_error(&err);
×
1218
                    defx!("return FileErrIo({:?})", err);
×
1219
                    return FileProcessingResultBlockZero::FileErrIoPath(err);
×
1220
                }
1221
            };
1222
            if 0 != self
379✔
1223
                .syslinereader
379✔
1224
                .linereader
379✔
1225
                .block_offset_at_file_offset(fo)
379✔
1226
            {
1227
                break;
4✔
1228
            }
375✔
1229
        }
1230

1231
        let fpr: FileProcessingResultBlockZero = if found >= found_min {
366✔
1232
            FileProcessingResultBlockZero::FileOk
366✔
1233
        } else {
1234
            FileProcessingResultBlockZero::FileErrNoLinesFound
×
1235
        };
1236

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

1239
        fpr
366✔
1240
    }
366✔
1241

1242
    /// Attempt to find a minimum number of [`Sysline`] within the first block.
1243
    /// If enough `Sysline` found then return [`FileOk`]
1244
    /// else return [`FileErrNoSyslinesFound`].
1245
    ///
1246
    /// [`Sysline`]: crate::data::sysline::Sysline
1247
    /// [`FileOk`]: self::FileProcessingResultBlockZero
1248
    /// [`FileErrNoSyslinesFound`]: self::FileProcessingResultBlockZero
1249
    pub(super) fn blockzero_analysis_syslines(&mut self) -> FileProcessingResultBlockZero {
366✔
1250
        defn!();
366✔
1251
        self.assert_stage(ProcessingStage::Stage1BlockzeroAnalysis);
366✔
1252

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

1280
        // find `at_max` Syslines within block zero
1281
        while found < found_min
647✔
1282
            && self.syslinereader.block_offset_at_file_offset(fo) == 0
386✔
1283
        {
1284
            fo = match self
386✔
1285
                .syslinereader
386✔
1286
                .find_sysline_in_block(fo)
386✔
1287
            {
1288
                (ResultFindSysline::Found((fo_next, _slinep)), _) => {
281✔
1289
                    found += 1;
281✔
1290
                    defo!("Found; found {} syslines, fo_next {}", found, fo_next);
281✔
1291

1292
                    fo_next
281✔
1293
                }
1294
                (ResultFindSysline::Done, partial_found) => {
105✔
1295
                    defo!("Done; found {} syslines, partial_found {}", found, partial_found);
105✔
1296
                    if partial_found {
105✔
1297
                        found += 1;
8✔
1298
                    }
97✔
1299
                    break;
105✔
1300
                }
1301
                (ResultFindSysline::Err(err), _) => {
×
1302
                    self.set_error(&err);
×
1303
                    defx!("return FileErrIo({:?})", err);
×
1304
                    return FileProcessingResultBlockZero::FileErrIoPath(err);
×
1305
                }
1306
            };
1307
        }
1308

1309
        if found == 0 {
366✔
1310
            defx!("found {} syslines, require {} syslines, return FileErrNoSyslinesFound", found, found_min);
97✔
1311
            return FileProcessingResultBlockZero::FileErrNoSyslinesFound;
97✔
1312
        }
269✔
1313

1314
        let patt_count_a = self.syslinereader.dt_patterns_counts_in_use();
269✔
1315
        defo!("dt_patterns_counts_in_use {}", patt_count_a);
269✔
1316

1317
        if !self.syslinereader.dt_patterns_analysis() {
269✔
1318
            de_err!("dt_patterns_analysis() failed which is unexpected; return FileErrNoSyslinesFound");
×
1319
            return FileProcessingResultBlockZero::FileErrNoSyslinesFound;
×
1320
        }
269✔
1321

1322
        let _patt_count_b = self.syslinereader.dt_patterns_counts_in_use();
269✔
1323
        debug_assert_eq!(
269✔
1324
            _patt_count_b,
1325
            SyslogProcessor::DT_PATTERN_MAX,
1326
            "expected patterns to be reduced to {}, found {:?}",
1327
            SyslogProcessor::DT_PATTERN_MAX,
1328
            _patt_count_b,
1329
        );
1330

1331
        // if more than one `DateTimeParseInstr` was used then the syslines
1332
        // must be reparsed using the one chosen `DateTimeParseInstr`
1333
        if patt_count_a > 1 {
269✔
1334
            defo!("must reprocess all syslines using limited patterns (used {} DateTimeParseInstr; must only use {})!", patt_count_a, 1);
8✔
1335

1336
            self.syslinereader.clear_syslines();
8✔
1337
            // find `at_max` Syslines within block zero
1338
            found = 0;
8✔
1339
            fo = 0;
8✔
1340
            while found < found_min
11✔
1341
                && self.syslinereader.block_offset_at_file_offset(fo) == 0
8✔
1342
            {
1343
                fo = match self
8✔
1344
                    .syslinereader
8✔
1345
                    .find_sysline_in_block(fo)
8✔
1346
                {
1347
                    (ResultFindSysline::Found((fo_next, _slinep)), _) => {
3✔
1348
                        found += 1;
3✔
1349
                        defo!("Found; found {} syslines, fo_next {}", found, fo_next);
3✔
1350

1351
                        fo_next
3✔
1352
                    }
1353
                    (ResultFindSysline::Done, partial_found) => {
5✔
1354
                        defo!("Done; found {} syslines, partial_found {}", found, partial_found);
5✔
1355
                        if partial_found {
5✔
1356
                            found += 1;
5✔
1357
                        }
5✔
1358
                        break;
5✔
1359
                    }
1360
                    (ResultFindSysline::Err(err), _) => {
×
1361
                        self.set_error(&err);
×
1362
                        defx!("return FileErrIo({:?})", err);
×
1363
                        return FileProcessingResultBlockZero::FileErrIoPath(err);
×
1364
                    }
1365
                };
1366
            }
1367
            defo!("done reprocessing.");
8✔
1368
        } else {
1369
            defo!("no reprocess needed ({} DateTimeParseInstr)!", patt_count_a);
261✔
1370
        }
1371

1372
        let fpr: FileProcessingResultBlockZero = match found >= found_min {
269✔
1373
            true => FileProcessingResultBlockZero::FileOk,
269✔
1374
            false => FileProcessingResultBlockZero::FileErrNoSyslinesFound,
×
1375
        };
1376

1377
        // sanity check that only one `DateTimeParseInstr` is in use
1378
        if cfg!(debug_assertions) && self.syslinereader.dt_patterns_counts_in_use() != 1 {
269✔
1379
            de_wrn!(
×
1380
                "dt_patterns_counts_in_use() = {}, expected 1; for {:?}",
×
1381
                self.syslinereader.dt_patterns_counts_in_use(), self.path()
×
1382
            );
×
1383
        }
269✔
1384

1385
        if self.syslinereader.is_streamed_file()
269✔
1386
            && !self.syslinereader.dt_pattern_has_year()
50✔
1387
        {
1388
            self.syslinereader.linereader.blockreader.disable_drop_data();
×
1389
            debug_assert!(!self.is_drop_data(), "is_drop_data() should be false");
×
1390
        }
269✔
1391

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

1394
        fpr
269✔
1395
    }
366✔
1396

1397
    /// Call `self.blockzero_analysis_lines`.
1398
    /// If that passes then call `self.blockzero_analysis_syslines`.
1399
    pub(super) fn blockzero_analysis(&mut self) -> FileProcessingResultBlockZero {
377✔
1400
        defn!();
377✔
1401
        assert!(!self.blockzero_analysis_done, "blockzero_analysis_lines should only be completed once.");
377✔
1402
        self.blockzero_analysis_done = true;
377✔
1403
        self.assert_stage(ProcessingStage::Stage1BlockzeroAnalysis);
377✔
1404

1405
        if self.syslinereader.filesz() == 0 {
377✔
1406
            defx!("return FileErrEmpty");
×
1407
            return FileProcessingResultBlockZero::FileErrEmpty;
×
1408
        }
377✔
1409

1410
        let result: FileProcessingResultBlockZero = self.blockzero_analysis_bytes();
377✔
1411
        if !result.is_ok() {
377✔
1412
            defx!("syslinereader.blockzero_analysis_bytes() was !is_ok(), return {:?}", result);
11✔
1413
            return result;
11✔
1414
        };
366✔
1415

1416
        let result: FileProcessingResultBlockZero = self.blockzero_analysis_lines();
366✔
1417
        if !result.is_ok() {
366✔
1418
            defx!("syslinereader.blockzero_analysis() was !is_ok(), return {:?}", result);
×
1419
            return result;
×
1420
        };
366✔
1421

1422
        let result: FileProcessingResultBlockZero = self.blockzero_analysis_syslines();
366✔
1423
        defx!("return {:?}", result);
366✔
1424

1425
        result
366✔
1426
    }
377✔
1427

1428
    #[cfg(test)]
1429
    pub(crate) fn dropped_blocks(&self) -> SetDroppedBlocks {
3✔
1430
        self.syslinereader
3✔
1431
            .linereader
3✔
1432
            .blockreader
3✔
1433
            .dropped_blocks
3✔
1434
            .clone()
3✔
1435
    }
3✔
1436

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

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

1452
    pub fn summary(&self) -> SummarySyslogProcessor {
537✔
1453
        let syslogprocessor_missing_year = self.missing_year;
537✔
1454

1455
        SummarySyslogProcessor {
537✔
1456
            syslogprocessor_missing_year,
537✔
1457
        }
537✔
1458
    }
537✔
1459

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

1477
        Summary::new(
534✔
1478
            path,
534✔
1479
            path_ntf,
534✔
1480
            filetype,
534✔
1481
            logmessagetype,
534✔
1482
            Some(summaryblockreader),
534✔
1483
            Some(summarylinereader),
534✔
1484
            Some(summarysyslinereader),
534✔
1485
            Some(summarysyslogprocessor),
534✔
1486
            None,
534✔
1487
            None,
534✔
1488
            None,
534✔
1489
            None,
534✔
1490
            error,
534✔
1491
        )
1492
    }
534✔
1493
}
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