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

jtmoon79 / super-speedy-syslog-searcher / 30326158672

28 Jul 2026 03:31AM UTC coverage: 70.857% (+1.9%) from 68.982%
30326158672

push

github

jtmoon79
(LIB) bump macro-string 0.3.0

19964 of 28175 relevant lines covered (70.86%)

1699356.33 hits per line

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

66.94
/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 ::more_asserts::debug_assert_le;
38
use ::rangemap::RangeMap;
39
use ::si_trace_print::{
40
    def1n,
41
    def1x,
42
    def1ñ,
43
    def2ñ,
44
    defn,
45
    defo,
46
    defx,
47
    defñ,
48
};
49

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

106
// ---------------
107
// SyslogProcessor
108

109
/// `SYSLOG_SZ_MAX` as a `BlockSz`.
110
pub(crate) const SYSLOG_SZ_MAX_BSZ: BlockSz = SYSLOG_SZ_MAX as BlockSz;
111

112
/// Typed [`FileProcessingResult`] for "block zero analysis".
113
///
114
/// [`FileProcessingResult`]: crate::common::FileProcessingResult
115
pub type FileProcessingResultBlockZero = FileProcessingResult<std::io::Error>;
116

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

159
/// [`BlockSz`] in a [`Range`].
160
///
161
/// [`Range`]: std::ops::Range
162
/// [`BlockSz`]: crate::readers::blockreader::BlockSz
163
type BszRange = std::ops::Range<BlockSz>;
164

165
/// Map [`BlockSz`] to a [`Count`].
166
///
167
/// [`BlockSz`]: crate::readers::blockreader::BlockSz
168
/// [`Count`]: crate::common::Count
169
type MapBszRangeToCount = RangeMap<u64, Count>;
170

171
lazy_static! {
172
    /// For files in `blockzero_analyis`, the number of [`Line`]s needed to
173
    /// be found within block zero.
174
    ///
175
    /// [`Line`]: crate::data::line::Line
176
    pub static ref BLOCKZERO_ANALYSIS_LINE_COUNT_MIN_MAP: MapBszRangeToCount = {
177
        defñ!("lazy_static! BLOCKZERO_ANALYSIS_LINE_COUNT_MIN_MAP::new()");
178

179
        let mut m = MapBszRangeToCount::new();
180
        m.insert(BszRange{start: 0, end: SYSLOG_SZ_MAX_BSZ}, 1);
181
        m.insert(BszRange{start: SYSLOG_SZ_MAX_BSZ, end: SYSLOG_SZ_MAX_BSZ * 3}, 3);
182
        m.insert(BszRange{start: SYSLOG_SZ_MAX_BSZ * 3, end: BlockSz::MAX}, 3);
183

184
        m
185
    };
186

187
    /// For files in `blockzero_analyis`, the number of [`Sysline`]s needed to
188
    /// be found within block zero.
189
    ///
190
    /// [`Sysline`]: crate::data::sysline::Sysline
191
    pub static ref BLOCKZERO_ANALYSIS_SYSLINE_COUNT_MIN_MAP: MapBszRangeToCount = {
192
        defñ!("lazy_static! BLOCKZERO_ANALYSIS_SYSLINE_COUNT_MIN_MAP::new()");
193

194
        let mut m = MapBszRangeToCount::new();
195
        m.insert(BszRange{start: 0, end: SYSLOG_SZ_MAX_BSZ}, 1);
196
        m.insert(BszRange{start: SYSLOG_SZ_MAX_BSZ, end: BlockSz::MAX}, 2);
197

198
        m
199
    };
200
}
201

202

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

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

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

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

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

300
    /// For testing purposes, must enforce a minimum [`BlockSz`].
301
    /// Necessary for `blockzero_analysis` functions to have chance at success.
302
    #[cfg(not(any(debug_assertions, test)))]
303
    pub const BLOCKSZ_MIN: BlockSz = 0x40;
304
    #[doc(hidden)]
305
    #[cfg(any(debug_assertions, test))]
