]> SALOME platform Git repositories - tools/sat.git/blob - commands/log.py
Salome HOME
20f975bd561926ffb404569b071e5bf1a036e1f2
[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     files = os.listdir(product_log_dir)
142     # sort the files chronologically
143     l_time_file = []
144     for file_n in os.listdir(product_log_dir):
145         my_stat = os.stat(os.path.join(product_log_dir, file_n))
146         l_time_file.append(
147               (datetime.datetime.fromtimestamp(my_stat[stat.ST_MTIME]), file_n))
148         
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(files))
163         if x > 0:
164             log_file_path = os.path.join(product_log_dir, files[x-1])
165             src.system.show_in_editor(config.USER.editor, log_file_path, logger)
166         
167 def ask_value(nb):
168     '''Ask for an int n. 0<n<nb
169     
170     :param nb int: The maximum value of the value to be returned by the user.
171     :return: the value entered by the user. Return -1 if it is not as expected
172     :rtype: int
173     '''
174     try:
175         # ask for a value
176         rep = input(_("Which one (enter or 0 to quit)? "))
177         # Verify it is on the right range
178         if len(rep) == 0:
179             x = 0
180         else:
181             x = int(rep)
182             if x > nb:
183                 x = -1
184     except:
185         x = -1
186     
187     return x
188
189 def description():
190     '''method that is called when salomeTools is called with --help option.
191     
192     :return: The text to display for the log command description.
193     :rtype: str
194     '''
195     return _("Gives access to the logs produced by the salomeTools commands.\n"
196              "\nexample:\nsat log")    
197
198 def run(args, runner, logger):
199     '''method that is called when salomeTools is called with log parameter.
200     '''
201     # Parse the options
202     (options, args) = parser.parse_args(args)
203
204     # get the log directory. 
205     logDir = runner.cfg.USER.log_dir
206     
207     # Print a header
208     nb_files_log_dir = len(glob.glob(os.path.join(logDir, "*")))
209     info = [("log directory", logDir), 
210             ("number of log files", nb_files_log_dir)]
211     src.print_info(logger, info)
212     
213     # If the clean options is invoked, 
214     # do nothing but deleting the concerned files.
215     if options.clean:
216         nbClean = options.clean
217         # get the list of files to remove
218         lLogs = src.logger.list_log_file(logDir, 
219                                    src.logger.log_all_command_file_expression)
220         nbLogFiles = len(lLogs)
221         # Delete all if the invoked number is bigger than the number of log files
222         if nbClean > nbLogFiles:
223             nbClean = nbLogFiles
224         # Get the list to delete and do the removing
225         lLogsToDelete = sorted(lLogs)[:nbClean]
226         for filePath, __, __, __, __, __, __ in lLogsToDelete:
227             # remove the xml log file
228             remove_log_file(filePath, logger)
229             # remove also the corresponding txt file in OUT directory
230             txtFilePath = os.path.join(os.path.dirname(filePath), 
231                             'OUT', 
232                             os.path.basename(filePath)[:-len('.xml')] + '.txt')
233             remove_log_file(txtFilePath, logger)
234             # remove also the corresponding pyconf (do not exist 2016-06) 
235             # file in OUT directory
236             pyconfFilePath = os.path.join(os.path.dirname(filePath), 
237                             'OUT', 
238                             os.path.basename(filePath)[:-len('.xml')] + '.pyconf')
239             remove_log_file(pyconfFilePath, logger)
240
241         
242         logger.write(src.printcolors.printcSuccess("OK\n"))
243         logger.write("%i logs deleted.\n" % nbClean)
244         return 0 
245
246     # determine the commands to show in the hat log
247     notShownCommands = list(runner.cfg.INTERNAL.log.not_shown_commands)
248     if options.full:
249         notShownCommands = []
250
251     # Find the stylesheets Directory and files
252     xslDir = os.path.join(runner.cfg.VARS.srcDir, 'xsl')
253     xslCommand = os.path.join(xslDir, "command.xsl")
254     xslHat = os.path.join(xslDir, "hat.xsl")
255     xsltest = os.path.join(xslDir, "test.xsl")
256     imgLogo = os.path.join(xslDir, "LOGO-SAT.png")
257     
258     # copy the stylesheets in the log directory
259     shutil.copy2(xslCommand, logDir)
260     shutil.copy2(xslHat, logDir)
261     src.ensure_path_exists(os.path.join(logDir, "TEST"))
262     shutil.copy2(xsltest, os.path.join(logDir, "TEST"))
263     shutil.copy2(imgLogo, logDir)
264
265     # If the last option is invoked, just, show the last log file
266     if options.last_terminal:
267         log_dirs = os.listdir(os.path.join(runner.cfg.APPLICATION.workdir,
268                                            'LOGS'))
269         show_last_logs(logger, runner.cfg, log_dirs)
270         return 0
271
272     # If the last option is invoked, just, show the last log file
273     if options.last:
274         lastLogFilePath = get_last_log_file(logDir,
275                                             notShownCommands + ["config"])        
276         if options.terminal:
277             # Show the log corresponding to the selected command call
278             print_log_command_in_terminal(lastLogFilePath, logger)
279         else:
280             # open the log xml file in the user editor
281             src.system.show_in_editor(runner.cfg.USER.browser, 
282                                       lastLogFilePath, logger)
283         return 0
284
285     # If the user asks for a terminal display
286     if options.terminal:
287         # Parse the log directory in order to find 
288         # all the files corresponding to the commands
289         lLogs = src.logger.list_log_file(logDir, 
290                                    src.logger.log_macro_command_file_expression)
291         lLogsFiltered = []
292         for filePath, __, date, __, hour, cmd, __ in lLogs:
293             showLog, cmdAppli, __ = src.logger.show_command_log(filePath, cmd, 
294                                 runner.cfg.VARS.application, notShownCommands)
295             if showLog:
296                 lLogsFiltered.append((filePath, date, hour, cmd, cmdAppli))
297             
298         lLogsFiltered = sorted(lLogsFiltered)
299         nb_logs = len(lLogsFiltered)
300         index = 0
301         # loop on all files and print it with date, time and command name 
302         for __, date, hour, cmd, cmdAppli in lLogsFiltered:          
303             num = src.printcolors.printcLabel("%2d" % (nb_logs - index))
304             logger.write("%s: %13s %s %s %s\n" % 
305                          (num, cmd, date, hour, cmdAppli), 1, False)
306             index += 1
307         
308         # ask the user what for what command he wants to be displayed
309         x = -1
310         while (x < 0):
311             x = ask_value(nb_logs)
312             if x > 0:
313                 index = len(lLogsFiltered) - int(x)
314                 # Show the log corresponding to the selected command call
315                 print_log_command_in_terminal(lLogsFiltered[index][0], logger)                
316                 x = 0
317         
318         return 0
319                     
320     # Create or update the hat xml that gives access to all the commands log files
321     logger.write(_("Generating the hat log file (can be long) ... "), 3)
322     xmlHatFilePath = os.path.join(logDir, 'hat.xml')
323     src.logger.update_hat_xml(runner.cfg.USER.log_dir, 
324                               application = runner.cfg.VARS.application, 
325                               notShownCommands = notShownCommands)
326     logger.write(src.printcolors.printc("OK"), 3)
327     logger.write("\n", 3)
328     
329     # open the hat xml in the user editor
330     if not options.no_browser:
331         logger.write(_("\nOpening the log file\n"), 3)
332         src.system.show_in_editor(runner.cfg.USER.browser, xmlHatFilePath, logger)
333     return 0