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

jtmoon79 / super-speedy-syslog-searcher / 17700737642

13 Sep 2025 06:55PM UTC coverage: 57.925% (+0.02%) from 57.903%
17700737642

push

github

jtmoon79
(TOOLS) cargo fmt use nightly

11940 of 20613 relevant lines covered (57.92%)

22056.21 hits per line

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

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

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

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

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

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

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

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

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

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

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

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

338
    /// Create a new `SyslogProcessor`.
339
    ///
340
    /// **NOTE:** should not attempt any block reads here,
341
    /// similar to other `*Readers::new()`
342
    pub fn new(
98✔
343
        path: FPath,
98✔
344
        filetype: FileType,
98✔
345
        blocksz: BlockSz,
98✔
346
        tz_offset: FixedOffset,
98✔
347
        filter_dt_after_opt: DateTimeLOpt,
98✔
348
        filter_dt_before_opt: DateTimeLOpt,
98✔
349
    ) -> Result<SyslogProcessor> {
98✔
350
        def1n!("({:?}, {:?}, {:?}, {:?})", path, filetype, blocksz, tz_offset);
98✔
351
        if blocksz < SyslogProcessor::BLOCKSZ_MIN {
98✔
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
        }
98✔
362
        let path_ = path.clone();
98✔
363
        let mut slr = match SyslineReader::new(path, filetype, blocksz, tz_offset) {
98✔
364
            Ok(val) => val,
96✔
365
            Err(err) => {
2✔
366
                def1x!();
2✔
367
                return Result::Err(err);
2✔
368
            }
369
        };
370

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

380
        def1x!("return Ok(SyslogProcessor)");
96✔
381

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

733
        FileProcessingResultBlockZero::FileOk
5✔
734
    }
5✔
735

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

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

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

752
                syslinep_
×
753
            }
754
            ResultFindSysline::Done => {
×
755
                defx!("No sysline found");
×
756
                return FileProcessingResultBlockZero::FileErrNoSyslinesFound;
×
757
            }
758
            ResultFindSysline::Err(err) => {
×
759
                defx!("error finding sysline: {:?}", err);
×
760
                return FileProcessingResultBlockZero::FileErrIo(err);
×
761
            }
762
        };
763
        let dt = syslinep.dt();
×
764
        let diff_ = datetime_minus_systemtime(&dt, &UPTIME_DEFAULT_OFFSET);
×
765
        defo!("diff_ from UPTIME_DEFAULT_OFFSET {:?}", diff_);
×
766
        let diff_secs = diff_.num_seconds();
×
767
        defo!("diff_secs {:?}", diff_secs);
×
768
        let mut diff_nanos = diff_.subsec_nanos();
×
769
        defo!("diff_nanos {:?}", diff_nanos);
×
770
        if diff_nanos < 0 {
×
771
            diff_nanos = 0;
×
772
        }
×
773
        let diffs: StdDuration = StdDuration::new(diff_secs as u64, diff_nanos as u32);
×
774
        defo!("diffs {:?}", diffs);
×
775
        defo!("mtime()");
×
776
        let mtime = self.mtime();
×
777
        defo!("mtime {:?} (as DateTime {:?})", mtime, systemtime_to_datetime(&self.tz_offset, &mtime));
×
778
        // std::time::Duration is unsigned whereas chrono::Duration is signed.