306
    pub const BLOCKSZ_MIN: BlockSz = crate::readers::blockreader::BLOCKSZ_MIN;
307

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

319
    /// If the first number of bytes are zero bytes (NULL bytes) then
320
    /// stop processing the file. It's extremely unlikely this is a syslog
321
    /// file and more likely it's some sort of binary data file.
322
    pub const BLOCKZERO_ANALYSIS_BYTES_NULL_MAX: usize = 128;
323
    /// Same as [`SyslogProcessor::BLOCKZERO_ANALYSIS_BYTES_NULL_MAX`] but for 0xFF bytes.
324
    pub const BLOCKZERO_ANALYSIS_BYTES_FF_MAX: usize = Self::BLOCKZERO_ANALYSIS_BYTES_NULL_MAX;
325

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

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

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

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

379
        def1x!("return Ok(SyslogProcessor)");
483✔
380

381
        Result::Ok(SyslogProcessor {
483✔
382
            syslinereader: slr,
483✔
383
            processingstage: ProcessingStage::Stage0ValidFileCheck,
483✔
384
            tz_offset,
483✔
385
            filter_dt_after_opt,
483✔
386
            filter_dt_before_opt,
483✔
387
            blockzero_analysis_done: false,
483✔
388
            drop_block_last: 0,
483✔
389
            missing_year: None,
483✔
390
            error: None,
483✔
391
        })
483✔
392
    }
485✔
393

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

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

413
    /// See [`BlockReader::blocksz`].
414
    ///
415
    /// [`BlockReader::blocksz`]: crate::readers::blockreader::BlockReader#method.blocksz
416
    #[inline(always)]
417
    pub const fn blocksz(&self) -> BlockSz {
873✔
418
        self.syslinereader.blocksz()
873✔
419
    }
873✔
420

421
    /// See [`BlockReader::path_id`].
422
    ///
423
    /// [`BlockReader::path_id`]: crate::readers::blockreader::BlockReader#method.path_id
424
    #[inline(always)]
425
    pub const fn path_id(&self) -> PathId {
483✔
426
        self.syslinereader.path_id()
483✔
427
    }
483✔
428

429
    /// See [`BlockReader::filesz`].
430
    ///
431
    /// [`BlockReader::filesz`]: crate::readers::blockreader::BlockReader#method.filesz
432
    #[inline(always)]
433
    pub const fn filesz(&self) -> FileSz {
476✔
434
        self.syslinereader.filesz()
476✔
435
    }
476✔
436

437
    /// See [`BlockReader::filetype`].
438
    ///
439
    /// [`BlockReader::filetype`]: crate::readers::blockreader::BlockReader#method.filetype
440
    #[inline(always)]
441
    pub const fn filetype(&self) -> FileType {
1,113✔
442
        self.syslinereader.filetype()
1,113✔
443
    }
1,113✔
444

445
    /// See [`BlockReader::path`].
446
    ///
447
    /// [`BlockReader::path`]: crate::readers::blockreader::BlockReader#method.path
448
    #[inline(always)]
449
    #[allow(dead_code)]
450
    pub const fn path(&self) -> &FPath {
1,604✔
451
        self.syslinereader.path()
1,604✔
452
    }
1,604✔
453

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

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

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

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

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

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

521
    /// See [`BlockReader::fileoffset_last`].
522
    ///
523
    /// [`BlockReader::fileoffset_last`]: crate::readers::blockreader::BlockReader#method.fileoffset_last
524
    pub const fn fileoffset_last(&self) -> FileOffset {
15✔
525
        self.syslinereader
15✔
526
            .fileoffset_last()
15✔
527
    }
15✔
528

529
    /// See [`LineReader::charsz`].
530
    ///
531
    /// [`LineReader::charsz`]: crate::readers::linereader::LineReader#method.charsz
532
    #[allow(dead_code)]
533
    pub const fn charsz(&self) -> CharSz {
15✔
534
        self.syslinereader.charsz()
15✔
535
    }
15✔
536

537
    /// See [`BlockReader::mtime`].
538
    ///
539
    /// [`BlockReader::mtime`]: crate::readers::blockreader::BlockReader#method.mtime
