]> SALOME platform Git repositories - tools/sat.git/blob - commands/log.py
Salome HOME
max lenght of lines is now 80
[tools/sat.git] / commands / log.py
1 #!/usr/bin/env python
2 #-*- coding:utf-8 -*-
3
4 import os
5 import shutil
6 import re
7
8 # Compatibility python 2/3 for input function
9 # input stays input for python 3 and input = raw_input for python 2
10 try: 
11     input = raw_input
12 except NameError: 
13     pass
14
15 import src
16
17 # Define all possible option for log command :  sat log <options>
18 parser = src.options.Options()
19 parser.add_option('t', 'terminal', 'boolean', 'terminal', "Terminal log.")
20 parser.add_option('l', 'last', 'boolean', 'last', "Show the log of the last "
21                   "launched command.")
22 parser.add_option('f', 'full', 'boolean', 'full', "Show the logs of ALL "
23                   "launched commands.")
24 parser.add_option('c', 'clean', 'int', 'clean', "Erase the n most ancient "
25                   "log files.")
26
27 def get_last_log_file(logDir, notShownCommands):
28     '''Used in case of last option. Get the last log command file path.
29     
30     :param logDir str: The directory where to search the log files
31     :param notShownCommands list: the list of commands to ignore
32     :return: the path to the last log file
33     :rtype: str
34     '''
35     last = (_, 0)
36     for fileName in os.listdir(logDir):
37         # YYYYMMDD_HHMMSS_namecmd.xml
38         sExpr = src.logger.logCommandFileExpression
39         oExpr = re.compile(sExpr)
40         if oExpr.search(fileName):
41             # get date and hour and format it
42             date_hour_cmd = fileName.split('_')
43             datehour = date_hour_cmd[0] + date_hour_cmd[1]
44             cmd = date_hour_cmd[2][:-len('.xml')]
45             if cmd in notShownCommands:
46                 continue
47             if int(datehour) > last[1]:
48                 last = (fileName, int(datehour))
49     return os.path.join(logDir, last[0])
50
51 def print_log_command_in_terminal(filePath, logger):
52     '''Print the contain of filePath. It contains a command log in xml format.
53     
54     :param filePath: The command xml file from which extract the commands 
55                      context and traces
56     :param logger Logger: the logging instance to use in order to print.  
57     '''
58     logger.write(_("Reading ") + src.printcolors.printcHeader(filePath) + "\n", 5)
59     # Instantiate the readXmlFile class that reads xml files
60     xmlRead = src.xmlManager.readXmlFile(filePath)
61     # Get the attributes containing the context (user, OS, time, etc..)
62     dAttrText = xmlRead.get_attrib('Site')
63     # format dAttrText and print the context
64     lAttrText = []
65     for attrib in dAttrText:
66         lAttrText.append((attrib, dAttrText[attrib]))
67     logger.write("\n", 1)
68     src.print_info(logger, lAttrText)
69     # Get the traces
70     command_traces = xmlRead.get_node_text('Log')
71     # Print it if there is any
72     if command_traces:
73         logger.write(src.printcolors.printcHeader(
74                                     _("Here are the command traces :\n")), 1)
75         logger.write(command_traces, 1)
76         logger.write("\n", 1)
77
78 def ask_value(nb):
79     '''Ask for an int n. 0<n<nb
80     
81     :param nb int: The maximum value of the value to be returned by the user.
82     :return: the value entered by the user. Return -1 if it is not as expected
83     :rtype: int
84     '''
85     try:
86         # ask for a value
87         rep = input(_("Which one (enter or 0 to quit)? "))
88         # Verify it is on the right range
89         if len(rep) == 0:
90             x = 0
91         else:
92             x = int(rep)
93             if x > nb:
94                 x = -1
95     except:
96         x = -1
97     
98     return x
99
100 def description():
101     '''method that is called when salomeTools is called with --help option.
102     
103     :return: The text to display for the log command description.
104     :rtype: str
105     '''
106     return _("Gives access to the logs produced by the salomeTools commands.")    
107
108 def run(args, runner, logger):
109     '''method that is called when salomeTools is called with log parameter.
110     '''
111     # Parse the options
112     (options, args) = parser.parse_args(args)
113
114     # get the log directory. 
115     # If there is an application, it is in cfg.APPLICATION.out_dir, 
116     # else in user directory
117     logDir = runner.cfg.SITE.log.logDir
118
119     # If the clean options is invoked, 
120     # do nothing but deleting the concerned files.
121     if options.clean:
122         nbClean = options.clean
123         # get the list of files to remove
124         lLogs = src.logger.list_log_file(logDir, 
125                                          src.logger.logCommandFileExpression)
126         nbLogFiles = len(lLogs)
127         # Delete all if the invoked number is bigger than the number of log files
128         if nbClean > nbLogFiles:
129             nbClean = nbLogFiles
130         # Get the list to delete and do the removing
131         lLogsToDelete = sorted(lLogs)[:nbClean]
132         for filePath, _, _, _, _, _ in lLogsToDelete:
133             logger.write(src.printcolors.printcWarning("Removing ")
134                           + filePath + "\n", 5)
135             os.remove(filePath)
136         
137         logger.write(src.printcolors.printcSuccess("OK\n"))
138         logger.write("%i files deleted.\n" % nbClean)
139         return 0 
140
141     # determine the commands to show in the hat log
142     notShownCommands = runner.cfg.INTERNAL.log.notShownCommands
143     if options.full:
144         notShownCommands = []
145
146     # If the user asks for a terminal display
147     if options.terminal:
148         # Parse the log directory in order to find 
149         # all the files corresponding to the commands
150         lLogs = src.logger.list_log_file(logDir, 
151                                          src.logger.logCommandFileExpression)
152         lLogsFiltered = []
153         for filePath, _, date, _, hour, cmd in lLogs:
154             showLog, cmdAppli = src.logger.show_command_log(filePath, cmd, 
155                                 runner.cfg.VARS.application, notShownCommands)
156             if showLog:
157                 lLogsFiltered.append((filePath, date, hour, cmd, cmdAppli))
158             
159         lLogsFiltered = sorted(lLogsFiltered)
160         nb_logs = len(lLogsFiltered)
161         index = 0
162         # loop on all files and print it with date, time and command name 
163         for _, date, hour, cmd, cmdAppli in lLogsFiltered:          
164             num = src.printcolors.printcLabel("%2d" % (nb_logs - index))
165             logger.write("%s: %13s %s %s %s\n" % 
166                          (num, cmd, date, hour, cmdAppli), 1, False)
167             index += 1
168         
169         # ask the user what for what command he wants to be displayed
170         x = -1
171         while (x < 0):
172             x = ask_value(nb_logs)
173             if x > 0:
174                 index = len(lLogsFiltered) - int(x)
175                 # Show the log corresponding to the selected command call
176                 print_log_command_in_terminal(lLogsFiltered[index][0], logger)                
177                 x = 0
178         
179         return 0
180                     
181     
182     # Find the stylesheets Directory and files
183     xslDir = os.path.join(runner.cfg.VARS.srcDir, 'xsl')
184     xslCommand = os.path.join(xslDir, "command.xsl")
185     xslHat = os.path.join(xslDir, "hat.xsl")
186     imgLogo = os.path.join(xslDir, "LOGO-SAT.png")
187     
188     # copy the stylesheets in the log directory
189     shutil.copy2(xslCommand, logDir)
190     shutil.copy2(xslHat, logDir)
191     shutil.copy2(imgLogo, logDir)
192
193     # If the last option is invoked, just, show the last log file
194     if options.last:
195         lastLogFilePath = get_last_log_file(logDir, notShownCommands)
196         # open the log xml file in the user editor
197         src.system.show_in_editor(runner.cfg.USER.browser, 
198                                   lastLogFilePath, logger)
199         return 0
200
201     # Create or update the hat xml that gives access to all the commands log files
202     xmlHatFilePath = os.path.join(logDir, 'hat.xml')
203     src.logger.update_hat_xml(runner.cfg.SITE.log.logDir, 
204                               application = runner.cfg.VARS.application, 
205                               notShownCommands = notShownCommands)
206     
207     # open the hat xml in the user editor
208     src.system.show_in_editor(runner.cfg.USER.browser, xmlHatFilePath, logger)
209     return 0