779
        let st_at_zero = if diff_secs > 0 {
×
780
            defo!("checked_sub({:?})", diffs);
×
781
            match mtime.checked_sub(diffs) {
×
782
                Some(st) => st,
×
783
                None => {
784
                    defx!("failed to calculate systemtime at uptime zero");
×
785
                    return FileProcessingResultBlockZero::FileErrIo(std::io::Error::new(
×
786
                        std::io::ErrorKind::Other,
×
787
                        "failed to calculate systemtime at uptime zero",
×
788
                    ));
×
789
                }
790
            }
791
        } else {
792
            defo!("checked_add({:?})", diffs);
×
793
            match mtime.checked_add(diffs) {
×
794
                Some(st) => st,
×
795
                None => {
796
                    defx!("failed to calculate systemtime at uptime zero");
×
797
                    return FileProcessingResultBlockZero::FileErrIo(std::io::Error::new(
×
798
                        std::io::ErrorKind::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(
×
831
        &self,
×
832
        syslinep: &SyslineP,
×
833
    ) -> bool {
×
834
        self.syslinereader
×
835
            .is_sysline_last(syslinep)
×
836
    }
×
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;
4✔
871
            def1x!("({}) return true", blockoffset);
4✔
872
            return true;
4✔
873
        }
5✔
874

875
        def1x!("({}) return false", blockoffset);
5✔
876
        false
5✔
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(
24✔
888
        &mut self,
24✔
889
        syslinep: &SyslineP,
24✔
890
    ) -> bool {
24✔
891
        if !SyslogProcessor::STREAM_STAGE_DROP {
24✔
892
            de_wrn!("drop_data_try() called but SyslogProcessor::STREAM_STAGE_DROP is false");
×
893
            return false;
×
894
        }
24✔
895
        if !self.is_drop_data() {
24✔
896
            def1ñ!("is_drop_data() is false; return false");
×
897
            return false;
×
898
        }
24✔
899

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

906
        false
10✔
907
    }
24✔
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(
88✔
921
        &mut self,
88✔
922
        fileoffset: FileOffset,
88✔
923
    ) -> ResultFindSysline {
88✔
924
        defn!("({})", fileoffset);
88✔
925
        let result: ResultFindSysline = self
88✔
926
            .syslinereader
88✔
927
            .find_sysline(fileoffset);
88✔
928
        match result {
88✔
929
            ResultFindSysline::Found(_) => {}
74✔
930
            ResultFindSysline::Done => {}
14✔
931
            ResultFindSysline::Err(ref err) => {
×
932
                self.set_error(err);
×
933
            }
×
934
        }
935
        defx!();
88✔
936

937
        result
88✔
938
    }
88✔
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(
5✔
956
        &mut self,
5✔
957
        fileoffset: FileOffset,
5✔
958
    ) -> ResultFindSysline {
5✔
959
        defn!("({})", fileoffset);
5✔
960

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

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

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

978
        result
5✔
979
    }
5✔
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(
469✔
991
        &self,
469✔
992
        stage_expact: ProcessingStage,
469✔
993
    ) {
469✔
994
        debug_assert_eq!(
469✔
995
            self.processingstage, stage_expact,
996
            "Unexpected Processing Stage {:?}, expected Processing Stage {:?}",
×
997
            self.processingstage, stage_expact,
998
        );
999
    }
469✔
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 {
80✔
1005
        defn!();
80✔
1006
        // sanity check calls are in correct order
1007
        self.assert_stage(ProcessingStage::Stage0ValidFileCheck);
80✔
1008
        self.processingstage = ProcessingStage::Stage0ValidFileCheck;
80✔
1009

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

1016
        FileProcessingResultBlockZero::FileOk
78✔
1017
    }
80✔
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 {
77✔
1025
        defn!();
77✔
1026
        self.assert_stage(ProcessingStage::Stage0ValidFileCheck);
77✔
1027
        self.processingstage = ProcessingStage::Stage1BlockzeroAnalysis;
77✔
1028

1029
        let result: FileProcessingResultBlockZero = self.blockzero_analysis();
77✔
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!(
77✔
1033
            "blockzero_analysis() stored syslines {}",
77✔
1034
            self.syslinereader
77✔
1035
                .count_syslines_stored()
77✔
1036
        );
1037
        match result {
77✔
1038
            FileProcessingResult::FileOk => {}
39✔
1039
            // skip further processing if not `FileOk`
1040
            _ => {
1041
                defx!("return {:?}", result);
38✔
1042
                return result;
38✔
1043
            }
1044
        }
1045

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

1048
        result
39✔
1049
    }
77✔
1050

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

1062
        // datetime formats without a year requires special handling
1063
        if !self.syslinereader.dt_pattern_has_year() &&
8✔
1064
            !self.syslinereader.dt_pattern_uptime()
4✔
1065
        {
1066
            defo!("!dt_pattern_has_year() && !dt_pattern_uptime()");
4✔
1067
            let mtime: SystemTime = self.mtime();
4✔
1068
            match self.process_missing_year(mtime, filter_dt_after_opt) {
4✔
1069
                FileProcessingResultBlockZero::FileOk => {}
4✔
1070
                result => {
×
1071
                    defx!("Bad result {:?}", result);
×
1072
                    return result;
×
1073
                }
1074
            }
1075
        } else if self.syslinereader.dt_pattern_uptime() {
4✔
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
        }
4✔
1085

1086
        defx!();
8✔
1087

1088
        FileProcessingResultBlockZero::FileOk
8✔
1089
    }
8✔
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 {
4✔
1100
        defñ!();
4✔
1101
        self.assert_stage(ProcessingStage::Stage2FindDt);
4✔
1102
        self.processingstage = ProcessingStage::Stage3StreamSyslines;
4✔
1103

1104
        FileProcessingResultBlockZero::FileOk
4✔
1105
    }
4✔
1106

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

1117
        self.summary_complete()
1✔
1118
    }
1✔
1119

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

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

1163
        defx!("return FileOk");
66✔
1164

1165
        FileProcessingResultBlockZero::FileOk
66✔
1166
    }
77✔
1167

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

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

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

1244
        let fpr: FileProcessingResultBlockZero = match found >= found_min {
66✔
1245
            true => FileProcessingResultBlockZero::FileOk,
66✔
1246
            false => FileProcessingResultBlockZero::FileErrNoLinesFound,
×
1247
        };
1248

1249
        defx!("found {} lines, partial_found {}, require {} lines, return {:?}", found, _partial_found, found_min, fpr);
66✔
1250

1251
        fpr
66✔
1252
    }