540
    pub fn mtime(&self) -> SystemTime {
414✔
541
        self.syslinereader.mtime()
414✔
542
    }
414✔
543

544
    /// Did this `SyslogProcessor` run `process_missing_year()` ?
545
    fn did_process_missing_year(&self) -> bool {
415✔
546
        self.missing_year.is_some()
415✔
547
    }
415✔
548

549
    /// Did this `SyslogProcessor` run `process_uptime()` ?
550
    fn did_process_uptime(&self) -> bool {
×
551
        self.systemtime_at_uptime_zero().is_some()
×
552
    }
×
553

554
    /// Return `drop_data` value.
555
    pub const fn is_drop_data(&self) -> bool {
3,218✔
556
        self.syslinereader.is_drop_data()
3,218✔
557
    }
3,218✔
558

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

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

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

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

735
        FileProcessingResultBlockZero::FileOk
15✔
736
    }
15✔
737

738
    fn systemtime_at_uptime_zero(&self) -> Option<SystemTime>{
×
739
        self.syslinereader.systemtime_at_uptime_zero
×
740
    }
×
741

742
    pub fn process_uptime(
×
743
        &mut self,
×
744
    ) -> FileProcessingResultBlockZero {
×
745
        defn!();
×
746
        debug_assert!(!self.did_process_uptime(), "did_process_uptime() must only be called once");
×
747

748
        let fo_last = self.fileoffset_last();
×
749
        defo!("find_sysline(fo_last={})", fo_last);
×
750
        let syslinep = match self.find_sysline(fo_last) {
×
751
            ResultFindSysline::Found((_fo, syslinep_)) => {
×
752
                defo!("found sysline at fo_last={} {:?}", fo_last, syslinep_);
×
753

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

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

822
        defx!("return FileOk");
×
823

824
        FileProcessingResultBlockZero::FileOk
×
825
    }
×
826

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

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

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

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

866
        if self
9✔
867
            .syslinereader
9✔
868
            .drop_data(blockoffset)
9✔
869
        {
870
            self.drop_block_last = blockoffset;
6✔
871
            def1x!("({}) return true", blockoffset);
6✔
872
            return true;
6✔
873
        }
3✔
874

875
        def1x!("({}) return false", blockoffset);
3✔
876
        false
3✔
877
    }
14✔
878

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

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

906
        false
3,190✔
907
    }
3,204✔
908

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

937
        result
40✔
938
    }
40✔
939

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

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

971
                ResultFindSysline::Err(err)
×
972
            }
973
            val => val,
3,975✔
974
        };
975

976
        defx!("({})", fileoffset);
3,975✔
977

978
        result
3,975✔
979
    }
3,975✔
980

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

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

1010
        if self.filesz() == 0 {
476✔
1011
            defx!("filesz 0; return {:?}", FileProcessingResultBlockZero::FileErrEmpty);
2✔
1012
            return FileProcessingResultBlockZero::FileErrEmpty;
2✔
1013
        }
474✔
1014
        defx!("return {:?}", FileProcessingResultBlockZero::FileOk);
474✔
1015

1016
        FileProcessingResultBlockZero::FileOk
474✔
1017
    }
476✔
1018

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

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

1046
        defx!("return {:?}", result);
345✔
1047

1048
        result
345✔
1049
    }
473✔
1050

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

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

1086
        defx!();
318✔
1087

1088
        FileProcessingResultBlockZero::FileOk
318✔
1089
    }
318✔
1090

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

1105
        FileProcessingResultBlockZero::FileOk
314✔
1106
    }
314✔
1107

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

1118
        self.summary_complete()
311✔
1119
    }
311✔
1120

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

1131
        let blockp: BlockP = match self
473✔
1132
            .syslinereader
473✔
1133
            .linereader
473✔
1134
            .blockreader
473✔
1135
            .read_block(0)
