Skip to main content

cmtraceopen_parser/parser/
psadt.rs

1//! PSADT Legacy format parser.
2//!
3//! Parses log lines produced by PSAppDeployToolkit v4 with `LogStyle = 'Legacy'`:
4//!   [2024-12-24 14:44:13.658] [Install] [Start-ADTMsiProcess] [Error] :: Message text here
5//!
6//! Fields extracted:
7//!   1. timestamp  (yyyy-MM-dd HH:mm:ss.fff)
8//!   2. section    (Initialization, Pre-Install, Install, Post-Install, Finalization)
9//!   3. source     (PSADT function name, e.g. Close-ADTSession)
10//!   4. severity   (Info, Warning, Error, Success)
11//!   5. message    (everything after `:: `)
12
13use regex::Regex;
14
15use super::severity::detect_severity_from_text;
16use crate::models::log_entry::{LogEntry, LogFormat, Severity};
17use std::sync::OnceLock;
18
19/// Full PSADT Legacy line regex.
20fn psadt_line_re() -> &'static Regex {
21    static CELL: OnceLock<Regex> = OnceLock::new();
22    CELL.get_or_init(|| {
23    Regex::new(
24        r"^\[(\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}\.\d{3})\]\s\[([^\]]+)\]\s\[([^\]]+)\]\s\[(\w+)\]\s::\s(.*)$",
25    )
26    .expect("PSADT Legacy line regex must compile")
27})
28}
29
30/// Lightweight prefix check for detection (avoids running the full regex).
31fn psadt_prefix_re() -> &'static Regex {
32    static CELL: OnceLock<Regex> = OnceLock::new();
33    CELL.get_or_init(|| {
34        Regex::new(r"^\[\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}\.\d{3}\]\s\[")
35            .expect("PSADT prefix regex must compile")
36    })
37}
38
39/// Known PSADT section names.
40static KNOWN_SECTIONS: &[&str] = &[
41    "Initialization",
42    "Pre-Install",
43    "Install",
44    "Post-Install",
45    "Finalization",
46];
47
48/// Known PSADT function names.
49static KNOWN_FUNCTIONS: &[&str] = &["Open-ADTSession", "Close-ADTSession", "Start-ADTMsiProcess"];
50
51/// Map the PSADT severity token to a `Severity` variant.
52fn map_severity(token: &str) -> Severity {
53    match token {
54        "Error" => Severity::Error,
55        "Warning" | "Warn" => Severity::Warning,
56        // "Info", "Information", "Success", or anything else → Info
57        _ => Severity::Info,
58    }
59}
60
61/// Parse a single PSADT Legacy format line.
62fn parse_line(line: &str) -> Option<PsadtParsed> {
63    let caps = psadt_line_re().captures(line)?;
64
65    let ts_str = caps.get(1)?.as_str();
66    let section = caps.get(2)?.as_str();
67    let source = caps.get(3)?.as_str();
68    let sev_token = caps.get(4)?.as_str();
69    let message = caps.get(5)?.as_str();
70
71    // Parse timestamp with chrono
72    let ndt = chrono::NaiveDateTime::parse_from_str(ts_str, "%Y-%m-%d %H:%M:%S%.3f").ok()?;
73    let timestamp = ndt.and_utc().timestamp_millis();
74
75    // Format display as MM-dd-yyyy HH:mm:ss.fff
76    let timestamp_display = format!(
77        "{:02}-{:02}-{:04} {:02}:{:02}:{:02}.{:03}",
78        ndt.month(),
79        ndt.day(),
80        ndt.year(),
81        ndt.hour(),
82        ndt.minute(),
83        ndt.second(),
84        ndt.and_utc().timestamp_subsec_millis()
85    );
86
87    Some(PsadtParsed {
88        timestamp,
89        timestamp_display,
90        section: section.to_string(),
91        source: source.to_string(),
92        severity: map_severity(sev_token),
93        message: message.to_string(),
94    })
95}
96
97struct PsadtParsed {
98    timestamp: i64,
99    timestamp_display: String,
100    section: String,
101    source: String,
102    severity: Severity,
103    message: String,
104}
105
106// Need these for the timestamp formatting in parse_line
107use chrono::{Datelike, Timelike};
108
109/// Parse all lines as PSADT Legacy format.
110/// Lines that don't match the format fall back to plain text entries with
111/// text-based severity detection.
112pub fn parse_lines(lines: &[&str], file_path: &str) -> (Vec<LogEntry>, u32) {
113    let mut entries = Vec::with_capacity(lines.len());
114    let mut errors = 0u32;
115    let mut id_counter = 0u64;
116
117    for (i, line) in lines.iter().enumerate() {
118        if line.trim().is_empty() {
119            continue;
120        }
121
122        match parse_line(line) {
123            Some(parsed) => {
124                entries.push(LogEntry {
125                    id: id_counter,
126                    line_number: (i + 1) as u32,
127                    message: parsed.message,
128                    component: Some(parsed.section),
129                    timestamp: Some(parsed.timestamp),
130                    timestamp_display: Some(parsed.timestamp_display),
131                    severity: parsed.severity,
132                    thread: None,
133                    thread_display: None,
134                    source_file: Some(parsed.source),
135                    format: LogFormat::Timestamped,
136                    file_path: file_path.to_string(),
137                    timezone_offset: None,
138                    error_code_spans: Vec::new(),
139                    ip_address: None,
140                    host_name: None,
141                    mac_address: None,
142                    result_code: None,
143                    gle_code: None,
144                    setup_phase: None,
145                    operation_name: None,
146                    http_method: None,
147                    uri_stem: None,
148                    uri_query: None,
149                    status_code: None,
150                    sub_status: None,
151                    time_taken_ms: None,
152                    client_ip: None,
153                    server_ip: None,
154                    user_agent: None,
155                    server_port: None,
156                    username: None,
157                    win32_status: None,
158                    query_name: None,
159                    query_type: None,
160                    response_code: None,
161                    dns_direction: None,
162                    dns_protocol: None,
163                    source_ip: None,
164                    dns_flags: None,
165                    dns_event_id: None,
166                    zone_name: None,
167                    entry_kind: None,
168                    whatif: None,
169                    section_name: None,
170                    section_color: None,
171                    iteration: None,
172                    tags: None,
173                });
174                id_counter += 1;
175            }
176            None => {
177                // Doesn't match PSADT format — treat as plain text
178                entries.push(LogEntry {
179                    id: id_counter,
180                    line_number: (i + 1) as u32,
181                    message: line.to_string(),
182                    component: None,
183                    timestamp: None,
184                    timestamp_display: None,
185                    severity: detect_severity_from_text(line),
186                    thread: None,
187                    thread_display: None,
188                    source_file: None,
189                    format: LogFormat::Plain,
190                    file_path: file_path.to_string(),
191                    timezone_offset: None,
192                    error_code_spans: Vec::new(),
193                    ip_address: None,
194                    host_name: None,
195                    mac_address: None,
196                    result_code: None,
197                    gle_code: None,
198                    setup_phase: None,
199                    operation_name: None,
200                    http_method: None,
201                    uri_stem: None,
202                    uri_query: None,
203                    status_code: None,
204                    sub_status: None,
205                    time_taken_ms: None,
206                    client_ip: None,
207                    server_ip: None,
208                    user_agent: None,
209                    server_port: None,
210                    username: None,
211                    win32_status: None,
212                    query_name: None,
213                    query_type: None,
214                    response_code: None,
215                    dns_direction: None,
216                    dns_protocol: None,
217                    source_ip: None,
218                    dns_flags: None,
219                    dns_event_id: None,
220                    zone_name: None,
221                    entry_kind: None,
222                    whatif: None,
223                    section_name: None,
224                    section_color: None,
225                    iteration: None,
226                    tags: None,
227                });
228                id_counter += 1;
229                errors += 1;
230            }
231        }
232    }
233
234    (entries, errors)
235}
236
237/// Detection helper: returns a weight indicating how likely the line is PSADT Legacy format.
238///
239/// Weight breakdown:
240/// - Full bracketed timestamp prefix `[yyyy-MM-dd HH:mm:ss.fff] [` → 3
241/// - Known section name (e.g. `[Initialization]`) → +1
242/// - Known PSADT function name (e.g. `[Open-ADTSession]`) → +1
243/// - Banner delimiter (10+ asterisks in a bracketed line) → 2
244pub fn matches_psadt_legacy_content(line: &str) -> u32 {
245    let mut weight = 0u32;
246
247    // Check for the bracketed timestamp prefix
248    if psadt_prefix_re().is_match(line) {
249        weight += 3;
250
251        // Check for known section names
252        for section in KNOWN_SECTIONS {
253            let bracketed = format!("[{}]", section);
254            if line.contains(&bracketed) {
255                weight += 1;
256                break;
257            }
258        }
259
260        // Check for known PSADT function names
261        for func in KNOWN_FUNCTIONS {
262            let bracketed = format!("[{}]", func);
263            if line.contains(&bracketed) {
264                weight += 1;
265                break;
266            }
267        }
268
269        // Check for banner delimiter (10+ asterisks)
270        if line.contains("**********") {
271            weight += 2;
272        }
273    }
274
275    weight
276}
277
278#[cfg(test)]
279mod tests {
280    use super::*;
281
282    #[test]
283    fn test_parse_info_line() {
284        let line =
285            "[2024-12-24 14:44:13.658] [Finalization] [Close-ADTSession] [Info] :: Message text here";
286        let parsed = parse_line(line).expect("should parse");
287        assert_eq!(parsed.message, "Message text here");
288        assert_eq!(parsed.section, "Finalization");
289        assert_eq!(parsed.source, "Close-ADTSession");
290        assert_eq!(parsed.severity, Severity::Info);
291        assert_eq!(parsed.timestamp_display, "12-24-2024 14:44:13.658");
292    }
293
294    #[test]
295    fn test_parse_error_line() {
296        let line = "[2024-12-24 14:44:13.700] [Install] [Start-ADTMsiProcess] [Error] :: MSI installation failed. [Exit code: 1603]";
297        let parsed = parse_line(line).expect("should parse");
298        assert_eq!(parsed.message, "MSI installation failed. [Exit code: 1603]");
299        assert_eq!(parsed.section, "Install");
300        assert_eq!(parsed.source, "Start-ADTMsiProcess");
301        assert_eq!(parsed.severity, Severity::Error);
302    }
303
304    #[test]
305    fn test_parse_warning_line() {
306        let line =
307            "[2024-12-24 14:44:14.000] [Pre-Install] [Test-Function] [Warning] :: Something is off";
308        let parsed = parse_line(line).expect("should parse");
309        assert_eq!(parsed.severity, Severity::Warning);
310        assert_eq!(parsed.section, "Pre-Install");
311    }
312
313    #[test]
314    fn test_parse_success_maps_to_info() {
315        let line = "[2024-12-24 14:44:14.000] [Post-Install] [Test-Function] [Success] :: All good";
316        let parsed = parse_line(line).expect("should parse");
317        assert_eq!(parsed.severity, Severity::Info);
318    }
319
320    #[test]
321    fn test_parse_banner_line() {
322        let line = "[2024-12-24 14:44:13.658] [Initialization] [Open-ADTSession] [Info] :: *******************************************************************************";
323        let parsed = parse_line(line).expect("should parse");
324        assert_eq!(parsed.severity, Severity::Info);
325        assert!(parsed.message.contains("***"));
326    }
327
328    #[test]
329    fn test_parse_lines_mixed() {
330        let lines = vec![
331            "[2024-12-24 14:44:13.658] [Finalization] [Close-ADTSession] [Info] :: Session closed",
332            "Some random non-matching line",
333            "[2024-12-24 14:44:13.700] [Install] [Start-ADTMsiProcess] [Error] :: MSI failed",
334        ];
335        let (entries, errors) = parse_lines(&lines, "test.log");
336        assert_eq!(entries.len(), 3);
337        assert_eq!(errors, 1);
338
339        // First entry: structured
340        assert_eq!(entries[0].component.as_deref(), Some("Finalization"));
341        assert_eq!(entries[0].source_file.as_deref(), Some("Close-ADTSession"));
342        assert_eq!(entries[0].severity, Severity::Info);
343        assert_eq!(entries[0].format, LogFormat::Timestamped);
344
345        // Second entry: plain fallback
346        assert_eq!(entries[1].message, "Some random non-matching line");
347        assert_eq!(entries[1].format, LogFormat::Plain);
348        assert!(entries[1].component.is_none());
349
350        // Third entry: structured error
351        assert_eq!(entries[2].severity, Severity::Error);
352        assert_eq!(entries[2].component.as_deref(), Some("Install"));
353    }
354
355    #[test]
356    fn test_parse_lines_skips_empty() {
357        let lines = vec![
358            "",
359            "  ",
360            "[2024-12-24 14:44:13.658] [Install] [Func] [Info] :: msg",
361        ];
362        let (entries, errors) = parse_lines(&lines, "test.log");
363        assert_eq!(entries.len(), 1);
364        assert_eq!(errors, 0);
365    }
366
367    #[test]
368    fn test_parse_lines_file_path_propagated() {
369        let lines = vec!["[2024-12-24 14:44:13.658] [Install] [Func] [Info] :: msg"];
370        let (entries, _) = parse_lines(&lines, "/path/to/deploy.log");
371        assert_eq!(entries[0].file_path, "/path/to/deploy.log");
372    }
373
374    #[test]
375    fn test_timestamp_to_millis() {
376        let line = "[2024-12-24 14:44:13.658] [Install] [Func] [Info] :: msg";
377        let parsed = parse_line(line).expect("should parse");
378        // 2024-12-24 14:44:13.658 UTC → verify it's a reasonable millis value
379        assert!(parsed.timestamp > 0);
380        // Rough check: 2024-12-24 is around epoch millis 1735000000000
381        assert!(parsed.timestamp > 1_735_000_000_000);
382        assert!(parsed.timestamp < 1_736_000_000_000);
383    }
384
385    // Detection tests
386
387    #[test]
388    fn test_matches_full_line() {
389        let line =
390            "[2024-12-24 14:44:13.658] [Finalization] [Close-ADTSession] [Info] :: Message text";
391        let weight = matches_psadt_legacy_content(line);
392        // 3 (prefix) + 1 (known section) + 1 (known function) = 5
393        assert_eq!(weight, 5);
394    }
395
396    #[test]
397    fn test_matches_unknown_section_and_function() {
398        let line =
399            "[2024-12-24 14:44:13.658] [CustomSection] [Custom-Function] [Info] :: Some message";
400        let weight = matches_psadt_legacy_content(line);
401        // 3 (prefix only, no known section or function)
402        assert_eq!(weight, 3);
403    }
404
405    #[test]
406    fn test_matches_banner_line() {
407        let line = "[2024-12-24 14:44:13.658] [Initialization] [Open-ADTSession] [Info] :: *******************************************************************************";
408        let weight = matches_psadt_legacy_content(line);
409        // 3 (prefix) + 1 (known section) + 1 (known function) + 2 (banner) = 7
410        assert_eq!(weight, 7);
411    }
412
413    #[test]
414    fn test_matches_non_psadt_line() {
415        let weight = matches_psadt_legacy_content("Just a plain text line");
416        assert_eq!(weight, 0);
417    }
418
419    #[test]
420    fn test_matches_similar_but_not_psadt() {
421        // Has a bracketed timestamp but wrong format
422        let weight = matches_psadt_legacy_content("[2024-12-24] Some log message");
423        assert_eq!(weight, 0);
424    }
425}