66✔
1253

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

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

1292
        // find `at_max` Syslines within block zero
1293
        while found < found_min
97✔
1294
            && self.syslinereader.block_offset_at_file_offset(fo) == 0
66✔
1295
        {
1296
            fo = match self
66✔
1297
                .syslinereader
66✔
1298
                .find_sysline_in_block(fo)
66✔
1299
            {
1300
                (ResultFindSysline::Found((fo_next, _slinep)), _) => {
31✔
1301
                    found += 1;
31✔
1302
                    defo!("Found; found {} syslines, fo_next {}", found, fo_next);
31✔
1303

1304
                    fo_next
31✔
1305
                }
1306
                (ResultFindSysline::Done, partial_found) => {
35✔
1307
                    defo!("Done; found {} syslines, partial_found {}", found, partial_found);
35✔
1308
                    if partial_found {
35✔
1309
                        found += 1;
8✔
1310
                    }
27✔
1311
                    break;
35✔
1312
                }
1313
                (ResultFindSysline::Err(err), _) => {
×
1314
                    self.set_error(&err);
×
1315
                    defx!("return FileErrIo({:?})", err);
×
1316
                    return FileProcessingResultBlockZero::FileErrIoPath(err);
×
1317
                }
1318
            };
1319
        }
1320

1321
        if found == 0 {
66✔
1322
            defx!("found {} syslines, require {} syslines, return FileErrNoSyslinesFound", found, found_min);
27✔
1323
            return FileProcessingResultBlockZero::FileErrNoSyslinesFound;
27✔
1324
        }
39✔
1325

1326
        let patt_count_a = self.syslinereader.dt_patterns_counts_in_use();
39✔
1327
        defo!("dt_patterns_counts_in_use {}", patt_count_a);
39✔
1328

1329
        if !self.syslinereader.dt_patterns_analysis() {
39✔
1330
            de_err!("dt_patterns_analysis() failed which is unexpected; return FileErrNoSyslinesFound");
×
1331
            return FileProcessingResultBlockZero::FileErrNoSyslinesFound;
×
1332
        }
39✔
1333

1334
        let _patt_count_b = self.syslinereader.dt_patterns_counts_in_use();
39✔
1335
        debug_assert_eq!(
39✔
1336
            _patt_count_b,
1337
            SyslogProcessor::DT_PATTERN_MAX,
1338
            "expected patterns to be reduced to {}, found {:?}",
×
1339
            SyslogProcessor::DT_PATTERN_MAX,
1340
            _patt_count_b,
1341
        );