473✔
1136
        {
1137
            ResultFindReadBlock::Found(blockp_) => blockp_,
473✔
1138
            ResultFindReadBlock::Done => {
×
1139
                defx!("return FileErrEmpty");
×
1140
                return FileProcessingResultBlockZero::FileErrEmpty;
×
1141
            }
1142
            ResultFindReadBlock::Err(err) => {
×
1143
                self.set_error(&err);
×
1144
                defx!("return FileErrIo({:?})", err);
×
1145
                return FileProcessingResultBlockZero::FileErrIoPath(err);
×
1146
            }
1147
        };
1148
        // if the first block is too small then not a valid log file
1149
        let blocksz0: BlockSz = (*blockp).len() as BlockSz;
473✔
1150
        let require_sz: BlockSz = std::cmp::min(Self::BLOCKZERO_ANALYSIS_BYTES_MIN, self.blocksz());
473✔
1151
        defo!("blocksz0 {} < {} require_sz", blocksz0, require_sz);
473✔
1152
        if blocksz0 < require_sz {
473✔
1153
            defx!("return FileErrTooSmall");
9✔
1154
            return FileProcessingResultBlockZero::FileErrTooSmall;
9✔
1155
        }
464✔
1156
        // if all 0x00 bytes then not valid log file
1157
        if (*blockp).iter().take(Self::BLOCKZERO_ANALYSIS_BYTES_NULL_MAX).all(|&b| b == 0) {
666✔
1158
            defx!("return FileErrNullBytes");
2✔
1159
            return FileProcessingResultBlockZero::FileErrNullBytes;
2✔
1160
        }
462✔
1161
        // if all 0xFF bytes then not valid log file
1162
        if (*blockp).iter().take(Self::BLOCKZERO_ANALYSIS_BYTES_FF_MAX).all(|&b| b == 0xFF) {
482✔
1163
            defx!("return FileErrFFBytes");
×
1164
            return FileProcessingResultBlockZero::FileErrFFBytes;
×
1165
        }
462✔
1166
        // determine file encoding
1167
        let block_bytes = blockp.as_slice();
462✔
1168
        let encoding_type: FileTypeTextEncoding = match detect_filetype_text_encoding(block_bytes) {
462✔
1169
            Some(enc) => {
462✔
1170
                defo!("detected encoding {:?}", enc);
462✔
1171
                enc
462✔
1172
            },
1173
            None => {
1174
                defo!("could not detect valid encoding; fallback to UTF-8/ASCII");
×
1175
                FileTypeTextEncoding::Utf8Ascii
×
1176
            }
1177
        };
1178

1179
        // TODO: here is where to detect magic bytes for
1180
        //       unsupported file types, e.g. databases, unsupported compressed, etc.
1181

1182
        self.syslinereader.filetype_text_encoding_update(encoding_type);
462✔
1183

1184
        defx!("return FileOk");
462✔
1185

1186
        FileProcessingResultBlockZero::FileOk
462✔
1187
    }
473✔
1188

1189
    /// Attempt to find a minimum number of [`Line`s] within the first block
1190
    /// (block zero).
1191
    /// If enough `Line` found then return [`FileOk`]
1192
    /// else return [`FileErrNoLinesFound`].
1193
    ///
1194
    /// [`Line`s]: crate::data::line::Line
1195
    /// [`FileOk`]: self::FileProcessingResultBlockZero
1196
    /// [`FileErrNoLinesFound`]: self::FileProcessingResultBlockZero
