Salome HOME
src.xmlManager escapeSequence
[tools/sat.git] / commands / log.py
1 #!/usr/bin/env python
2 #-*- coding:utf-8 -*-
3 #  Copyright (C) 2010-2012  CEA/DEN
4 #
5 #  This library is free software; you can redistribute it and/or
6 #  modify it under the terms of the GNU Lesser General Public
7 #  License as published by the Free Software Foundation; either
8 #  version 2.1 of the License.
9 #
10 #  This library is distributed in the hope that it will be useful,
11 #  but WITHOUT ANY WARRANTY; without even the implied warranty of
12 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 #  Lesser General Public License for more details.
14 #
15 #  You should have received a copy of the GNU Lesser General Public
16 #  License along with this library; if not, write to the Free Software
17 #  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
18
19 import os
20 import shutil
21 import re
22 import glob
23 import datetime
24 import stat
25
26 # Compatibility python 2/3 for input function
27 # input stays input for python 3 and input = raw_input for python 2
28 try: 
29     input = raw_input
30 except NameError: 
31     pass
32
33 import src
34
35 # Define all possible option for log command :  sat log <options>
36 parser = src.options.Options()
37 parser.add_option('t', 'terminal', 'boolean', 'terminal', "Optional: "
38                   "Terminal log.")
39 parser.add_option('l', 'last', 'boolean', 'last', "Show the log of the last "
40                   "Optional: launched command.")
41 parser.add_option('', 'last_terminal', 'boolean', 'last_terminal', "Show the "
42                   "log of the last compilations"
43                   "Optional: launched command.")
44 parser.add_option('f', 'full', 'boolean', 'full', "Optional: Show the logs of "
45                   "ALL the launched commands.")
46 parser.add_option('c', 'clean', 'int', 'clean', "Optional: Erase the n most "
47                   "ancient log files.")
48 parser.add_option('n', 'no_browser', 'boolean', 'no_browser', "Optional: Do not"
49                   " launch the browser at the end of the command. Only update "
50                   "the hat file.")
51
52 def get_last_log_file(logDir, notShownCommands):
53     '''Used in case of last option. Get the last log command file path.
54     
55     :param logDir str: The directory where to search the log files
56     :param notShownCommands list: the list of commands to ignore
57     :return: the path to the last log file
58     :rtype: str
59     '''
60     last = (_, 0)
61     for fileName in os.listdir(logDir):
62         # YYYYMMDD_HHMMSS_namecmd.xml
63         sExpr = src.logger.log_macro_command_file_expression
64         oExpr = re.compile(sExpr)
65         if oExpr.search(fileName):
66             # get date and hour and format it
67             date_hour_cmd = fileName.split('_')
68             datehour = date_hour_cmd[0] + date_hour_cmd[1]
69             cmd = date_hour_cmd[2]
70             if cmd in notShownCommands:
71                 continue
72             if int(datehour) > last[1]:
73                 last = (fileName, int(datehour))
74     return os.path.join(logDir, last[0])
75
76 def remove_log_file(filePath, logger):
77     '''if it exists, print a warning and remove the input file
78     
79     :param filePath: the path of the file to delete
80     :param logger Logger: the logger instance to use for the print 
81     '''
82     if os.path.exists(filePath):
83         logger.write(src.printcolors.printcWarning("Removing ")
84                      + filePath + "\n", 5)
85         os.remove(filePath)
86
87 def print_log_command_in_terminal(filePath, logger):
88     '''Print the contain of filePath. It contains a command log in xml format.
89     
90     :param filePath: The command xml file from which extract the commands 
91                      context and traces
92     :param logger Logger: the logging instance to use in order to print.  
93     '''
94     logger.write(_("Reading ") + src.printcolors.printcHeader(filePath) + "\n", 5)
95     # Instantiate the ReadXmlFile class that reads xml files
96     xmlRead = src.xmlManager.ReadXmlFile(filePath)
97     # Get the attributes containing the context (user, OS, time, etc..)
98     dAttrText = xmlRead.get_attrib('Site')
99     # format dAttrText and print the context
100     lAttrText = []
101     for attrib in dAttrText:
102         lAttrText.append((attrib, dAttrText[attrib]))
103     logger.write("\n", 1)
104     src.print_info(logger, lAttrText)
105     # Get the traces
106     command_traces = xmlRead.get_node_text('Log')
107     # Print it if there is any
108     if command_traces:
109         logger.write(src.printcolors.printcHeader(
110                                     _("Here are the command traces :\n")), 1)
111         logger.write(command_traces, 1)
112         logger.write("\n", 1)
113
114 def show_last_logs(logger, config, log_dirs):
115     """Show last compilation logs"""
116     log_dir = os.path.join(config.APPLICATION.workdir, 'LOGS')
117     # list the logs
118     nb = len(log_dirs)
119     nb_cols = 4
120     col_size = (nb / nb_cols) + 1
121     for index in range(0, col_size):
122         for i in range(0, nb_cols):
123             k = index + i * col_size
124             if k < nb:
125                 l = log_dirs[k]
126                 str_indice = src.printcolors.printcLabel("%2d" % (k+1))
127                 log_name = l
128                 logger.write("%s: %-30s" % (str_indice, log_name), 1, False)
129         logger.write("\n", 1, False)
130
131     # loop till exit
132     x = -1
133     while (x < 0):
134         x = ask_value(nb)
135         if x > 0:
136             product_log_dir = os.path.join(log_dir, log_dirs[x-1])
137             show_product_last_logs(logger, config, product_log_dir)
138
139 def show_product_last_logs(logger, config, product_log_dir):
140     """Show last compilation logs of a product"""
141     # sort the files chronologically
142     l_time_file = []
143     for file_n in os.listdir(product_log_dir):
144         my_stat = os.stat(os.path.join(product_log_dir, file_n))
145         l_time_file.append(
146               (datetime.datetime.fromtimestamp(my_stat[stat.ST_MTIME]), file_n))
147     
148     # display the available logs
149     for i, (__, file_name) in enumerate(sorted(l_time_file)):
150         str_indice = src.printcolors.printcLabel("%2d" % (i+1))
151         opt = []
152         my_stat = os.stat(os.path.join(product_log_dir, file_name))
153         opt.append(str(datetime.datetime.fromtimestamp(my_stat[stat.ST_MTIME])))
154         
155         opt.append("(%8.2f)" % (my_stat[stat.ST_SIZE] / 1024.0))
156         logger.write(" %-35s" % " ".join(opt), 1, False)
157         logger.write("%s: %-30s\n" % (str_indice, file_name), 1, False)
158         
159     # loop till exit
160     x = -1
161     while (x < 0):
162         x = ask_value(len(l_time_file))
163         if x > 0:
164             (__, file_name) =  sorted(l_time_file)[x-1]
165             log_file_path = os.path.join(product_log_dir, file_name)
166             src.system.show_in_editor(config.USER.editor, log_file_path, logger)
167         
168 def ask_value(nb):
169     '''Ask for an int n. 0<n<nb
170     
171     :param nb int: The maximum value of the value to be returned by the user.
172     :return: the value entered by the user. Return -1 if it is not as expected
173     :rtype: int
174     '''
175     try:
176         # ask for a value
177         rep = input(_("Which one (enter or 0 to quit)? "))
178         # Verify it is on the right range
179         if len(rep) == 0:
180             x = 0
181         else:
182             x = int(rep)
183             if x > nb:
184                 x = -1
185     except:
186         x = -1
187     
188     return x
189
190 def description():
191     '''method that is called when salomeTools is called with --help option.
192     
193     :return: The text to display for the log command description.
194     :rtype: str
195     '''
196     return _("""\
197 The log command gives access to the logs produced by the salomeTools commands.
198
199 example:
200 >> sat log
201 """)
202
203 def run(args, runner, logger):
204     '''method that is called when salomeTools is called with log parameter.
205     '''
206     # Parse the options
207     (options, args) = parser.parse_args(args)
208
209     # get the log directory. 
210     logDir = src.get_log_path(runner.cfg)
211     
212     # Print a header
213     nb_files_log_dir = len(glob.glob(os.path.join(logDir, "*")))
214     info = [("log directory", logDir), 
215             ("number of log files", nb_files_log_dir)]
216     src.print_info(logger, info)
217     
218     # If the clean options is invoked, 
219     # do nothing but deleting the concerned files.
220     if options.clean:
221         nbClean = options.clean
222         # get the list of files to remove
223         lLogs = src.logger.list_log_file(logDir, 
224                                    src.logger.log_all_command_file_expression)
225         nbLogFiles = len(lLogs)
226         # Delete all if the invoked number is bigger than the number of log files
227         if nbClean > nbLogFiles:
228             nbClean = nbLogFiles
229         # Get the list to delete and do the removing
230         lLogsToDelete = sorted(lLogs)[:nbClean]
231         for filePath, __, __, __, __, __, __ in lLogsToDelete:
232             # remove the xml log file
233             remove_log_file(filePath, logger)
234             # remove also the corresponding txt file in OUT directory
235             txtFilePath = os.path.join(os.path.dirname(filePath), 
236                             'OUT', 
237                             os.path.basename(filePath)[:-len('.xml')] + '.txt')
238             remove_log_file(txtFilePath, logger)
239             # remove also the corresponding pyconf (do not exist 2016-06) 
240             # file in OUT directory
241             pyconfFilePath = os.path.join(os.path.dirname(filePath), 
242                             'OUT', 
243                             os.path.basename(filePath)[:-len('.xml')] + '.pyconf')
244             remove_log_file(pyconfFilePath, logger)
245
246         
247         logger.write(src.printcolors.printcSuccess("OK\n"))
248         logger.write("%i logs deleted.\n" % nbClean)
249         return 0 
250
251     # determine the commands to show in the hat log
252     notShownCommands = list(runner.cfg.INTERNAL.log.not_shown_commands)
253     if options.full:
254         notShownCommands = []
255
256     # Find the stylesheets Directory and files
257     xslDir = os.path.join(runner.cfg.VARS.srcDir, 'xsl')
258     xslCommand = os.path.join(xslDir, "command.xsl")
259     xslHat = os.path.join(xslDir, "hat.xsl")
260     xsltest = os.path.join(xslDir, "test.xsl")
261     imgLogo = os.path.join(xslDir, "LOGO-SAT.png")
262     
263     # copy the stylesheets in the log directory
264     # OP We use copy instead of copy2 to update the creation date
265     #    So we can clean the LOGS directories easily
266     shutil.copy(xslCommand, logDir)
267     shutil.copy(xslHat, logDir)
268     src.ensure_path_exists(os.path.join(logDir, "TEST"))
269     shutil.copy(xsltest, os.path.join(logDir, "TEST"))
270     shutil.copy(imgLogo, logDir)
271
272     # If the last option is invoked, just, show the last log file
273     if options.last_terminal:
274         src.check_config_has_application(runner.cfg)
275         log_dirs = os.listdir(os.path.join(runner.cfg.APPLICATION.workdir,
276                                            'LOGS'))
277         show_last_logs(logger, runner.cfg, log_dirs)
278         return 0
279
280     # If the last option is invoked, just, show the last log file
281     if options.last:
282         lastLogFilePath = get_last_log_file(logDir,
283                                             notShownCommands + ["config"])        
284         if options.terminal:
285             # Show the log corresponding to the selected command call
286             print_log_command_in_terminal(lastLogFilePath, logger)
287         else:
288             # open the log xml file in the user editor
289             src.system.show_in_editor(runner.cfg.USER.browser, 
290                                       lastLogFilePath, logger)
291         return 0
292
293     # If the user asks for a terminal display
294     if options.terminal:
295         # Parse the log directory in order to find 
296         # all the files corresponding to the commands
297         lLogs = src.logger.list_log_file(logDir, 
298                                    src.logger.log_macro_command_file_expression)
299         lLogsFiltered = []
300         for filePath, __, date, __, hour, cmd, __ in lLogs:
301             showLog, cmdAppli, __ = src.logger.show_command_log(filePath, cmd, 
302                                 runner.cfg.VARS.application, notShownCommands)
303             if showLog:
304                 lLogsFiltered.append((filePath, date, hour, cmd, cmdAppli))
305             
306         lLogsFiltered = sorted(lLogsFiltered)
307         nb_logs = len(lLogsFiltered)
308         index = 0
309         # loop on all files and print it with date, time and command name 
310         for __, date, hour, cmd, cmdAppli in lLogsFiltered:          
311             num = src.printcolors.printcLabel("%2d" % (nb_logs - index))
312             logger.write("%s: %13s %s %s %s\n" % 
313                          (num, cmd, date, hour, cmdAppli), 1, False)
314             index += 1
315         
316         # ask the user what for what command he wants to be displayed
317         x = -1
318         while (x < 0):
319             x = ask_value(nb_logs)
320             if x > 0:
321                 index = len(lLogsFiltered) - int(x)
322                 # Show the log corresponding to the selected command call
323                 print_log_command_in_terminal(lLogsFiltered[index][0], logger)                
324                 x = 0
325         
326         return 0
327                     
328     # Create or update the hat xml that gives access to all the commands log files
329     logger.write(_("Generating the hat log file (can be long) ... "), 3)
330     xmlHatFilePath = os.path.join(logDir, 'hat.xml')
331     src.logger.update_hat_xml(logDir, 
332                               application = runner.cfg.VARS.application, 
333                               notShownCommands = notShownCommands)
334     logger.write(src.printcolors.printc("OK"), 3)
335     logger.write("\n", 3)
336     
337     # open the hat xml in the user editor
338     if not options.no_browser:
339         logger.write(_("\nOpening the log file\n"), 3)
340         src.system.show_in_editor(runner.cfg.USER.browser, xmlHatFilePath, logger)
341     return 0