1342

1343
        // if more than one `DateTimeParseInstr` was used then the syslines
1344
        // must be reparsed using the one chosen `DateTimeParseInstr`
1345
        if patt_count_a > 1 {
39✔
1346
            defo!("must reprocess all syslines using limited patterns (used {} DateTimeParseInstr; must only use {})!", patt_count_a, 1);
8✔
1347

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

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

1384
        let fpr: FileProcessingResultBlockZero = match found >= found_min {
39✔
1385
            true => FileProcessingResultBlockZero::FileOk,
39✔
1386
            false => FileProcessingResultBlockZero::FileErrNoSyslinesFound,
×
1387
        };
1388

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

1397
        if self.syslinereader.is_streamed_file()
39✔
1398
            && !self.syslinereader.dt_pattern_has_year()
×
1399
        {
1400
            self.syslinereader.linereader.blockreader.disable_drop_data();
×
1401
            debug_assert!(!self.is_drop_data(), "is_drop_data() should be false");
×
1402
        }
39✔
1403

1404
        defx!("found {} syslines, require {} syslines, return {:?}", found, found_min, fpr);
39✔
1405

1406
        fpr
39✔
1407
    }
66✔
1408

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

1417
        if self.syslinereader.filesz() == 0 {
77✔
1418
            defx!("return FileErrEmpty");
×
1419
            return FileProcessingResultBlockZero::FileErrEmpty;
×
1420
        }
77✔
1421

1422
        let result: FileProcessingResultBlockZero = self.blockzero_analysis_bytes();
77✔
1423
        if !result.is_ok() {
77✔
1424
            defx!("syslinereader.blockzero_analysis_bytes() was !is_ok(), return {:?}", result);
11✔
1425
            return result;
11✔
1426
        };
66✔
1427

1428
        let result: FileProcessingResultBlockZero = self.blockzero_analysis_lines();
66✔
1429
        if !result.is_ok() {
66✔
1430
            defx!("syslinereader.blockzero_analysis() was !is_ok(), return {:?}", result);
×
1431
            return result;
×
1432
        };
66✔
1433

1434
        let result: FileProcessingResultBlockZero = self.blockzero_analysis_syslines();
66✔
1435
        defx!("return {:?}", result);
66✔
1436

1437
        result
66✔
1438
    }
77✔
1439

1440
    #[cfg(test)]
1441
    pub(crate) fn dropped_blocks(&self) -> SetDroppedBlocks {
3✔
1442
        self.syslinereader
3✔
1443
            .linereader
3✔
1444
            .blockreader
3✔
1445
            .dropped_blocks
3✔
1446
            .clone()
3✔
1447
    }
3✔
1448

1449
    #[cfg(test)]
1450
    pub(crate) fn dropped_lines(&self) -> SetDroppedLines {
3✔
1451
        self.syslinereader
3✔
1452
            .linereader
3✔
1453
            .dropped_lines
3✔
1454
            .clone()
3✔
1455
    }
3✔
1456

1457
    #[cfg(test)]
1458
    pub(crate) fn dropped_syslines(&self) -> SetDroppedSyslines {
3✔
1459
        self.syslinereader
3✔
1460
            .dropped_syslines
3✔
1461
            .clone()
3✔
1462
    }
3✔
1463

1464
    pub fn summary(&self) -> SummarySyslogProcessor {
7✔
1465
        let syslogprocessor_missing_year = self.missing_year;
7✔
1466

1467
        SummarySyslogProcessor {
7✔
1468
            syslogprocessor_missing_year,
7✔
1469
        }
7✔
1470
    }
7✔
1471

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

1489
        Summary::new(
4✔
1490
            path,
4✔
1491
            path_ntf,
4✔
1492
            filetype,
4✔
1493
            logmessagetype,
4✔
1494
            Some(summaryblockreader),
4✔
1495
            Some(summarylinereader),
4✔
1496
            Some(summarysyslinereader),
4✔
1497
            Some(summarysyslogprocessor),
4✔
1498
            None,
4✔
1499
            None,
4✔
1500
            None,
4✔
1501
            error,
4✔
1502
        )
1503
    }
4✔
1504
}
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