1197
    pub(super) fn blockzero_analysis_lines(&mut self) -> FileProcessingResultBlockZero {
462✔
1198
        defn!();
462✔
1199
        self.assert_stage(ProcessingStage::Stage1BlockzeroAnalysis);
462✔
1200

1201
        let blockp: BlockP = match self
462✔
1202
            .syslinereader
462✔
1203
            .linereader
462✔
1204
            .blockreader
462✔
1205
            .read_block(0)
462✔
1206
        {
1207
            ResultFindReadBlock::Found(blockp_) => blockp_,
462✔
1208
            ResultFindReadBlock::Done => {
×
1209
                defx!("return FileErrEmpty");
×
1210
                return FileProcessingResultBlockZero::FileErrEmpty;
×
1211
            }
1212
            ResultFindReadBlock::Err(err) => {
×
1213
                self.set_error(&err);
×
1214
                defx!("return FileErrIo({:?})", err);
×
1215
                return FileProcessingResultBlockZero::FileErrIoPath(err);
×
1216
            }
1217
        };
1218
        let blocksz0: BlockSz = (*blockp).len() as BlockSz;
462✔
1219
        let mut _partial_found = false;
462✔
1220
        let mut fo: FileOffset = 0;
462✔
1221
        // how many lines have been found?
1222
        let mut found: Count = 0;
462✔
1223
        // must find at least this many lines in block zero to be FileOk
1224
        let found_min: Count = *BLOCKZERO_ANALYSIS_LINE_COUNT_MIN_MAP
462✔
1225
            .get(&blocksz0)
462✔
1226
            .unwrap();
462✔
1227
        defx!("block zero blocksz {} found_min {}", blocksz0, found_min);
462✔
1228
        // find `found_min` Lines or whatever can be found within block 0
1229
        while found < found_min {
936✔
1230
            fo = match self
502✔
1231
                .syslinereader
502✔
1232
                .linereader
502✔
1233
                .find_line_in_block(fo)
502✔
1234
            {
1235
                (ResultFindLine::Found((fo_next, _linep)), _) => {
475✔
1236
                    found += 1;
475✔
1237

1238
                    fo_next
475✔
1239
                }
1240
                (ResultFindLine::Done, partial) => {
27✔
1241
                    if partial.is_some() {
27✔
1242
                        found += 1;
27✔
1243
                        _partial_found = true;
27✔
1244
                    }
27✔
1245
                    break;
27✔
1246
                }
1247
                (ResultFindLine::Err(err), _) => {
×
1248
                    self.set_error(&err);
×
1249
                    defx!("return FileErrIo({:?})", err);
×
1250
                    return FileProcessingResultBlockZero::FileErrIoPath(err);
×
1251
                }
1252
            };
1253
            if 0 != self
475✔
1254
                .syslinereader
475✔
1255
                .linereader
475✔
1256
                .block_offset_at_file_offset(fo)
475✔
1257
            {
1258
                break;
1✔
1259
            }
474✔
1260
        }
1261

1262
        let fpr: FileProcessingResultBlockZero = if found >= found_min {
462✔
1263
            FileProcessingResultBlockZero::FileOk
462✔
1264
        } else {
1265
            FileProcessingResultBlockZero::FileErrNoLinesFound
×
1266
        };
1267

1268
        defx!("found {} lines, partial_found {}, require {} lines, return {:?}", found, _partial_found, found_min, fpr);
462✔
1269

1270
        fpr
462✔
1271
    }
462✔
1272

1273
    /// Attempt to find a minimum number of [`Sysline`] within the first block.
1274
    /// If enough `Sysline` found then return [`FileOk`]
1275
    /// else return [`FileErrNoSyslinesFound`].
1276
    ///
1277
    /// [`Sysline`]: crate::data::sysline::Sysline
1278
    /// [`FileOk`]: self::FileProcessingResultBlockZero
1279
    /// [`FileErrNoSyslinesFound`]: self::FileProcessingResultBlockZero
