1313 sudo python loganalyzer.py --out_dir /home/hrachya/projects/loganalyzer/log.analyzer.results --action analyze --run_id myTest114 --logs file3.log -m /home/hrachya/projects/loganalyzer/match.file.1.log,/home/hrachya/projects/loganalyzer/match.file.2.log -i ignore.file.1.log,ignore.file.2.log -v
1414'''
1515
16- # ---------------------------------------------------------------------
16+ #---------------------------------------------------------------------
1717# Global imports
18- # ---------------------------------------------------------------------
18+ #---------------------------------------------------------------------
1919from __future__ import print_function
2020import sys
2121import getopt
3030import subprocess
3131from datetime import datetime
3232
33- # ---------------------------------------------------------------------
33+ #---------------------------------------------------------------------
3434# Global variables
35- # ---------------------------------------------------------------------
35+ #---------------------------------------------------------------------
3636tokenizer = ','
3737comment_key = '#'
3838system_log_file = '/var/log/syslog'
3939re_rsyslog_pid = re .compile ("PID:\s+(\d+)" )
4040
41- # -- List of ERROR codes to be returned by AnsibleLogAnalyzer
41+ #-- List of ERROR codes to be returned by AnsibleLogAnalyzer
4242err_duplicate_start_marker = - 1
4343err_duplicate_end_marker = - 2
4444err_no_end_marker = - 3
4848err_end_ignore_marker = - 7
4949err_start_ignore_marker = - 8
5050
51-
5251class AnsibleLogAnalyzer :
5352 '''
5453 @summary: Overview of functionality
@@ -85,36 +84,36 @@ class AnsibleLogAnalyzer:
8584 def init_sys_logger (self ):
8685 logger = logging .getLogger ('LogAnalyzer' )
8786 logger .setLevel (logging .DEBUG )
88- handler = logging .handlers .SysLogHandler (address = '/dev/log' )
87+ handler = logging .handlers .SysLogHandler (address = '/dev/log' )
8988 logger .addHandler (handler )
9089 return logger
91- # ---------------------------------------------------------------------
90+ #---------------------------------------------------------------------
9291
93- def __init__ (self , run_id , verbose , start_marker = None ):
92+ def __init__ (self , run_id , verbose , start_marker = None ):
9493 self .run_id = run_id
9594 self .verbose = verbose
9695 self .start_marker = start_marker
97- # ---------------------------------------------------------------------
96+ #---------------------------------------------------------------------
9897
9998 def print_diagnostic_message (self , message ):
10099 if (not self .verbose ):
101100 return
102101
103102 print ('[LogAnalyzer][diagnostic]:%s' % message )
104- # ---------------------------------------------------------------------
103+ #---------------------------------------------------------------------
105104
106105 def create_start_marker (self ):
107106 if (self .start_marker is None ) or (len (self .start_marker ) == 0 ):
108107 return self .start_marker_prefix + "-" + self .run_id
109108 else :
110109 return self .start_marker
111110
112- # ---------------------------------------------------------------------
111+ #---------------------------------------------------------------------
113112
114113 def is_filename_stdin (self , file_name ):
115114 return file_name == "-"
116115
117- # ---------------------------------------------------------------------
116+ #---------------------------------------------------------------------
118117
119118 def require_marker_check (self , file_path ):
120119 '''
@@ -128,19 +127,19 @@ def require_marker_check(self, file_path):
128127 files_to_skip = ["sairedis.rec" , "bgpd.log" ]
129128 return not any ([target in file_path for target in files_to_skip ])
130129
131- # ---------------------------------------------------------------------
130+ #---------------------------------------------------------------------
132131
133132 def create_end_marker (self ):
134133 return self .end_marker_prefix + "-" + self .run_id
135- # ---------------------------------------------------------------------
134+ #---------------------------------------------------------------------
136135
137136 def create_start_ignore_marker (self ):
138137 return self .start_ignore_marker_prefix + "-" + self .run_id
139- # ---------------------------------------------------------------------
138+ #---------------------------------------------------------------------
140139
141140 def create_end_ignore_marker (self ):
142141 return self .end_ignore_marker_prefix + "-" + self .run_id
143- # ---------------------------------------------------------------------
142+ #---------------------------------------------------------------------
144143
145144 def flush_rsyslogd (self ):
146145 '''
@@ -209,11 +208,11 @@ def wait_for_marker(self, marker, timeout=120, polling_interval=10):
209208 prev_syslog_file = "/var/log/syslog.1"
210209 last_dt = os .path .getctime (syslog_file )
211210 while wait_time <= timeout :
212- with open (syslog_file , 'r' , errors = 'ignore' ) as fp :
211+ with open (syslog_file , 'r' ) as fp :
213212 dt = os .path .getctime (syslog_file )
214213 if last_dt != dt :
215214 try :
216- with open (prev_syslog_file , 'r' , errors = 'ignore' ) as pfp :
215+ with open (prev_syslog_file , 'r' ) as pfp :
217216 pfp .seek (last_check_pos )
218217 for l in fp :
219218 if marker in l :
@@ -252,7 +251,7 @@ def place_marker(self, log_file_list, marker, wait_for_marker=False):
252251 raise RuntimeError ("cannot find marker {} in /var/log/syslog" .format (marker ))
253252
254253 return
255- # ---------------------------------------------------------------------
254+ #---------------------------------------------------------------------
256255
257256 def error_to_regx (self , error_string ):
258257 '''
@@ -272,11 +271,11 @@ def error_to_regx(self, error_string):
272271 original_string = error_string
273272 #-- Escapes out of all the meta characters --#
274273 error_string = re .escape (error_string )
275- # -- Replaces a white space with the white space regular expression
274+ #-- Replaces a white space with the white space regular expression
276275 error_string = re .sub (r"(\\\s+)+" , "\\ \\ s+" , error_string )
277- # -- Replaces a digit number with the digit regular expression
276+ #-- Replaces a digit number with the digit regular expression
278277 error_string = re .sub (r"\b\d+\b" , "\\ \\ d+" , error_string )
279- # -- Replaces a hex number with the hex regular expression
278+ #-- Replaces a hex number with the hex regular expression
280279 error_string = re .sub (r"0x[0-9a-fA-F]+" , "0x[0-9a-fA-F]+" , error_string )
281280 self .print_diagnostic_message ('Built error string: %s' % error_string )
282281
@@ -285,7 +284,7 @@ def error_to_regx(self, error_string):
285284 error_string = '|' .join (map (self .error_to_regx , error_string ))
286285
287286 return error_string
288- # ---------------------------------------------------------------------
287+ #---------------------------------------------------------------------
289288
290289 def create_msg_regex (self , file_lsit ):
291290 '''
@@ -311,17 +310,17 @@ def create_msg_regex(self, file_lsit):
311310 for index , row in enumerate (csvreader ):
312311 row = [item for item in row if item != "" ]
313312 self .print_diagnostic_message ('[diagnostic]:processing row:%d' % index )
314- self .print_diagnostic_message ('row:%s' % row )
313+ self .print_diagnostic_message ('row:%s' % row )
315314 try :
316- # -- Ignore Empty Lines
315+ #-- Ignore Empty Lines
317316 if not row :
318317 continue
319- # -- Ignore commented Lines
318+ #-- Ignore commented Lines
320319 if row [0 ].startswith (comment_key ):
321320 self .print_diagnostic_message ('[diagnostic]:skipping row[0]:%s' % row [0 ])
322321 continue
323322
324- # -- ('s' | 'r') = (Raw String | Regular Expression)
323+ #-- ('s' | 'r') = (Raw String | Regular Expression)
325324 is_regex = row [0 ]
326325 if ('s' == row [0 ]):
327326 is_regex = False
@@ -330,7 +329,7 @@ def create_msg_regex(self, file_lsit):
330329 else :
331330 raise Exception ('file:%s, malformed line:%d. '
332331 'must be \' s\' (string) or \' r\' (regex)'
333- % (filename , index ))
332+ % (filename ,index ))
334333
335334 if (is_regex ):
336335 messages_regex .extend (row [1 :])
@@ -347,7 +346,7 @@ def create_msg_regex(self, file_lsit):
347346 else :
348347 regex = None
349348 return regex , messages_regex
350- # ---------------------------------------------------------------------
349+ #---------------------------------------------------------------------
351350
352351 def line_matches (self , str , match_messages_regex , ignore_messages_regex ):
353352 '''
@@ -379,7 +378,7 @@ def line_matches(self, str, match_messages_regex, ignore_messages_regex):
379378 ret_code = True
380379
381380 return ret_code
382- # ---------------------------------------------------------------------
381+ #---------------------------------------------------------------------
383382
384383 def line_is_expected (self , str , expect_messages_regex ):
385384 '''
@@ -414,10 +413,11 @@ def analyze_file(self, log_file_path, match_messages_regex, ignore_messages_rege
414413 @return: List of strings match search criteria.
415414 '''
416415
417- self .print_diagnostic_message ('analyzing file: %s' % log_file_path )
418416
419- # -- indicates whether log analyzer currently is in the log range between start
420- # -- and end marker. see analyze_file method.
417+ self .print_diagnostic_message ('analyzing file: %s' % log_file_path )
418+
419+ #-- indicates whether log analyzer currently is in the log range between start
420+ #-- and end marker. see analyze_file method.
421421 check_marker = self .require_marker_check (log_file_path )
422422 in_analysis_range = not check_marker
423423 stdin_as_input = self .is_filename_stdin (log_file_path )
@@ -503,7 +503,7 @@ def analyze_file(self, log_file_path, match_messages_regex, ignore_messages_rege
503503 sys .exit (err_no_end_marker )
504504
505505 return matching_lines , expected_lines
506- # ---------------------------------------------------------------------
506+ #---------------------------------------------------------------------
507507
508508 def analyze_file_list (self , log_file_list , match_messages_regex , ignore_messages_regex , expect_messages_regex ):
509509 '''
@@ -528,16 +528,14 @@ def analyze_file_list(self, log_file_list, match_messages_regex, ignore_messages
528528 for log_file in log_file_list :
529529 if not len (log_file ):
530530 continue
531- match_strings , expect_strings = self .analyze_file (
532- log_file , match_messages_regex , ignore_messages_regex , expect_messages_regex )
531+ match_strings , expect_strings = self .analyze_file (log_file , match_messages_regex , ignore_messages_regex , expect_messages_regex )
533532
534533 match_strings .reverse ()
535534 expect_strings .reverse ()
536- res [log_file ] = [match_strings , expect_strings ]
535+ res [log_file ] = [ match_strings , expect_strings ]
537536
538537 return res
539- # ---------------------------------------------------------------------
540-
538+ #---------------------------------------------------------------------
541539
542540def usage ():
543541 print ('loganalyzer input parameters:' )
@@ -567,8 +565,7 @@ def usage():
567565 print (' in one of specified log files during the analysis. Must be present' )
568566 print (' when action == analyze.' )
569567
570- # ---------------------------------------------------------------------
571-
568+ #---------------------------------------------------------------------
572569
573570def check_action (action , log_files_in , out_dir , match_files_in , ignore_files_in , expect_files_in ):
574571 '''
@@ -591,13 +588,13 @@ def check_action(action, log_files_in, out_dir, match_files_in, ignore_files_in,
591588 print ('ERROR: missing required match_files_in for analyze action' )
592589 ret_code = False
593590
591+
594592 else :
595593 ret_code = False
596594 print ('ERROR: invalid action:%s specified' % action )
597595
598596 return ret_code
599- # ---------------------------------------------------------------------
600-
597+ #---------------------------------------------------------------------
601598
602599def check_run_id (run_id ):
603600 '''
@@ -615,8 +612,7 @@ def check_run_id(run_id):
615612 ret_code = False
616613
617614 return ret_code
618- # ---------------------------------------------------------------------
619-
615+ #---------------------------------------------------------------------
620616
621617def write_result_file (run_id , out_dir , analysis_result_per_file , messages_regex_e , unused_regex_messages ):
622618 '''
@@ -670,8 +666,7 @@ def write_result_file(run_id, out_dir, analysis_result_per_file, messages_regex_
670666
671667 out_file .write ("\n -------------------------------------------------\n \n " )
672668 out_file .flush ()
673- # ---------------------------------------------------------------------
674-
669+ #---------------------------------------------------------------------
675670
676671def write_summary_file (run_id , out_dir , analysis_result_per_file , unused_regex_messages ):
677672 '''
@@ -708,8 +703,7 @@ def write_summary_file(run_id, out_dir, analysis_result_per_file, unused_regex_m
708703 out_file .write ("-----------------------------------\n " )
709704 out_file .flush ()
710705 out_file .close ()
711- # ---------------------------------------------------------------------
712-
706+ #---------------------------------------------------------------------
713707
714708def main (argv ):
715709
@@ -724,8 +718,7 @@ def main(argv):
724718 verbose = False
725719
726720 try :
727- opts , args = getopt .getopt (argv , "a:r:s:l:o:m:i:e:vh" , [
728- "action=" , "run_id=" , "start_marker=" , "logs=" , "out_dir=" , "match_files_in=" , "ignore_files_in=" , "expect_files_in=" , "verbose" , "help" ])
721+ opts , args = getopt .getopt (argv , "a:r:s:l:o:m:i:e:vh" , ["action=" , "run_id=" , "start_marker=" , "logs=" , "out_dir=" , "match_files_in=" , "ignore_files_in=" , "expect_files_in=" , "verbose" , "help" ])
729722
730723 except getopt .GetoptError :
731724 print ("Invalid option specified" )
@@ -806,11 +799,11 @@ def main(argv):
806799 analyzer .place_marker (log_file_list , analyzer .create_end_ignore_marker (), wait_for_marker = True )
807800 return 0
808801
802+
809803 else :
810804 print ('Unknown action:%s specified' % action )
811805 return len (result )
812- # ---------------------------------------------------------------------
813-
806+ #---------------------------------------------------------------------
814807
815808if __name__ == "__main__" :
816809 main (sys .argv [1 :])
0 commit comments