-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathcheck_log_ng.py
executable file
·1401 lines (1250 loc) · 49.4 KB
/
check_log_ng.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 python
# -*- coding: utf-8 -*-
"""A log file regular expression-based parser plugin for Nagios.
Features are as follows:
- You can specify the character string you want to detect with regular
expressions.
- You can specify the character string you do not want to detect with
regular expressions.
- You can specify the character encoding of a log file.
- You can check multiple log files at once and also check log-rotated files.
- This script uses seek files which record the position where the check is
completed for each log file.
With these seek files, you can check only the differences from the last check.
- You can check multiple lines outputted at once as one message.
- The result can be cached within the specified time period.
This will help multiple monitoring servers and multiple attempts.
This module is available in Python 2.6, 2.7, 3.5, 3.6.
Require argparse module in python 2.6.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import sys
import os
import io
import glob
import time
import re
import hashlib
import base64
import fcntl
import warnings
FALLBACK_PATH = "/usr/local/hb-agent/bin"
try:
import argparse
except ImportError as _ex:
if __name__ != "__main__":
raise _ex
if FALLBACK_PATH not in os.environ["PATH"]:
os.environ["PATH"] = ":".join([FALLBACK_PATH, os.environ["PATH"]])
os.execve(__file__, sys.argv, os.environ)
else:
raise _ex
# Globals
__version__ = '2.0.8'
class LogChecker(object):
"""LogChecker."""
# Class constant
STATE_OK = 0
STATE_WARNING = 1
STATE_CRITICAL = 2
STATE_UNKNOWN = 3
STATE_DEPENDENT = 4
STATE_NO_CACHE = -1
FORMAT_SYSLOG = (
r'^((?:%b\s%e\s%T|%FT%T\S*)\s'
r'[-_0-9A-Za-z.]+\s'
r'(?:[^ :\[\]]+(?:\[\d+?\])?:\s)?)'
r'(.*)$')
'''FORMAT_SYSLOG is `^(TIMESTAMP HOSTNAME (TAG )?)(MSG)$`.'''
_SUFFIX_SEEK = ".seek"
_SUFFIX_SEEK_WITH_INODE = ".inode.seek"
_SUFFIX_CACHE = ".cache"
_SUFFIX_LOCK = ".lock"
_RETRY_PERIOD = 0.5
_LOGFORMAT_EXPANSION_LIST = [
{'%%': '_PERCENT_'},
{'%F': '%Y-%m-%d'},
{'%T': '%H:%M:%S'},
{'%a': '(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)'},
{'%b': '(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)'},
{'%Y': '20[0-9][0-9]'},
{'%y': '[0-9][0-9]'},
{'%m': '(?:0[1-9]|1[0-2])'},
{'%d': '(?:0[1-9]|[12][0-9]|3[01])'},
{'%e': '(?: [1-9]|[12][0-9]|3[01])'},
{'%H': '(?:[01][0-9]|2[0-3])'},
{'%M': '[0-5][0-9]'},
{'%S': '(?:[0-5][0-9]|60)'},
{'_PERCENT_': '%'},
]
def __init__(self, config):
"""Constructor.
The keys of configuration parameters are::
logformat (str): Regular expression for log format.
state_directory (str): The directory to store seek files, cache
file and lock file.
pattern_list (list): The list of regular expressions to scan for
in the log file.
critical_pattern_list (list): The list of regular expressions to
scan for in the log file. If found, return CRITICAL.
negpattern_list (list): The list of regular expressions which all
will be skipped except as critical pattern in the log file.
critical_negpattern_list (list): The list of regular expressions
which all will be skipped except as critical pattern in the
log file. If found, return CRITICAL.
case_insensitive (bool): Do a case insensitive scan.
encoding (str): Specify the character encoding in the log file.
warning (int): The number of times found that be needed to return WARNING.
critical (int): The number of times found that be needed to return CRITICAL.
trace_inode (bool): Trace the inode of the log file.
multiline (bool): Treat multiple lines outputted at once as one message.
scantime (int): The range of time to scan.
expiration (int): The expiration of seek files.
cachetime (int): The period to cache the result.
lock_timeout (int): The period to wait for if another process is running.
output_header (bool): Suppress the output of the message on matched lines.
quiet (bool): Suppress output of matched lines.
Args:
config (dict): The dictionary of configuration parameters.
"""
# set default value
self.config = {}
self.config['dry_run'] = False
self.config['logformat'] = LogChecker.FORMAT_SYSLOG
self.config['state_directory'] = None
self.config['pattern_list'] = []
self.config['critical_pattern_list'] = []
self.config['negpattern_list'] = []
self.config['critical_negpattern_list'] = []
self.config['case_insensitive'] = False
self.config['encoding'] = 'utf-8'
self.config['warning'] = 1
self.config['critical'] = 0
self.config['trace_inode'] = False
self.config['multiline'] = False
self.config['scantime'] = 86400
self.config['expiration'] = 691200
self.config['cachetime'] = 60
self.config['lock_timeout'] = 3
self.config['output_header'] = False
self.config['output_quiet'] = False
# overwrite values with user's values
for key in self.config:
if key not in config:
continue
value = config[key]
if isinstance(value, (bool, int)):
pass
elif isinstance(value, list):
value = [LogChecker.to_unicode(x) for x in value]
else:
# On python 2.x, str, unicode or None reaches.
# On python 3.x, bytes, str or None reaches.
value = LogChecker.to_unicode(value)
self.config[key] = value
self.pattern_flags = 0
if self.config['case_insensitive']:
self.pattern_flags = re.IGNORECASE
self.re_logformat = re.compile(LogChecker._expand_logformat_by_strftime(
self.config['logformat']))
_debug("logformat='{0}'".format(self.re_logformat.pattern))
# status variables
self.state = None
self.message = None
self.messages = []
self.found = []
self.found_messages = []
self.critical_found = []
self.critical_found_messages = []
def _check_updated(self, logfile, offset, filesize):
"""Check whether the log file is updated.
If updated, return True.
"""
if os.stat(logfile).st_mtime < time.time() - self.config['scantime']:
_debug("Skipped: mtime < curtime - scantime")
return False
if filesize == offset:
_debug("Skipped: filesize == offset")
return False
return True
def _find_pattern(self, message, negative=False, critical=False):
"""Find pattern.
If found, return True.
"""
if negative:
if critical:
pattern_list = self.config['critical_negpattern_list']
pattern_type = "critical_negpattern"
else:
pattern_list = self.config['negpattern_list']
pattern_type = "negpattern"
else:
if critical:
pattern_list = self.config['critical_pattern_list']
pattern_type = "critical_pattern"
else:
pattern_list = self.config['pattern_list']
pattern_type = "pattern"
if not pattern_list:
return False
for pattern in pattern_list:
if not pattern:
continue
matchobj = re.search(pattern, message, self.pattern_flags)
if matchobj:
_debug("{0}: '{1}' found".format(pattern_type, pattern))
return True
return False
def _remove_old_seekfile(self, logfile_pattern_list, tag=''):
"""Remove old seek files."""
if self.config['dry_run']:
return True
cwd = os.getcwd()
try:
os.chdir(self.config['state_directory'])
except OSError:
LogChecker.print_message("Unable to chdir: {0}".format(
self.config['state_directory']))
sys.exit(LogChecker.STATE_UNKNOWN)
curtime = time.time()
for logfile_pattern in logfile_pattern_list.split():
if not logfile_pattern:
continue
seekfile_pattern = (
re.sub(r'[^-0-9A-Za-z*?]', '_', logfile_pattern) +
tag + LogChecker._SUFFIX_SEEK)
for seekfile in glob.glob(seekfile_pattern):
if not os.path.isfile(seekfile):
continue
if curtime - self.config['expiration'] <= os.stat(seekfile).st_mtime:
continue
try:
_debug("remove seekfile: {0}".format(seekfile))
os.unlink(seekfile)
except OSError:
LogChecker.print_message("Unable to remove old seekfile: {0}".format(
seekfile))
sys.exit(LogChecker.STATE_UNKNOWN)
try:
os.chdir(cwd)
except OSError:
LogChecker.print_message("Unable to chdir: {0}".format(cwd))
sys.exit(LogChecker.STATE_UNKNOWN)
return True
def _remove_old_seekfile_with_inode(self, logfile_pattern, tag=''):
"""Remove old inode-based seek files."""
if self.config['dry_run']:
return True
prefix = None
if self.config['trace_inode']:
prefix = LogChecker.get_digest(logfile_pattern)
cwd = os.getcwd()
try:
os.chdir(self.config['state_directory'])
except OSError:
LogChecker.print_message("Unable to chdir: {0}".format(
self.config['state_directory']))
sys.exit(LogChecker.STATE_UNKNOWN)
curtime = time.time()
seekfile_pattern = "{0}.[0-9]*{1}{2}".format(
prefix, tag, LogChecker._SUFFIX_SEEK_WITH_INODE)
for seekfile in glob.glob(seekfile_pattern):
if not os.path.isfile(seekfile):
continue
if curtime - self.config['expiration'] <= os.stat(seekfile).st_mtime:
continue
try:
_debug("remove seekfile: {0}".format(seekfile))
os.unlink(seekfile)
except OSError:
LogChecker.print_message("Unable to remove old seekfile: {0}".format(seekfile))
sys.exit(LogChecker.STATE_UNKNOWN)
try:
os.chdir(cwd)
except OSError:
LogChecker.print_message("Unable to chdir: {0}".format(cwd))
sys.exit(LogChecker.STATE_UNKNOWN)
return True
def _get_logfile_list(self, filename_pattern_list):
"""Get the list of log files from pattern of filenames."""
logfile_list = []
for filename_pattern in filename_pattern_list.split():
filename_list = glob.glob(filename_pattern)
if filename_list:
logfile_list.extend(filename_list)
if logfile_list:
logfile_list = sorted(
logfile_list, key=lambda x: os.stat(x).st_mtime)
return logfile_list
def _update_state(self):
"""Update the state of the result."""
output_mode = None
if self.config['output_quiet']:
output_mode = "QUIET"
elif self.config['output_header']:
output_mode = "HEADER"
num_critical = len(self.critical_found)
if num_critical > 0:
self.state = LogChecker.STATE_CRITICAL
if output_mode:
self.messages.append("Critical Found {0} lines ({1}): {2}".format(
num_critical, output_mode, ','.join(self.critical_found_messages)))
else:
self.messages.append("Critical Found {0} lines: {1}".format(
num_critical, ','.join(self.critical_found_messages)))
num = len(self.found)
if num > 0:
if output_mode:
self.messages.append(
"Found {0} lines (limit={1}/{2}, {3}): {4}".format(
num, self.config['warning'], self.config['critical'],
output_mode, ','.join(self.found_messages)))
else:
self.messages.append(
"Found {0} lines (limit={1}/{2}): {3}".format(
num, self.config['warning'], self.config['critical'],
','.join(self.found_messages)))
if self.config['critical'] > 0 and self.config['critical'] <= num:
if self.state is None:
self.state = LogChecker.STATE_CRITICAL
if self.config['warning'] > 0 and self.config['warning'] <= num:
if self.state is None:
self.state = LogChecker.STATE_WARNING
if self.state is None:
self.state = LogChecker.STATE_OK
return
def _update_message(self):
state_string = 'OK'
message = 'OK - No matches found.'
if self.state == LogChecker.STATE_WARNING:
state_string = 'WARNING'
elif self.state == LogChecker.STATE_CRITICAL:
state_string = 'CRITICAL'
if self.state != LogChecker.STATE_OK:
message = "{0}: {1}".format(state_string, ', '.join(self.messages))
message = message.replace('|', '(pipe)')
self.message = message
return
def _set_found(self, header, message, found, critical_found):
"""Set the found and critical_found if matching pattern is found."""
_debug("header='{0}', message='{1}'".format(header, message))
log_message = ''.join([header, message])
found_negpattern = self._find_pattern(log_message, negative=True)
found_critical_negpattern = self._find_pattern(
log_message, negative=True, critical=True)
if not found_negpattern and not found_critical_negpattern:
if self._find_pattern(log_message):
found.append({"header": header, "message": message})
if not found_critical_negpattern:
if self._find_pattern(log_message, critical=True):
critical_found.append({"header": header, "message": message})
return
def _check_each_multiple_lines(
self, logfile, start_position, found, critical_found):
"""Match the pattern each multiple lines in the log file."""
messages = []
previous_header = None
header = None
message = None
with io.open(logfile, mode='r', encoding=self.config['encoding'],
errors='replace') as fileobj:
fileobj.seek(start_position, 0)
for line in fileobj:
line = line.rstrip()
_debug("line='{0}'".format(line))
matchobj = self.re_logformat.match(line)
if matchobj:
header = matchobj.group(1)
message = matchobj.group(2)
_debug(" logformat: header='{0}', message='{1}'".format(
header, message))
else:
_debug(" logformat: unmatched")
if previous_header is None:
if self.config['dry_run']:
LogChecker.print_message("[DRY RUN] Log format does not match. Set --format option.")
sys.exit(LogChecker.STATE_UNKNOWN)
else:
# If you do not enable dry run, ignore log format errors.
previous_header = ''
# assume it is continuation
header = previous_header
message = line
if previous_header is not None and previous_header != header:
# The current line is a new log line.
self._set_found(previous_header, ' '.join(messages), found, critical_found)
messages = []
previous_header = header
messages.append(message)
end_position = fileobj.tell()
fileobj.close()
# flush
if messages:
self._set_found(header, ' '.join(messages), found, critical_found)
return end_position
def _check_each_single_line(
self, logfile, start_position, found, critical_found):
"""Match the pattern each a single line in the log file."""
with io.open(logfile, mode='r', encoding=self.config['encoding'],
errors='replace') as fileobj:
fileobj.seek(start_position, 0)
for line in fileobj:
line = line.rstrip()
_debug("line='{0}'".format(line))
matchobj = self.re_logformat.match(line)
if matchobj:
header = matchobj.group(1)
message = matchobj.group(2)
_debug(" logformat: header='{0}', message='{1}'".format(
header, message))
else:
_debug(" logformat: unmatched")
if self.config['dry_run']:
LogChecker.print_message("[DRY RUN] Log format does not match. Set --format option.")
sys.exit(LogChecker.STATE_UNKNOWN)
else:
# If you do not enable dry run, ignore log format errors.
header = ''
message = line
self._set_found(header, message, found, critical_found)
end_position = fileobj.tell()
fileobj.close()
return end_position
def _create_digest_condition(self, logfile_pattern):
"""Create the digest of search conditions."""
strings = []
for key in sorted(self.config):
if key in ['expiration', 'cachetime', 'lock_timeout']:
continue
value = self.config[key]
if isinstance(value, list):
strings.append(
"{0}={1}".format(key, "\t".join(value)))
elif isinstance(value, bool):
strings.append(
"{0}={1}".format(key, LogChecker.to_unicode(str(value))))
elif isinstance(value, int):
strings.append(
"{0}={1}".format(key, LogChecker.to_unicode(str(value))))
else:
strings.append("{0}={1}".format(key, value))
strings.append(logfile_pattern)
digest_condition = LogChecker.get_digest('\n'.join(strings))
return digest_condition
def _create_seek_filename(
self, logfile_pattern, logfile, trace_inode=False, tag=''):
"""Return the file name of seek file."""
prefix = None
filename = None
if trace_inode:
filename = (str(os.stat(logfile).st_ino) +
tag + LogChecker._SUFFIX_SEEK_WITH_INODE)
prefix = LogChecker.get_digest(logfile_pattern)
else:
filename = (re.sub(r'[^-0-9A-Za-z]', '_', logfile) +
tag + LogChecker._SUFFIX_SEEK)
if prefix:
filename = prefix + '.' + filename
seekfile = os.path.join(self.config['state_directory'], filename)
return seekfile
def _create_cache_filename(self, logfile_pattern, tag=''):
"""Return the file name of cache file."""
digest_condition = self._create_digest_condition(logfile_pattern)
filename_elements = []
filename_elements.append(digest_condition)
if tag:
filename_elements.append(".")
filename_elements.append(tag)
filename_elements.append(LogChecker._SUFFIX_CACHE)
cache_filename = os.path.join(
self.config['state_directory'], "".join(filename_elements))
return cache_filename
def _create_lock_filename(self, logfile_pattern, tag=''):
"""Return the file name of lock file."""
digest_condition = self._create_digest_condition(logfile_pattern)
filename_elements = []
filename_elements.append(digest_condition)
if tag:
filename_elements.append(".")
filename_elements.append(tag)
filename_elements.append(LogChecker._SUFFIX_LOCK)
lock_filename = os.path.join(
self.config['state_directory'], "".join(filename_elements))
return lock_filename
def check(
self, logfile_pattern, seekfile=None,
remove_seekfile=False, tag=''):
"""Check log files.
If cache is enabled and exists, return cache.
Args:
logfile_pattern (str): The file names of log files to be scanned.
seekfile (str, optional): The file name of the seek file.
remove_seekfile (bool, optional): If true, remove expired seek files.
tag (str, optional): The tag added in the file names of state files,
to prevent names collisions.
"""
logfile_pattern = LogChecker.to_unicode(logfile_pattern)
seekfile = LogChecker.to_unicode(seekfile)
tag = LogChecker.to_unicode(tag)
cachefile = self._create_cache_filename(logfile_pattern, tag=tag)
lockfile = self._create_lock_filename(logfile_pattern, tag=tag)
locked = False
cur_time = time.time()
timeout_time = cur_time + self.config['lock_timeout']
while cur_time < timeout_time:
if self.config['cachetime'] > 0:
state, message = self._get_cache(cachefile)
if state != LogChecker.STATE_NO_CACHE:
self.state = state
self.message = message
return
with warnings.catch_warnings():
warnings.simplefilter("ignore")
lockfileobj = LogChecker.lock(lockfile)
if lockfileobj:
locked = True
break
cur_time = time.time()
time.sleep(LogChecker._RETRY_PERIOD)
if not locked:
self.state = LogChecker.STATE_UNKNOWN
self.message = "UNKNOWN: Lock timeout. Another process is running."
return
if LogChecker.is_multiple_logfiles(logfile_pattern):
self._check_log_multi(
logfile_pattern, remove_seekfile=remove_seekfile, tag=tag)
else:
# create seekfile
if not seekfile:
seekfile = self._create_seek_filename(
logfile_pattern, logfile_pattern,
trace_inode=self.config['trace_inode'], tag=tag)
self._check_log(logfile_pattern, seekfile)
if self.config['cachetime'] > 0:
self._update_cache(cachefile)
LogChecker.unlock(lockfile, lockfileobj)
return
def check_log(self, logfile, seekfile):
"""Check the log file.
deprecated:: 2.0.1
Use :func:`check` instead.
"""
self.check(logfile, seekfile=seekfile)
return
def _check_log(self, logfile, seekfile):
"""Check the log file.
Args:
logfile (str): The file name of the log file to be scanned.
seekfile (str): The file name of the seek file.
"""
_debug("logfile='{0}', seekfile='{1}'".format(logfile, seekfile))
logfile = LogChecker.to_unicode(logfile)
if not os.path.exists(logfile):
return
filesize = os.path.getsize(logfile)
# define seek positions.
start_position = LogChecker._read_seekfile(seekfile)
end_position = 0
if not self._check_updated(logfile, start_position, filesize):
return
# if log was rotated, set start_position.
if filesize < start_position:
start_position = 0
found = []
critical_found = []
if self.config['multiline']:
end_position = self._check_each_multiple_lines(
logfile, start_position, found, critical_found)
else:
end_position = self._check_each_single_line(
logfile, start_position, found, critical_found)
if found:
self.found.extend(found)
if self.config['output_quiet']:
self.found_messages.append(
"at {0}".format(logfile))
elif self.config['output_header']:
self.found_messages.append(
"{0} at {1}".format(LogChecker._join_header(found), logfile))
else:
self.found_messages.append(
"{0} at {1}".format(LogChecker._join_header_and_message(found) , logfile))
if critical_found:
self.critical_found.extend(critical_found)
if self.config['output_quiet']:
self.critical_found_messages.append(
"at {0}".format(logfile))
elif self.config['output_header']:
self.critical_found_messages.append(
"{0} at {1}".format(LogChecker._join_header(critical_found), logfile))
else:
self.critical_found_messages.append(
"{0} at {1}".format(LogChecker._join_header_and_message(critical_found), logfile))
self._update_seekfile(seekfile, end_position)
return
def check_log_multi(
self, logfile_pattern, state_directory,
remove_seekfile=False, tag=''):
"""Check the multiple log files.
deprecated:: 2.0.1
Use :func:`check` instead.
"""
state_directory = state_directory # not used
self.check(logfile_pattern, remove_seekfile=remove_seekfile, tag=tag)
def _check_log_multi(self, logfile_pattern, remove_seekfile=False, tag=''):
"""Check the multiple log files.
Args:
logfile_pattern (str): The file names of log files to be scanned.
remove_seekfile (bool, optional): If true, remove expired seek files.
tag (str, optional): The tag added in the file names of state files,
to prevent names collisions.
"""
logfile_list = self._get_logfile_list(logfile_pattern)
for logfile in logfile_list:
if not os.path.isfile(logfile):
continue
seekfile = self._create_seek_filename(
logfile_pattern, logfile,
trace_inode=self.config['trace_inode'], tag=tag)
self._check_log(logfile, seekfile)
if remove_seekfile:
if self.config['trace_inode']:
self._remove_old_seekfile_with_inode(logfile_pattern, tag)
else:
self._remove_old_seekfile(logfile_pattern, tag)
return
def clear_state(self):
"""Clear the state of the result."""
self.state = None
self.message = None
self.messages = []
self.found = []
self.found_messages = []
self.critical_found = []
self.critical_found_messages = []
return
def get_state(self):
"""Get the state of the result.
When get_state() or get_message() is executed,
the state is retained until clear_state() is executed.
"""
if self.state is None:
self._update_state()
return self.state
def get_message(self):
"""Get the message of the result.
When get_state() or get_message() is executed,
the message is retained until clear_state() is executed.
"""
if self.state is None:
self._update_state()
if self.message is None:
self._update_message()
return self.message
def _get_cache(self, cachefile):
"""Get the cache."""
if self.config['dry_run']:
return LogChecker.STATE_NO_CACHE, None
if not os.path.exists(cachefile):
return LogChecker.STATE_NO_CACHE, None
if os.stat(cachefile).st_mtime < time.time() - self.config['cachetime']:
_debug("Cache is expired: mtime < curtime - cachetime")
return LogChecker.STATE_NO_CACHE, None
with io.open(cachefile, mode='r', encoding='utf-8') as fileobj:
line = fileobj.readline()
fileobj.close()
state, message = line.split("\t", 1)
_debug("cache: state={0}, message='{1}'".format(state, message))
return int(state), message
def _update_cache(self, cachefile):
"""Update the cache."""
if self.config['dry_run']:
return True
tmp_cachefile = cachefile + "." + str(os.getpid())
with io.open(tmp_cachefile, mode='w', encoding='utf-8') as cachefileobj:
cachefileobj.write(LogChecker.to_unicode(str(self.get_state())))
cachefileobj.write("\t")
cachefileobj.write(self.get_message())
cachefileobj.flush()
cachefileobj.close()
os.rename(tmp_cachefile, cachefile)
return True
def _remove_cache(self, cachefile):
"""Remove the cache file."""
if self.config['dry_run']:
return True
if os.path.isfile(cachefile):
os.unlink(cachefile)
@staticmethod
def get_pattern_list(pattern_string, pattern_filename):
"""Get the pattern list.
Args:
pattern_string (str): The pattern to scan for.
pattern_filename (str): The file name of file containing patterns.
Returns:
The list of patterns.
"""
pattern_list = []
if pattern_string:
# Revert the surrogate-escaped string in the ASCII locale.
try:
pattern_string = re.sub(
r'[\udc80-\udcff]+',
lambda m: b''.join(
[bytes.fromhex('%x' % (ord(char) - ord('\udc00'))) for char in m.group(0)]
).decode('utf-8'),
pattern_string)
pattern_list.append(LogChecker.to_unicode(pattern_string))
except UnicodeDecodeError:
LogChecker.print_message("The character encoding of the locale or pattern string is incorrect. Use UTF-8.")
sys.exit(LogChecker.STATE_UNKNOWN)
if pattern_filename:
if os.path.isfile(pattern_filename):
lines = []
try:
with io.open(pattern_filename, mode='r', encoding='utf-8') as fileobj:
for line in fileobj:
pattern = line.rstrip()
if pattern:
lines.append(pattern)
fileobj.close()
except UnicodeDecodeError:
LogChecker.print_message("The character encoding of the pattern file is incorrect: {0}. Save its character encoding as UTF-8.".format(pattern_filename))
sys.exit(LogChecker.STATE_UNKNOWN)
if lines:
pattern_list.extend(lines)
else:
LogChecker.print_message("Unable to find the pattern file: {0}".format(pattern_filename))
sys.exit(LogChecker.STATE_UNKNOWN)
return pattern_list
@staticmethod
def _expand_logformat_by_strftime(logformat):
"""Expand log format by strftime variables.
Args:
logformat (str): The string of log format.
Returns:
The string expanded by strftime().
"""
for item in LogChecker._LOGFORMAT_EXPANSION_LIST:
key = list(item)[0]
logformat = logformat.replace(key, item[key])
return logformat
def _update_seekfile(self, seekfile, position):
"""Update the seek file for the log file."""
if self.config['dry_run']:
return True
tmp_seekfile = seekfile + "." + str(os.getpid())
with io.open(tmp_seekfile, mode='w', encoding='utf-8') as fileobj:
fileobj.write(LogChecker.to_unicode(str(position)))
fileobj.flush()
fileobj.close()
os.rename(tmp_seekfile, seekfile)
return True
@staticmethod
def _read_seekfile(seekfile):
"""Read the offset of the log file from its seek file."""
if not os.path.exists(seekfile):
return 0
with io.open(seekfile, mode='r', encoding='utf-8') as fileobj:
offset = int(fileobj.readline())
fileobj.close()
return offset
@staticmethod
def _join_header(found):
"""Join header."""
headers = []
for item in found:
if item['header']:
headers.append(item['header'])
else:
headers.append(item['message'])
return ','.join(headers)
@staticmethod
def _join_header_and_message(found):
"""Join header and message."""
log_messages = []
for item in found:
log_messages.append(''.join([item['header'], item['message']]))
return ','.join(log_messages)
@staticmethod
def lock(lockfile):
"""Lock.
Args:
lockfile (str): The file name of the lock file.
Returns:
The instance of the object of the lock file.
If lock fails, return None.
"""
lockfileobj = io.open(lockfile, mode='w')
try:
fcntl.flock(lockfileobj, fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError:
return None
lockfileobj.flush()
return lockfileobj
@staticmethod
def unlock(lockfile, lockfileobj):
"""Unlock.
Args:
lockfile (str): The file name of the lock file.
lockfileobj (file): The instance of the object of the lock file.
Returns:
True if unlock successes.
"""
if lockfileobj is None:
return False
lockfileobj.close()
if os.path.isfile(lockfile):
os.unlink(lockfile)
return True
@staticmethod
def get_digest(string):
"""Get digest string.
Args:
string (str): The string to be digested.
Returns:
The string of digest.
"""
hashobj = hashlib.sha1()
hashobj.update(LogChecker.to_bytes(string))
digest = LogChecker.to_unicode(
base64.urlsafe_b64encode(hashobj.digest()))
return digest
@staticmethod
def is_multiple_logfiles(logfile_pattern):
"""Whether the pattern of the log file names is multiple files.
Args:
logfile_pattern (str): The pattern of the file names of log files.
Returns:
True if the string of the log file pattern is multiple log files.
"""
matchobj = re.search('[*? ]', logfile_pattern)
if matchobj:
return True
return False
@staticmethod
def to_unicode(string):
"""Convert str to unicode.
Args:
string (str or bytes): The string or bytes to convert to unicode string.
Returns:
The unicode string to be converted.
"""
if sys.version_info >= (3,):
# Python3
# type: str or bytes
if isinstance(string, bytes):
# type: bytes
# convert bytes to str.
return string.decode('utf-8')
# type: str
else:
# Python2
# type: unicode or str
if isinstance(string, str):
# type: str
# convert str to unicode.
return string.decode('utf-8')
# type: unicode
return string
@staticmethod
def to_bytes(string):
"""Convert str to bytes.
Args:
string (str or unicode): The string to convert to bytes.
Returns:
The bytes to be converted.
"""
if sys.version_info >= (3,):
# Python3
# type: str or bytes
if isinstance(string, str):
# type: str
return string.encode('utf-8')
# type: bytes
else:
# Python2
# type: unicode or str
if not isinstance(string, str):