1280
    pub(super) fn blockzero_analysis_syslines(&mut self) -> FileProcessingResultBlockZero {
462✔
1281
        defn!();
462✔
1282
        self.assert_stage(ProcessingStage::Stage1BlockzeroAnalysis);
462✔
1283

1284
        let blockp: BlockP = match self
462✔
1285
            .syslinereader
462✔
1286
            .linereader
462✔
1287
            .blockreader
462✔
1288
            .read_block(0)
462✔
1289
        {
1290
            ResultFindReadBlock::Found(blockp_) => blockp_,
462✔
1291
            ResultFindReadBlock::Done => {
×
1292
                defx!("return FileErrEmpty");
×
1293
                return FileProcessingResultBlockZero::FileErrEmpty;
×
1294
            }
1295
            ResultFindReadBlock::Err(err) => {
×
1296
                self.set_error(&err);
×
1297
                defx!("return FileErrIo({:?})", err);
×
1298
                return FileProcessingResultBlockZero::FileErrIoPath(err);
×
1299
            }
1300
        };
1301
        let blocksz0: BlockSz = (*blockp).len() as BlockSz;
462✔
1302
        let mut fo: FileOffset = 0;
462✔
1303
        // how many syslines have been found?
1304
        let mut found: Count = 0;
462✔
1305
        // must find at least this many syslines in block zero to be FileOk
1306
        let found_min: Count = *BLOCKZERO_ANALYSIS_SYSLINE_COUNT_MIN_MAP
462✔
1307
            .get(&blocksz0)
462✔
1308
            .unwrap();
462✔
1309
        defo!("block zero blocksz {} found_min {:?}", blocksz0, found_min);
462✔
1310

1311
        // find `at_max` Syslines within block zero
1312
        while found < found_min
817✔
1313
            && self.syslinereader.block_offset_at_file_offset(fo) == 0
482✔
1314
        {
1315
            fo = match self
482✔
1316
                .syslinereader
482✔
1317
                .find_sysline_in_block(fo)
482✔
1318
            {
1319
                (ResultFindSysline::Found((fo_next, _slinep)), _) => {
355✔
1320
                    found += 1;
355✔
1321
                    defo!("Found; found {} syslines, fo_next {}", found, fo_next);
355✔
1322

1323
                    fo_next
355✔
1324
                }
1325
                (ResultFindSysline::Done, partial_found) => {
127✔
1326
                    defo!("Done; found {} syslines, partial_found {}", found, partial_found);
127✔
1327
                    if partial_found
127✔
1328
                        && (self.syslinereader.count_lines_stored() > 0
10✔
1329
                            || self.syslinereader.charsz() > 1)
×
1330
                    {
10✔
1331
                        found += 1;
10✔
1332
                    }
117✔
1333
                    break;
127✔
1334
                }
1335
                (ResultFindSysline::Err(err), _) => {
×
1336
                    self.set_error(&err);
×
1337
                    defx!("return FileErrIo({:?})", err);
×
1338
                    return FileProcessingResultBlockZero::FileErrIoPath(err);
×
1339
                }
1340
            };
1341
        }
1342

1343
        if found == 0 {
462✔
1344
            defx!("found {} syslines, require {} syslines, return FileErrNoSyslinesFound", found, found_min);
117✔
1345
            return FileProcessingResultBlockZero::FileErrNoSyslinesFound;
117✔
1346
        }
345✔
1347

1348
        let patt_count_a = self.syslinereader.dt_patterns_counts_in_use();
345✔
1349
        defo!("dt_patterns_counts_in_use {}", patt_count_a);
345✔
1350

1351
        if patt_count_a == 0 && self.syslinereader.charsz() > 1 {
345✔
1352
            // For UTF-16/UTF-32 with small block sizes, block zero may only
1353
            // produce a partial line and no complete datetime match yet.
1354
            // Defer datetime pattern narrowing to later full-file processing.
1355
            defo!("multibyte block-zero partial detected; skip dt_patterns_analysis and continue");
×
1356
            return FileProcessingResultBlockZero::FileOk;
×
1357
        }
345✔
1358

1359
        if !self.syslinereader.dt_patterns_analysis() {
345✔
1360
            de_err!("dt_patterns_analysis() failed which is unexpected; return FileErrNoSyslinesFound");
×
1361
            return FileProcessingResultBlockZero::FileErrNoSyslinesFound;
×
1362
        }
345✔
1363

1364
        let _patt_count_b = self.syslinereader.dt_patterns_counts_in_use();
345✔
1365
        debug_assert_le!(
345✔
1366
            _patt_count_b,
1367
            SyslogProcessor::DT_PATTERN_MAX,
1368
            "expected patterns to be reduced to {}, found {:?}",
1369
            SyslogProcessor::DT_PATTERN_MAX,
1370
            _patt_count_b,
1371
        );
1372

1373
        // if more than one `DateTimeParseInstr` was used then the syslines
1374
        // must be reparsed using the one chosen `DateTimeParseInstr`
1375
        if patt_count_a > 1 {
345✔
1376
            defo!("must reprocess all syslines using limited patterns (used {} DateTimeParseInstr; must only use {})!", patt_count_a, 1);
8✔
1377

1378
            self.syslinereader.clear_syslines();
8✔
1379
            // find `at_max` Syslines within block zero
1380
            found = 0;
8✔
1381
            fo = 0;
8✔
1382
            while found < found_min
16✔
1383
                && self.syslinereader.block_offset_at_file_offset(fo) == 0
8✔
1384
            {
1385
                fo = match self
8✔
1386
                    .syslinereader
8✔
1387
                    .find_sysline_in_block(fo)
8✔
1388
                {
1389
                    (ResultFindSysline::Found((fo_next, _slinep)), _) => {
8✔
1390
                        found += 1;
8✔
1391
                        defo!("Found; found {} syslines, fo_next {}", found, fo_next);
8✔
1392

1393
                        fo_next
8✔
1394
                    }
1395
                    (ResultFindSysline::Done, partial_found) => {
×
1396
                        defo!("Done; found {} syslines, partial_found {}", found, partial_found);
×
1397
                        if partial_found
×
1398
                            && (self.syslinereader.count_lines_stored() > 0
×
1399
                                || self.syslinereader.charsz() > 1)
×
1400
                        {
×
1401
                            found += 1;
×
1402
                        }
×
1403
                        break;
×
1404
                    }
1405
                    (ResultFindSysline::Err(err), _) => {
×
1406
                        self.set_error(&err);
×
1407
                        defx!("return FileErrIo({:?})", err);
×
1408
                        return FileProcessingResultBlockZero::FileErrIoPath(err);
×
1409
                    }
1410
                };
1411
            }
1412
            defo!("done reprocessing.");
8✔
1413
        } else {
1414
            defo!("no reprocess needed ({} DateTimeParseInstr)!", patt_count_a);
337✔
1415
        }
1416

1417
        let fpr: FileProcessingResultBlockZero = match found >= found_min {
345✔
1418
            true => FileProcessingResultBlockZero::FileOk,
345✔
1419
            false => FileProcessingResultBlockZero::FileErrNoSyslinesFound,
×
1420
        };
1421

1422
        // sanity check that only one `DateTimeParseInstr` is in use
1423
        if cfg!(debug_assertions) && self.syslinereader.dt_patterns_counts_in_use() != 1 {
345✔
1424
            de_wrn!(
8✔
1425
                "dt_patterns_counts_in_use() = {}, expected 1; for {:?}",
8✔
1426
                self.syslinereader.dt_patterns_counts_in_use(), self.path()
8✔
1427
            );
8✔
1428
        }
337✔
1429

1430
        if self.syslinereader.is_streamed_file()
345✔
1431
            && !self.syslinereader.dt_pattern_has_year()
50✔
1432
        {
1433
            self.syslinereader.linereader.blockreader.disable_drop_data();
×
1434
            debug_assert!(!self.is_drop_data(), "is_drop_data() should be false");
×
1435
        }
345✔
1436

1437
        defx!("found {} syslines, require {} syslines, return {:?}", found, found_min, fpr);
345✔
1438

1439
        fpr
345✔
1440
    }
