-
Notifications
You must be signed in to change notification settings - Fork 2
/
logparser.py
3884 lines (3435 loc) · 163 KB
/
logparser.py
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#! /usr/bin/env python3
# vim: ts=4 filetype=python expandtab shiftwidth=4 softtabstop=4 syntax=python
# Requires: python3 (>= 3.8)
#
# Copyright the Cluster Management Toolkit for Kubernetes contributors.
# SPDX-License-Identifier: MIT
# The parser takes one line of input at a time;
# for messages that need multi-line parsing you need to
# return remnants and if necessary tweak multiline_parser
#
# Log levels are the same as in syslog:
# EMERG system is unusable <should be irrelevant>
# ALERT action must be taken immediately
# CRIT critical conditions
# ERR error conditions
# WARNING warning conditions
# NOTICE normal, but significant, condition
# INFO informational message
# DEBUG debug-level message
#
# Return format is timestamp, facility, severity, message
"""
Log parsers for cmu
unit-tests:
tests/logtests
"""
# pylint: disable=too-many-lines
import ast
from collections import namedtuple
from datetime import datetime
import difflib
# ujson is much faster than json,
# but it might not be available
try:
import ujson as json
json_is_ujson = True # pylint: disable=invalid-name
# The exception raised by ujson when parsing fails is different
# from what json raises
DecodeException = ValueError
except ModuleNotFoundError:
import json # type: ignore
json_is_ujson = False # pylint: disable=invalid-name
DecodeException = json.decoder.JSONDecodeError # type: ignore
from pathlib import Path, PurePath
import re
import sys
from typing import Any, cast, Callable, Dict, List, Optional, Sequence, Set, Tuple, Union
try:
import yaml
except ModuleNotFoundError: # pragma: no cover
sys.exit("ModuleNotFoundError: Could not import yaml; "
"you may need to (re-)run `cmt-install` or `pip3 install PyYAML`; aborting.")
try:
from natsort import natsorted
except ModuleNotFoundError: # pragma: no cover
sys.exit("ModuleNotFoundError: Could not import natsort; "
"you may need to (re-)run `cmt-install` or `pip3 install natsort`; aborting.")
try:
import validators
except ModuleNotFoundError:
print("ModuleNotFoundError: Could not import validators; "
"you may need to (re-)run `cmt-install` or `pip3 install validators`; "
"disabling IP-address validation.\n", file=sys.stderr)
# pylint: disable-next=invalid-name
validators = None # type: ignore
from cmtpaths import HOMEDIR, PARSER_DIR
from cmttypes import deep_get, deep_get_with_fallback, DictPath
from cmttypes import FilePath, LogLevel, loglevel_mappings, loglevel_to_name, ProgrammingError
from cmtio_yaml import secure_read_yaml, secure_read_yaml_all
import cmtlib
from cmtlib import none_timestamp, strip_ansicodes
# from cmtlog import debuglog
import formatters
from curses_helper import themearray_len, themearray_to_string, ThemeAttr, ThemeRef, ThemeStr
from ansithemeprint import ANSIThemeStr
# pylint: disable-next=too-few-public-methods
class LogparserConfiguration:
"""
Various configuration options used by the logparsers
"""
# Keep or strip timestamps in structured logs
pop_ts: bool = True
# Keep or strip severity in structured logs
pop_severity: bool = True
# Keep or strip facility in structured logs
pop_facility: bool = True
# msg="foo" or msg=foo => foo
msg_extract: bool = True
# If msg_extract is False,
# this decides whether or not to put msg="foo" first or not
# this also affects err="foo" and error="foo"
msg_first: bool = True
# if msg_extract is True,
# this decides whether msg="foo\nbar" should be converted to:
# foo
# bar
# Currently this only work with JSON & key_value on a subset of keys
# and does not affect "err=" and "error="
expand_newlines: bool = True
# Should "* " be replaced with real bullets?
msg_realbullets: bool = True
# Should override severity rules be applied?
override_severity: bool = True
# collector=foo => • foo
bullet_collectors: bool = True
# if msg_extract is True,
# this decides whether should be converted to:
# msg="Starting foo" version="(version=.*)" => Starting foo (version=.*)
merge_starting_version: bool = True
# Replace tabs within values
expand_tabs: bool = True
using_bundles: bool = False
if json_is_ujson:
def json_dumps(obj: Dict[str, Any]) -> str:
"""
Dump JSON object to text format; ujson version
Parameters:
obj (dict): The JSON object to dump
Returns:
str: The serialized JSON object
"""
indent = 2
return json.dumps(obj, indent=indent, escape_forward_slashes=False)
else:
def json_dumps(obj: Dict[str, Any]) -> str:
"""
Dump JSON object to text format; json version
Parameters:
obj (dict): The JSON object to dump
Returns:
str: The serialized JSON object
"""
indent = 2
return json.dumps(obj, indent=indent)
def get_loglevel_names() -> List[str]:
"""
Ugly way of removing duplicate values from dict
Returns:
([str]): The unique severities
"""
return list(dict.fromkeys(list(loglevel_mappings.values())))
def name_to_loglevel(severity: str) -> LogLevel:
"""
Given a severity string, return its numerical number
Parameters:
name (int): The corresponding numerical loglevel
Returns:
(str): A severity string
"""
for _severity, _severity_string in loglevel_mappings.items():
if _severity_string.lower() == severity.lower():
return _severity
msg = [
[("Loglevel ", "error"),
(f"{severity}", "argument"),
(" does not exist!", "error")]
]
unformatted_msg, formatted_msg = ANSIThemeStr.format_error_msg(msg)
raise ProgrammingError(unformatted_msg,
severity=LogLevel.ERR,
formatted_msg=formatted_msg)
def month_to_numerical(month: str) -> str:
"""
Convert a 3-letter month string to a numerical month string
Parameters:
month (str): The month string
Returns:
(str): The numerical value for the month
"""
months = ("jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec")
return f"{months.index(month.lower()[0:3]):02}"
# Mainly used by glog
def letter_to_severity(letter: str, **kwargs: Any) -> Optional[LogLevel]:
"""
Convert a 1-letter severity string to a LogLevel
Parameters:
letter (str): A 1-letter severity string
**kwargs (dict[str, Any]): Keyword arguments
default (LogLevel): The loglevel to return if the input is invalid
Returns:
(LogLevel): The corresponding LogLevel
"""
default: Optional[LogLevel] = deep_get(kwargs, DictPath("default"))
severities = {
"F": LogLevel.EMERG,
"E": LogLevel.ERR,
"W": LogLevel.WARNING,
"N": LogLevel.NOTICE,
"C": LogLevel.NOTICE, # Used by jupyter for the login token
"I": LogLevel.INFO,
"D": LogLevel.DEBUG,
}
return severities.get(letter, default)
# Used by Kiali and kubeshark
def str_3letter_to_severity(string: str, **kwargs: Any) -> Optional[LogLevel]:
"""
Convert a 3-letter severity string to a LogLevel
Parameters:
letter (str): A 3-letter severity string
**kwargs (dict[str, Any]): Keyword arguments
default (LogLevel): The loglevel to return if the input is invalid
Returns:
(LogLevel): The corresponding LogLevel
"""
default: Optional[LogLevel] = deep_get(kwargs, DictPath("default"))
severities = {
"ERR": LogLevel.ERR,
"WRN": LogLevel.WARNING,
"INF": LogLevel.INFO,
}
return severities.get(string.upper(), default)
def str_4letter_to_severity(string: str, **kwargs: Any) -> Optional[LogLevel]:
"""
Convert a 4-letter severity string to a LogLevel
Parameters:
letter (str): A 4-letter severity string
**kwargs (dict[str, Any]): Keyword arguments
default (LogLevel): The loglevel to return if the input is invalid
Returns:
(LogLevel): The corresponding LogLevel
"""
default: Optional[LogLevel] = deep_get(kwargs, DictPath("default"))
severities = {
"CRIT": LogLevel.CRIT,
"FATA": LogLevel.CRIT,
"ERRO": LogLevel.ERR,
"WARN": LogLevel.WARNING,
"NOTI": LogLevel.NOTICE,
"SUCC": LogLevel.NOTICE, # From KubeRay
"INFO": LogLevel.INFO,
"DEBU": LogLevel.DEBUG,
}
return severities.get(string.upper(), default)
def str_to_severity(string: str, **kwargs: Any) -> Optional[LogLevel]:
"""
Convert a severity string to a LogLevel
Parameters:
letter (str): A severity string
**kwargs (dict[str, Any]): Keyword arguments
default (LogLevel): The loglevel to return if the input is invalid
Returns:
(LogLevel): The corresponding LogLevel
"""
default: Optional[LogLevel] = deep_get(kwargs, DictPath("default"))
severities = {
"fatal": LogLevel.CRIT,
"error": LogLevel.ERR,
"eror": LogLevel.ERR,
"warning": LogLevel.WARNING,
"warn": LogLevel.WARNING,
"notice": LogLevel.NOTICE,
"noti": LogLevel.NOTICE,
"info": LogLevel.INFO,
"debug": LogLevel.DEBUG,
"debu": LogLevel.DEBUG,
}
return severities.get(string.lower(), default)
def lvl_to_letter_severity(lvl: LogLevel) -> str:
"""
Convert a LogLevel to a 1-letter severity string
Parameters:
lvl (LogLevel): A LogLevel
Returns:
(str): The corresponding severity string
"""
severities = {
LogLevel.CRIT: "C",
LogLevel.ERR: "E",
LogLevel.WARNING: "W",
LogLevel.NOTICE: "N",
LogLevel.INFO: "I",
LogLevel.DEBUG: "D",
}
return severities.get(lvl, "!ERROR IN LOGPARSER!")
def lvl_to_4letter_severity(lvl: LogLevel) -> str:
"""
Convert a LogLevel to a 4-letter severity string
Parameters:
lvl (LogLevel): A LogLevel
Returns:
(str): The corresponding severity string
"""
severities = {
LogLevel.CRIT: "CRIT",
LogLevel.ERR: "ERRO",
LogLevel.WARNING: "WARN",
LogLevel.NOTICE: "NOTI",
LogLevel.INFO: "INFO",
LogLevel.DEBUG: "DEBU",
}
return severities.get(lvl, "!ERROR IN LOGPARSER!")
def lvl_to_word_severity(lvl: LogLevel) -> str:
"""
Convert a LogLevel to a severity string
Parameters:
lvl (LogLevel): A LogLevel
Returns:
(str): The corresponding severity string
"""
severities = {
LogLevel.CRIT: "CRITICAL",
LogLevel.ERR: "ERROR",
LogLevel.WARNING: "WARNING",
LogLevel.NOTICE: "NOTICE",
LogLevel.INFO: "INFO",
LogLevel.DEBUG: "DEBUG",
}
return severities.get(lvl, "!ERROR IN LOGPARSER!")
def split_bracketed_severity(message: str, **kwargs: Any) -> Tuple[str, LogLevel]:
"""
Remove a bracketed severity prefix from a string
Parameters:
message: A string to strip a severity prefix from
**kwargs (dict[str, Any]): Keyword arguments
default: The default severity to use if no LogLevel prefix can be found
Returns:
(str, LogLevel):
(str): The input string with the severity prefix removed
(LogLevel): The extracted LogLevel
"""
default: LogLevel = deep_get(kwargs, DictPath("default"), LogLevel.INFO)
severities = {
"[fatal]": LogLevel.CRIT,
# This is for ingress-nginx; while alert is higher than crit in syslog terms,
# ingress-nginx doesn't seem to use it that way.
"[alert]": LogLevel.ERR,
"[error]": LogLevel.ERR,
"[err]": LogLevel.ERR,
"[warning]": LogLevel.WARNING,
"[warn]": LogLevel.WARNING,
"[notice]": LogLevel.NOTICE,
"[info]": LogLevel.INFO,
"[system]": LogLevel.INFO, # MySQL seems to have its own loglevels
"[note]": LogLevel.INFO, # none of which makes every much sense
"[debug]": LogLevel.DEBUG,
}
tmp = re.match(r"^(\[[A-Za-z]+?\]) ?(.*)", message)
if tmp is not None:
if (severity := severities.get(tmp[1].lower())) is not None:
message = tmp[2]
else:
severity = default
else:
severity = default
return message, severity
def split_colon_severity(message: str, **kwargs: Any) -> Tuple[str, LogLevel]:
"""
Remove a colon severity prefix from a string
Parameters:
message (str): A string to strip a severity prefix from
**kwargs (dict[str, Any]): Keyword arguments
default: The default severity to use if no LogLevel prefix can be found
Returns:
(str, LogLevel):
(str): The input string with the severity prefix removed
(LogLevel): The extracted LogLevel
"""
default: LogLevel = deep_get(kwargs, DictPath("default"), LogLevel.INFO)
severities = {
"CRITICAL:": LogLevel.CRIT,
"ERROR:": LogLevel.ERR,
"WARNING:": LogLevel.WARNING,
"NOTICE:": LogLevel.NOTICE,
"NOTE:": LogLevel.NOTICE,
"INFO:": LogLevel.INFO,
"DEBUG:": LogLevel.DEBUG,
}
if (tmp := re.match(r"^([A-Za-z]+?:) ?(.*)", message)) is not None:
if (severity := severities.get(tmp[1].upper())) is not None:
message = tmp[2]
else:
severity = default
else:
severity = default
return message, severity
def is_timestamp(message: str) -> bool:
"""
Tries to check whether the field is a timestamp
Parameters:
message (str): The string to check
Returns:
(bool): True if the string is a timestamp, False if not
"""
tmp = re.match(r"^\d\.\d+e\+09", message)
if tmp is not None:
return True
tmp = re.match(r"^\d{4}[/-]\d\d[/-]\d\d"
r"[ T]"
r"\d\d[\.:]\d\d[\.:]\d\d"
r"([\.,]\d{8} [+-]\d\d[:\.]\d\d|"
r"[\.,]\d{6} [+-]\d\d[:\.]\d\d|"
r"[\.,]\d{3} [+-]\d\d[:\.]\d\d|"
r"[\.,]\d{8}Z?|"
r"[\.,]\d{6}Z?|"
r"[\.,]\d{3}Z?|"
r"Z?)$", message)
if tmp is not None:
return True
return False
# pylint: disable-next=too-many-statements
def split_iso_timestamp(message: str, timestamp: datetime) -> Tuple[str, datetime]:
"""
Split a message into timestamp and remaining message
Parameters:
message (str): The message to strip the timestamp from
timestamp (datetime): The datetime to return if the message doesn't have a timestamp
Returns:
(str, datetime): Return the remainder of the message and the datetime
"""
old_timestamp = timestamp
tmp_timestamp = ""
# This while loop is merely to allow for breaking out anywhere
while True:
# 2020-02-07 13:12:24.224
# 2020-02-07 13:12:24,224
# [2020-02-07 13:12:24.224]
# [2020-02-07 13:12:24,224]
tmp = re.match(r"^\[?(\d{4}-\d\d-\d\d) (\d\d:\d\d:\d\d)(,|\.)(\d+)\]? ?(.*)", message)
if tmp is not None:
ymd = tmp[1]
hms = tmp[2]
# This just matches the separator; we don't use it
# _sep = tmp[3]
ms = tmp[4]
tmp_timestamp = f"{ymd} {hms}.{ms}+0000"
message = tmp[5]
break
# 2020-02-07T13:12:24.224Z (Z = UTC)
tmp = re.match(r"^(\d{4}-\d\d-\d\d)T(\d\d:\d\d:\d\d\.\d+)Z ?(.*)", message)
if tmp is not None:
ymd = tmp[1]
hmsms = tmp[2][0:len("HH:MM:SS.sss")]
tmp_timestamp = f"{ymd} {hmsms}+0000"
message = tmp[3]
break
# 2020-02-13T12:06:18.011345 [+-]00:00 (+timezone)
# 2020-09-23T17:12:32.183967091[+-]03:00
tmp = re.match(r"^(\d{4}-\d\d-\d\d)T(\d\d:\d\d:\d\d\.\d+) ?([\+-])(\d\d):(\d\d) ?(.*)",
message)
if tmp is not None:
ymd = tmp[1]
hmsms = tmp[2][0:len("HH:MM:SS.sss")]
tzsign = tmp[3]
tzhour = tmp[4]
tzmin = tmp[5]
tmp_timestamp = f"{ymd} {hmsms}{tzsign}{tzhour}{tzmin}"
message = tmp[6]
break
# 2020-02-13 12:06:18[+-]00:00 (+timezone)
# [2020-02-13 12:06:18 [+-]00:00] (+timezone)
# 2020-02-13T12:06:18[+-]0000 (+timezone)
tmp = re.match(r"^\[?(\d{4}-\d\d-\d\d)[ T](\d\d:\d\d:\d\d) ?([\+-])(\d\d):?(\d\d)\]? ?(.*)",
message)
if tmp is not None:
ymd = tmp[1]
hms = tmp[2]
tzsign = tmp[3]
tzhour = tmp[4]
tzmin = tmp[5]
tmp_timestamp = f"{ymd} {hms}.000{tzsign}{tzhour}{tzmin}"
message = tmp[6]
break
# 2020-02-20 13:47:41.008416 (assume UTC)
# 2020-02-20 13:47:41.008416: (assume UTC)
# 2020/02/20 13:47:41.008416 (assume UTC)
# 2020-02-20 13:47:41.008416Z (Z = UTC)
tmp = re.match(r"^(\d{4})[-/](\d\d)[-/](\d\d) (\d\d:\d\d:\d\d\.\d+)[Z:]? ?(.*)", message)
if tmp is not None:
year = tmp[1]
month = tmp[2]
day = tmp[3]
hmsms = tmp[4][0:len("HH:MM:SS.sss")]
tmp_timestamp = f"{year}-{month}-{day} {hmsms}+0000"
message = tmp[5]
break
# [2021-12-18T20:15:36Z]
# 2021-12-18T20:15:36Z
tmp = re.match(r"^\[?(\d{4}-\d\d-\d\d)T(\d\d:\d\d:\d\d)Z\]? ?(.*)", message)
if tmp is not None:
ymd = tmp[1]
hms = tmp[2]
tmp_timestamp = f"{ymd} {hms}.000+0000"
message = tmp[3]
break
# 2020-02-20 13:47:41 (assume UTC)
# 2020/02/20 13:47:41 (assume UTC)
tmp = re.match(r"^(\d{4})[-/](\d\d)[-/](\d\d) (\d\d:\d\d:\d\d) ?(.*)", message)
if tmp is not None:
year = tmp[1]
month = tmp[2]
day = tmp[3]
hms = tmp[4]
tmp_timestamp = f"{year}-{month}-{day} {hms}.000+0000"
message = tmp[5]
break
break
if old_timestamp == none_timestamp() and tmp_timestamp:
timestamp = datetime.strptime(tmp_timestamp, "%Y-%m-%d %H:%M:%S.%f%z")
# message + (timestamp|none_timestamp()) is passed in,
# so it is safe just to return it too.
return message, timestamp
def strip_iso_timestamp(message: str) -> str:
"""
Given a string with a timestamp, return that string without the timestamp
Parameters:
message (str): The message to strip
Returns:
(str): The stripped message
"""
message, _timestamp = split_iso_timestamp(message, none_timestamp())
return message
# 2020-02-20 13:47:01.531 GMT
def strip_iso_timestamp_with_tz(message: str) -> str:
"""
Given a string with a timestamp and timezone, return that string without the timestamp
Parameters:
message (str): The message to strip
Returns:
(str): The stripped message
"""
tmp = re.match(r"^\d{4}-\d\d-\d\d \d\d:\d\d:\d\d\.\d\d\d [A-Z]{3}(\s+?|$)(.*)", message)
if tmp is not None:
message = tmp[2]
return message
# pylint: disable-next=too-many-locals,too-many-arguments,too-many-branches
def iptables(message: str,
remnants: List[Tuple[List[Union[ThemeRef, ThemeStr]], LogLevel]], **kwargs: Any) \
-> Tuple[List[Union[ThemeRef, ThemeStr]], Optional[LogLevel], str,
List[Tuple[List[Union[ThemeRef, ThemeStr]], Optional[LogLevel]]]]:
"""
Format output from iptables-save
Parameters:
message (str): The message part of the msg to format
remnants (list[(themearray, severity)]): The remnants part of the msg to format
**kwargs (dict[str, Any]): Keyword arguments
severity (LogLevel): The log severity
facility (str): The log facility
fold_msg (bool): Should the message be expanded or folded?
options (dict): Additional, rule specific, options
Returns:
(ThemeArray, LogLevel, str, [(ThemeArray, LogLevel)]):
(ThemeArray): The formatted message
(LogLevel): The LogLevel of the message
(str): The facility of the message
([(ThemeArray, LogLevel)]):
(ThemeArray): The formatted strings of the remnant
(LogLevel): The severity of the remnant
"""
severity: Optional[LogLevel] = deep_get(kwargs, DictPath("severity"), LogLevel.INFO)
facility: str = deep_get(kwargs, DictPath("facility"), "")
fold_msg: bool = deep_get(kwargs, DictPath("fold_msg"), True)
new_message: List[Union[ThemeRef, ThemeStr]] = []
new_remnants: List[Tuple[List[Union[ThemeRef, ThemeStr]], Optional[LogLevel]]] = []
old_messages: List[str] = []
if fold_msg and "\\n" in message:
old_messages = message.split("\\n")
else:
old_messages.append(message)
for themearray, _loglevel in remnants:
old_messages.append(themearray_to_string(themearray))
for i, items in enumerate(old_messages):
tmp_message: List[Union[ThemeRef, ThemeStr]] = []
for j, item in enumerate(items.split(" ")):
if not j:
if item.startswith(("/usr/sbin/iptables", "/sbin/iptables")):
tmp_message.append(ThemeStr(item,
ThemeAttr("types", "iptables_programname")))
elif item.startswith("*"):
tmp_message.append(ThemeStr(item,
ThemeAttr("types", "iptables_table")))
elif item.startswith(":"):
tmp_message.append(ThemeStr(item,
ThemeAttr("types", "iptables_chain")))
elif item.startswith("COMMIT"):
tmp_message.append(ThemeStr(item,
ThemeAttr("types", "iptables_command")))
elif item.startswith("#"):
tmp_message.append(ThemeStr(items[j:],
ThemeAttr("types", "iptables_comment")))
break
elif item.startswith("-"):
tmp_message.append(ThemeStr(f" {item}",
ThemeAttr("types", "iptables_option")))
elif item.startswith("#"):
tmp_message.append(ThemeStr(" ",
ThemeAttr("types", "iptables_comment")))
tmp_message.append(ThemeStr(" ".join(item[j:]),
ThemeAttr("types", "iptables_comment")))
break
else:
tmp_message.append(ThemeStr(f" {item}",
ThemeAttr("types", "iptables_argument")))
if not i:
new_message = tmp_message
else:
new_remnants.append((tmp_message, severity))
if fold_msg and "\\n" in message:
for remnant, _severity in new_remnants:
new_message.append(ThemeRef("separators", "newline"))
new_message += remnant
new_remnants = []
return new_message, severity, facility, new_remnants
# pylint: disable-next=too-many-locals,too-many-branches,too-many-statements
def http(message: str,
**kwargs: Any) -> Tuple[Sequence[Union[ThemeRef, ThemeStr]], LogLevel, str]:
"""
Format various http log style messages
Parameters:
message (str): The message to format
**kwargs (dict[str, Any]): Keyword arguments
severity (LogLevel): The log severity
facility (str): The log facility
options (dict): Additional, rule specific, options
Returns:
(ThemeArray, LogLevel, str):
(ThemeArray): The formatted string
(LogLevel): The new loglevel
"""
severity: Optional[LogLevel] = deep_get(kwargs, DictPath("severity"), LogLevel.INFO)
facility: str = deep_get(kwargs, DictPath("facility"), "")
options: Optional[Dict] = deep_get(kwargs, DictPath("options"))
reformat_timestamps = deep_get(options, DictPath("reformat_timestamps"), False)
ipaddress = ""
# If the message starts with a timestamp without a leading IP-address, skip this
if not message.startswith("["):
# First try to check if it's an IP-address
tmp = re.match(r"^([a-f0-9:][a-f0-9:.]+[a-f0-9])( - - .*)", message)
if tmp is not None:
# Just pass-through if validators isn't installed;
# this might lead to false positives, but it's better than
# not working at all
if validators is None or validators.ipv4(tmp[1]) or validators.ipv6(tmp[1]):
ipaddress = tmp[1]
message = tmp[2]
# Short format
if ipaddress:
tmp = re.match(r"( - - )" # separator1
r"(\[)" # separator2
r"(\d\d)" # day
r"/"
r"([A-Z][a-z][a-z])" # _month
r"/"
r"(\d{4})" # year
r" "
r"(\d\d:\d\d:\d\d)" # hms
r"(\])" # separator3
r"(\s\")" # separator4
r"([A-Z]*?\s)" # verb
r"(\S*?)" # address3
r"(\s\S*?)" # protocol
r"(\"\s)" # separator5
r"(\d+?)" # statuscode
r"(\s+[\d-]+?$)", message) # separator6
if tmp is not None:
address1 = ipaddress
separator1 = tmp[1]
separator2 = tmp[2]
day = tmp[3]
_month = tmp[4]
month = month_to_numerical(_month)
year = tmp[5]
hms = tmp[6]
if reformat_timestamps:
ts = f"{year}-{month}-{day} {hms}"
else:
ts = f"{day}/{_month}/{year}:{hms}"
separator3 = tmp[7]
separator4 = tmp[8]
verb = tmp[9]
address3 = tmp[10]
protocol = tmp[11]
separator5 = tmp[12]
statuscode = tmp[13]
_statuscode = int(statuscode)
if 100 <= _statuscode < 300:
severity = LogLevel.NOTICE
elif 300 <= _statuscode < 400:
severity = LogLevel.WARNING
else:
severity = LogLevel.ERR
separator6 = tmp[14]
new_message: Sequence[Union[ThemeRef, ThemeStr]] = [
ThemeStr(address1, ThemeAttr("logview", "hostname")),
ThemeStr(separator1, ThemeAttr("logview", "severity_info")),
ThemeStr(f"{separator2}{ts}{separator3}", ThemeAttr("logview", "timestamp")),
ThemeStr(separator4, ThemeAttr("logview", "severity_info")),
ThemeStr(verb, ThemeAttr("logview", "protocol")),
ThemeStr(address3, ThemeAttr("logview", "url")),
ThemeStr(protocol, ThemeAttr("logview", "protocol")),
ThemeStr(separator5, ThemeAttr("logview", "severity_info")),
ThemeStr(statuscode,
ThemeAttr("logview", f"severity_{loglevel_to_name(severity).lower()}")),
ThemeStr(separator6, ThemeAttr("logview", "severity_info")),
]
return new_message, severity, facility
if ipaddress:
tmp = re.match(r"( - - )"
r"(\[)"
r"(\d\d)"
r"/"
r"([A-Z][a-z][a-z])"
r"/"
r"(\d{4})"
r":"
r"(\d\d:\d\d:\d\d)"
r"(\s\+\d{4}|\s-\d{4})"
r"(\])"
r"(\s\")"
r"([A-Z]*?\s)"
r"(\S*?)"
r"(\s\S*?)"
r"(\"\s)"
r"(\d+?)"
r"(\s+\d+?\s\")"
r"([^\"]*)"
r"(\")"
r"(\s|$)"
r"(\"|.*$)"
r"([^\"]*|$)"
r"(\"|$)"
r"(\s.*$|$)", message)
if tmp is not None:
address1 = ipaddress
separator1 = tmp[1]
separator2 = tmp[2]
day = tmp[3]
_month = tmp[4]
month = month_to_numerical(_month)
year = tmp[5]
hms = tmp[6]
tz = tmp[7]
if reformat_timestamps:
ts = f"{year}-{month}-{day} {hms}{tz}"
else:
ts = f"{day}/{_month}/{year}:{hms}{tz}"
separator3 = tmp[8]
separator4 = tmp[9]
verb = tmp[10]
address3 = tmp[11]
protocol = tmp[12]
separator5 = tmp[13]
statuscode = tmp[14]
_statuscode = int(statuscode)
if 100 <= _statuscode < 300:
severity = LogLevel.NOTICE
elif 300 <= _statuscode < 400:
severity = LogLevel.WARNING
else:
severity = LogLevel.ERR
separator6 = tmp[15]
address4 = tmp[16]
separator7 = tmp[17] + tmp[18] + tmp[19]
address5 = tmp[20]
separator8 = tmp[21]
remainder = tmp[22]
severity_name = f"severity_{loglevel_to_name(severity).lower()}"
new_message = [
ThemeStr(address1, ThemeAttr("logview", "hostname")),
ThemeStr(separator1, ThemeAttr("logview", "severity_info")),
ThemeStr(f"{separator2}{ts}{separator3}", ThemeAttr("logview", "timestamp")),
ThemeStr(separator4, ThemeAttr("logview", "severity_info")),
ThemeStr(verb, ThemeAttr("logview", "protocol")),
ThemeStr(address3, ThemeAttr("logview", "url")),
ThemeStr(protocol, ThemeAttr("logview", "protocol")),
ThemeStr(separator5, ThemeAttr("logview", "severity_info")),
ThemeStr(statuscode, ThemeAttr("logview", severity_name)),
ThemeStr(separator6, ThemeAttr("logview", "severity_info")),
ThemeStr(address4, ThemeAttr("logview", "url")),
ThemeStr(separator7, ThemeAttr("logview", "severity_info")),
]
if address5 is not None:
new_message.append(ThemeStr(address5, ThemeAttr("logview", "url")))
new_message.append(ThemeStr(separator8, ThemeAttr("logview", "severity_info")))
if remainder is not None:
new_message.append(ThemeStr(remainder, ThemeAttr("types", "generic")))
return new_message, severity, facility
# Alternate formats
tmp = re.match(r"^\|\s+"
r"(\d{3})" # statuscode
r"\s+\|\s+"
r"([0-9.]+)" # duration
r"([^ ]*)" # unit
r"\s+\|\s+"
r"([^:^\s]*)" # hostname
r":(\d+?)" # port
r"\s+\|\s+"
r"([A-Z]+)" # verb
r"\s+"
r"(.*)", message) # url
if tmp is not None:
statuscode = tmp[1]
_statuscode = int(statuscode)
if 100 <= _statuscode < 300:
severity = LogLevel.NOTICE
elif 300 <= _statuscode < 400:
severity = LogLevel.WARNING
else:
severity = LogLevel.ERR
duration = tmp[2]
unit = tmp[3]
hostname = tmp[4]
port = tmp[5]
verb = tmp[6]
url = tmp[7]
severity_name = f"severity_{loglevel_to_name(severity).lower()}"
new_message = [
ThemeStr("| ", ThemeAttr("logview", "severity_info")),
ThemeStr(statuscode, ThemeAttr("logview", severity_name)),
ThemeStr(" | ", ThemeAttr("logview", "severity_info")),
ThemeStr(duration, ThemeAttr("logview", "severity_info")),
ThemeStr(unit, ThemeAttr("types", "unit")),
ThemeStr(" | ", ThemeAttr("logview", "severity_info")),
ThemeStr(hostname, ThemeAttr("logview", "hostname")),
ThemeRef("separators", "port"),
ThemeStr(port, ThemeAttr("types", "port")),
ThemeStr(" | ", ThemeAttr("logview", "severity_info")),
ThemeStr(verb, ThemeAttr("logview", "protocol")),
ThemeStr(" ", ThemeAttr("logview", "severity_info")),
ThemeStr(url, ThemeAttr("logview", "url")),
]
return new_message, severity, facility
tmp = re.match(r"^\["
r"(\d{4}-\d\d-\d\d)"
r"T"
r"(\d\d:\d\d:\d\d\.\d\d\d)Z"
r"\] \""
r"([A-Z]+)"
r"\s"
r"([^\s]+)"
r"\s"
r"([^\"]+)"
r"\" "
r"([\d]+)"
r" ([^\s]+)"
r" ([^\s]+)"
r" ([^\s]+)"
r" ([^\s]+)"
r" ([^\s]+) "
r"\"([^\"]+)\" "
r"\"([^\"]+)\" "
r"\"([^\"]+)\" "
r"\"([^\"]+)\" "
r"\"([^\"]+)\"", message)
if tmp is not None:
date = tmp[1]
hmsms = tmp[2]
if reformat_timestamps:
ts = f"{date} {hmsms} +0000"
else:
ts = f"{date}T{hmsms}Z"
verb = tmp[3]
address1 = tmp[4]
protocol = tmp[5]
statuscode = tmp[6]
_statuscode = int(statuscode)
if 100 <= _statuscode < 300:
severity = LogLevel.NOTICE
elif 300 <= _statuscode < 400:
severity = LogLevel.WARNING
else:
severity = LogLevel.ERR
severity_name = f"severity_{loglevel_to_name(severity).lower()}"
number0 = tmp[7]
number1 = tmp[8]
number2 = tmp[9]
number3 = tmp[10]
number4 = tmp[11]
client = tmp[12]
str0 = tmp[13]
str1 = tmp[14]
str2 = tmp[15]
str3 = tmp[16]
new_message = [
ThemeStr(f"[{ts}] ", ThemeAttr("logview", "timestamp")),
ThemeStr("\"", ThemeAttr("logview", "severity_info")),
ThemeStr(f"{verb} ", ThemeAttr("logview", "protocol")),
ThemeStr(address1, ThemeAttr("logview", "url")),
ThemeStr(f" {protocol}", ThemeAttr("logview", "protocol")),
ThemeStr("\" ", ThemeAttr("logview", "severity_info")),
ThemeStr(statuscode, ThemeAttr("logview", severity_name)),
ThemeStr(f" {number0}", ThemeAttr("logview", "severity_info")),
ThemeStr(f" {number1}", ThemeAttr("logview", "severity_info")),
ThemeStr(f" {number2}", ThemeAttr("logview", "severity_info")),
ThemeStr(f" {number3}", ThemeAttr("logview", "severity_info")),
ThemeStr(f" {number4} \"", ThemeAttr("logview", "severity_info")),