postfix-log-parser 0.2.0

高性能模块化Postfix日志解析器,经3.2GB生产数据验证,SMTPD事件100%准确率
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
//! # Bounce 退信处理组件解析器
//!
//! Bounce 是 Postfix 的退信处理组件,负责:
//! - 生成和发送投递失败通知(NDN)
//! - 处理发送者通知和管理员通知
//! - 管理退信邮件的格式和内容
//! - 处理延迟投递通知和最终失败通知
//!
//! ## 支持的事件类型
//!
//! - **发送者通知**: 向原始发送者发送的投递失败通知
//! - **管理员通知**: 向邮件管理员发送的系统通知
//! - **警告事件**: 格式错误、配置问题、资源限制等警告
//!
//! ## 示例日志格式
//!
//! ```text
//! # 发送者投递失败通知
//! queue_id: sender non-delivery notification: new_queue_id
//!
//! # 管理员通知
//! queue_id: postmaster non-delivery notification: new_queue_id
//!
//! # 警告事件
//! malformed request
//! ```

use regex::Regex;

use crate::error::ParseError;
use crate::events::bounce::{BounceEvent, BounceWarningType};
use crate::events::{base::BaseEvent, ComponentEvent};

use super::ComponentParser;

/// BOUNCE组件解析器
///
/// 基于Postfix BOUNCE守护进程的真实日志格式开发
/// BOUNCE守护进程的特点:
/// - 处理投递失败通知(non-delivery notification)
/// - 生成发送者通知邮件
/// - 处理退信和延迟通知
/// - 管理通知邮件的生成和发送
pub struct BounceParser {
    /// 发送者投递失败通知事件解析 - 主要模式(95%+频率)
    /// 格式: "queue_id: sender non-delivery notification: new_queue_id"
    sender_notification_regex: Regex,

    /// 收件人投递失败通知事件解析
    /// 格式: "queue_id: postmaster non-delivery notification: new_queue_id"  
    postmaster_notification_regex: Regex,

    /// 警告事件解析 - malformed request
    /// 格式: "malformed request" (注意:MasterParser已剥离"warning:"前缀)
    warning_malformed_regex: Regex,

    /// 其他警告事件解析
    /// 格式: 各种警告消息 (注意:MasterParser已剥离"warning:"前缀)
    warning_general_regex: Regex,
}

impl BounceParser {
    pub fn new() -> Self {
        Self {
            // 主要的发送者投递失败通知事件模式
            sender_notification_regex: Regex::new(
                r"^([A-F0-9]+):\s+sender non-delivery notification:\s+([A-F0-9]+)$",
            )
            .expect("BOUNCE发送者通知正则表达式编译失败"),

            // 邮件管理员投递失败通知事件模式
            postmaster_notification_regex: Regex::new(
                r"^([A-F0-9]+):\s+postmaster non-delivery notification:\s+([A-F0-9]+)$",
            )
            .expect("BOUNCE邮件管理员通知正则表达式编译失败"),

            // 格式错误请求警告模式 (MasterParser已剥离"warning:"前缀)
            warning_malformed_regex: Regex::new(r"^malformed request$")
                .expect("BOUNCE格式错误警告正则表达式编译失败"),

            // 一般警告事件模式 (MasterParser已剥离"warning:"前缀)
            warning_general_regex: Regex::new(r"^(.+)$").expect("BOUNCE一般警告正则表达式编译失败"),
        }
    }

    /// 解析BOUNCE日志行
    pub fn parse_line(&self, line: &str, base_event: BaseEvent) -> Option<BounceEvent> {
        // 尝试解析发送者投递失败通知事件(主要模式)
        if let Some(captures) = self.sender_notification_regex.captures(line) {
            return self.parse_sender_notification(captures, base_event);
        }

        // 尝试解析邮件管理员投递失败通知事件
        if let Some(captures) = self.postmaster_notification_regex.captures(line) {
            return self.parse_postmaster_notification(captures, base_event);
        }

        // 尝试解析格式错误警告
        if self.warning_malformed_regex.is_match(line) {
            return self.parse_malformed_warning(base_event);
        }

        // 尝试解析其他警告事件 (只有在确认是警告消息时才处理)
        if self.is_bounce_warning(line) {
            if let Some(captures) = self.warning_general_regex.captures(line) {
                return self.parse_general_warning(captures, base_event);
            }
        }

        None
    }