462✔
1441

1442
    /// Call `self.blockzero_analysis_lines`.
1443
    /// If that passes then call `self.blockzero_analysis_syslines`.
1444
    pub(super) fn blockzero_analysis(&mut self) -> FileProcessingResultBlockZero {
473✔
1445
        defn!();
473✔
1446
        assert!(!self.blockzero_analysis_done, "blockzero_analysis_lines should only be completed once.");
473✔
1447
        self.blockzero_analysis_done = true;
473✔
1448
        self.assert_stage(ProcessingStage::Stage1BlockzeroAnalysis);
473✔
1449

1450
        if self.syslinereader.filesz() == 0 {
473✔
1451
            defx!("return FileErrEmpty");
×
1452
            return FileProcessingResultBlockZero::FileErrEmpty;
×
1453
        }
473✔
1454

1455
        let result: FileProcessingResultBlockZero = self.blockzero_analysis_bytes();
473✔
1456
        if !result.is_ok() {
473✔
1457
            defx!("syslinereader.blockzero_analysis_bytes() was !is_ok(), return {:?}", result);
11✔
1458
            return result;
11✔
1459
        };
462✔
1460

1461
        let result: FileProcessingResultBlockZero = self.blockzero_analysis_lines();
462✔
1462
        if !result.is_ok() {
462✔
1463
            defx!("syslinereader.blockzero_analysis() was !is_ok(), return {:?}", result);
×
1464
            return result;
×
1465
        };
462✔
1466

1467
        let result: FileProcessingResultBlockZero = self.blockzero_analysis_syslines();
462✔
1468
        defx!("return {:?}", result);
462✔
1469

1470
        result
462✔
1471
    }
