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