    /// 解析发送者投递失败通知事件
    fn parse_sender_notification(
        &self,
        captures: regex::Captures,
        base_event: BaseEvent,
    ) -> Option<BounceEvent> {
        let original_queue_id = captures.get(1)?.as_str().to_string();
        let bounce_queue_id = captures.get(2)?.as_str().to_string();

        Some(BounceEvent::SenderNotification {
            base: base_event,
            original_queue_id,
            bounce_queue_id,
        })
    }

    /// 解析邮件管理员投递失败通知事件
    fn parse_postmaster_notification(
        &self,
        captures: regex::Captures,
        base_event: BaseEvent,
    ) -> Option<BounceEvent> {
        let original_queue_id = captures.get(1)?.as_str().to_string();
        let bounce_queue_id = captures.get(2)?.as_str().to_string();

        Some(BounceEvent::PostmasterNotification {
            base: base_event,
            original_queue_id,
            bounce_queue_id,
        })
    }

    /// 解析格式错误警告事件
    fn parse_malformed_warning(&self, base_event: BaseEvent) -> Option<BounceEvent> {
        Some(BounceEvent::Warning {
            base: base_event,
            warning_type: BounceWarningType::MalformedRequest,
            details: "malformed request".to_string(),
        })
    }

    /// 解析其他警告事件
    /// 处理BOUNCE服务的其他警告类型
    fn parse_general_warning(
        &self,
        captures: regex::Captures,
        base_event: BaseEvent,
    ) -> Option<BounceEvent> {
        let warning_message = captures.get(1)?.as_str();

        // 根据警告内容确定警告类型
        let warning_type = if warning_message.contains("malformed") {
            BounceWarningType::MalformedRequest
        } else if warning_message.contains("configuration") || warning_message.contains("config") {
            BounceWarningType::Configuration
        } else if warning_message.contains("resource")
            || warning_message.contains("memory")
            || warning_message.contains("disk")
        {
            BounceWarningType::ResourceLimit
        } else {
            BounceWarningType::Other
        };

        Some(BounceEvent::Warning {
            base: base_event,
            warning_type,
            details: warning_message.to_string(),
        })
    }

    /// 判断是否是BOUNCE组件的警告消息
    fn is_bounce_warning(&self, message: &str) -> bool {
        // 只有在日志级别为Warning时才考虑作为警告处理
        // 这个判断会在实际使用中由MasterParser的日志级别提取来处理
        message.contains("malformed")
            || message.contains("configuration")
            || message.contains("resource")
            || message.contains("memory")
            || message.contains("disk")
            || message.contains("queue")
            || message.contains("bounce")
    }
}

impl ComponentParser for BounceParser {
    fn parse(&self, message: &str) -> Result<ComponentEvent, ParseError> {
        // 创建一个临时的BaseEvent,用于解析
        // 在实际使用中,这些字段会被MasterParser正确填充
        let base_event = BaseEvent {
            timestamp: chrono::Utc::now(),
            hostname: "temp".to_string(),
            component: "bounce".to_string(),
            process_id: 0,
            log_level: crate::events::base::PostfixLogLevel::Info,
            raw_message: message.to_string(),
        };

        if let Some(bounce_event) = self.parse_line(message, base_event) {
            Ok(ComponentEvent::Bounce(bounce_event))
        } else {
            Err(ParseError::ComponentParseError {
                component: "bounce".to_string(),
                reason: "无法识别的bounce日志格式".to_string(),
            })
        }
    }

    fn component_name(&self) -> &'static str {
        "bounce"
    }

    fn can_parse(&self, message: &str) -> bool {
        // 检查是否包含bounce特征
        self.sender_notification_regex.is_match(message)
            || self.postmaster_notification_regex.is_match(message)
            || self.warning_malformed_regex.is_match(message)
            // 对于一般警告,我们需要更精确的判断,而不是匹配所有内容
            || self.is_bounce_warning(message)
    }
}

impl Default for BounceParser {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::events::base::BaseEvent;
    use chrono::{DateTime, Utc};

    fn create_test_base_event() -> BaseEvent {
        BaseEvent {
            timestamp: DateTime::parse_from_rfc3339("2024-04-27T16:20:48+00:00")
                .unwrap()
                .with_timezone(&Utc),
            hostname: "m01".to_string(),
            component: "bounce".to_string(),
            process_id: 133,
            log_level: crate::events::base::PostfixLogLevel::Info,
            raw_message: "test message".to_string(),
        }
    }

    #[test]
    fn test_parse_sender_notification() {
        let parser = BounceParser::new();
        let base_event = create_test_base_event();

        let message = "5FC392A20996: sender non-delivery notification: 732B92A209A3";

        let result = parser.parse_line(message, base_event);
        assert!(result.is_some());

        if let Some(BounceEvent::SenderNotification {
            original_queue_id,
            bounce_queue_id,
            ..
        }) = result
        {
            assert_eq!(original_queue_id, "5FC392A20996");
            assert_eq!(bounce_queue_id, "732B92A209A3");
        } else {
            panic!("解析结果类型不正确");
        }
    }

    #[test]
    fn test_parse_postmaster_notification() {
        let parser = BounceParser::new();
        let base_event = create_test_base_event();

        let message = "633F488423: postmaster non-delivery notification: 6DFA788422";

        let result = parser.parse_line(message, base_event);
        assert!(result.is_some());

        if let Some(BounceEvent::PostmasterNotification {
            original_queue_id,
            bounce_queue_id,
            ..
        }) = result
        {
            assert_eq!(original_queue_id, "633F488423");
            assert_eq!(bounce_queue_id, "6DFA788422");
        } else {
            panic!("解析结果类型不正确");
        }
    }

    #[test]
    fn test_parse_malformed_warning() {
        let parser = BounceParser::new();
        let base_event = create_test_base_event();

        // 注意:MasterParser已剥离"warning:"前缀
        let message = "malformed request";

        let result = parser.parse_line(message, base_event);
        assert!(result.is_some());

        if let Some(BounceEvent::Warning {
            warning_type,
            details,
            ..
        }) = result
        {
            assert!(matches!(warning_type, BounceWarningType::MalformedRequest));
            assert_eq!(details, "malformed request");
        } else {
            panic!("解析结果类型不正确");
        }
    }

    #[test]
    fn test_parse_general_warning() {
        let parser = BounceParser::new();
        let base_event = create_test_base_event();

        // 注意:MasterParser已剥离"warning:"前缀
        let message = "configuration file error";

        let result = parser.parse_line(message, base_event);
        assert!(result.is_some());

        if let Some(BounceEvent::Warning {
            warning_type,
            details,
            ..
        }) = result
        {
            assert!(matches!(warning_type, BounceWarningType::Configuration));
            assert_eq!(details, "configuration file error");
        } else {
            panic!("解析结果类型不正确");
        }
    }

    #[test]
    fn test_can_parse() {
        let parser = BounceParser::new();

        // 应该能解析的消息
        assert!(parser.can_parse("5FC392A20996: sender non-delivery notification: 732B92A209A3"));
        assert!(parser.can_parse("633F488423: postmaster non-delivery notification: 6DFA788422"));
        // 注意:MasterParser已剥离"warning:"前缀
        assert!(parser.can_parse("malformed request"));
        assert!(parser.can_parse("configuration error"));

        // 不应该解析的消息
        assert!(!parser.can_parse("some random message"));
        assert!(!parser.can_parse("info: normal operation"));
        assert!(!parser.can_parse("5FC392A20996: to=<user@domain.com>, status=sent"));
    }

    #[test]
    fn test_component_parser_interface() {
        let parser = BounceParser::new();

        // 测试component_name
        assert_eq!(parser.component_name(), "bounce");

        // 测试parse方法成功案例
        let result = parser.parse("5FC392A20996: sender non-delivery notification: 732B92A209A3");
        assert!(result.is_ok());

        if let Ok(ComponentEvent::Bounce(bounce_event)) = result {
            match bounce_event {
                BounceEvent::SenderNotification {
                    original_queue_id,
                    bounce_queue_id,
                    ..
                } => {
                    assert_eq!(original_queue_id, "5FC392A20996");
                    assert_eq!(bounce_queue_id, "732B92A209A3");
                }
                _ => panic!("解析结果类型不正确"),
            }
        } else {
            panic!("解析失败");
        }

        // 测试parse方法失败案例
        let result = parser.parse("some random text that should not match");
        assert!(result.is_err());

        if let Err(ParseError::ComponentParseError { component, reason }) = result {
            assert_eq!(component, "bounce");
            assert!(reason.contains("无法识别的bounce日志格式"));
        } else {
            panic!("错误类型不正确");
        }
    }
}