473✔
1472

1473
    #[cfg(test)]
1474
    pub(crate) fn dropped_blocks(&self) -> SetDroppedBlocks {
3✔
1475
        self.syslinereader
3✔
1476
            .linereader
3✔
1477
            .blockreader
3✔
1478
            .dropped_blocks
3✔
1479
            .clone()
3✔
1480
    }
3✔
1481

1482
    #[cfg(test)]
1483
    pub(crate) fn dropped_lines(&self) -> SetDroppedLines {
3✔
1484
        self.syslinereader
3✔
1485
            .linereader
3✔
1486
            .dropped_lines
3✔
1487
            .clone()
3✔
1488
    }
3✔
1489

1490
    #[cfg(test)]
1491
    pub(crate) fn dropped_syslines(&self) -> SetDroppedSyslines {
3✔
1492
        self.syslinereader
3✔
1493
            .dropped_syslines
3✔
1494
            .clone()
3✔
1495
    }
3✔
1496

1497
    pub fn summary(&self) -> SummarySyslogProcessor {
715✔
1498
        let syslogprocessor_missing_year = self.missing_year;
715✔
1499

1500
        SummarySyslogProcessor {
715✔
1501
            syslogprocessor_missing_year,
715✔
1502
        }
715✔
1503
    }
715✔
1504

1505
    /// Return an up-to-date [`Summary`] instance for this `SyslogProcessor`.
1506
    ///
1507
    /// Probably not useful or interesting before
1508
    /// `ProcessingStage::Stage4Summary`.
1509
    ///
1510
    /// [`Summary`]: crate::readers::summary::Summary
1511
    pub fn summary_complete(&self) -> Summary {
713✔
1512
        let path = self.path().clone();
713✔
1513
        let path_ntf = None;
713✔
1514
        let filetype = self.filetype();
713✔
1515
        let logmessagetype = filetype.to_logmessagetype();
713✔
1516
        let summaryblockreader = self.syslinereader.linereader.blockreader.summary();
713✔
1517
        let summarylinereader = self.syslinereader.linereader.summary();
713✔
1518
        let summarysyslinereader = self.syslinereader.summary();
713✔
1519
        let summarysyslogprocessor = self.summary();
713✔
1520
        let error: Option<String> = self.error.clone();
713✔
1521

1522
        Summary::new(
713✔
1523
            path,
713✔
1524
            path_ntf,
713✔
1525
            filetype,
713✔
1526
            logmessagetype,
713✔
1527
            Some(summaryblockreader),
713✔
1528
            Some(summarylinereader),
713✔
1529
            Some(summarysyslinereader),
713✔
1530
            Some(summarysyslogprocessor),
713✔
1531
            None,
713✔
1532
            None,
713✔
1533
            None,
713✔
1534
            None,
713✔
1535
            error,
713✔
1536
        )
1537
    }
713✔
1538
}
1539

1540
impl Drop for SyslogProcessor {
1541
    fn drop(&mut self) {
483✔
1542
        def2ñ!("SyslogProcessor PathID {} Path {:?}", self.path_id(), self.path());
483✔
1543
    }
483✔
1544
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc