3 # Copyright (C) 2010-2012 CEA/DEN
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.
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.
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
26 # Compatibility python 2/3 for input function
27 # input stays input for python 3 and input = raw_input for python 2
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_terminal', 'boolean', 'last_terminal',
42 "Optional: Show the log (in terminal) of the last launched command.")
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.")
50 def get_last_log_file(logDir, notShownCommands):
51 '''Used in case of last option. Get the last log command file path.
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
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:
70 if int(datehour) > last[1]:
71 last = (fileName, int(datehour))
72 return os.path.join(logDir, last[0])
74 def remove_log_file(filePath, logger):
75 '''if it exists, print a warning and remove the input file
77 :param filePath: the path of the file to delete
78 :param logger Logger: the logger instance to use for the print
80 if os.path.exists(filePath):
81 logger.write(src.printcolors.printcWarning("Removing ")
85 def print_log_command_in_terminal(filePath, logger):
86 '''Print the contain of filePath. It contains a command log in xml format.
88 :param filePath: The command xml file from which extract the commands
90 :param logger Logger: the logging instance to use in order to print.
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
99 for attrib in dAttrText:
100 lAttrText.append((attrib, dAttrText[attrib]))
101 logger.write("\n", 1)
102 src.print_info(logger, lAttrText)
104 command_traces = xmlRead.get_node_text('Log')
105 # Print it if there is any
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)
112 def show_last_logs(logger, config, log_dirs):
113 """Show last compilation logs"""
114 log_dir = os.path.join(config.APPLICATION.workdir, 'LOGS')
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
124 str_indice = src.printcolors.printcLabel("%2d" % (k+1))
126 logger.write("%s: %-30s" % (str_indice, log_name), 1, False)
127 logger.write("\n", 1, False)
134 product_log_dir = os.path.join(log_dir, log_dirs[x-1])
135 show_product_last_logs(logger, config, product_log_dir)
137 def show_product_last_logs(logger, config, product_log_dir):
138 """Show last compilation logs of a product"""
139 # sort the files chronologically
141 for file_n in os.listdir(product_log_dir):
142 my_stat = os.stat(os.path.join(product_log_dir, file_n))
144 (datetime.datetime.fromtimestamp(my_stat[stat.ST_MTIME]), file_n))
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))
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])))
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)
160 x = ask_value(len(l_time_file))
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)
167 '''Ask for an int n. 0<n<nb
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
175 rep = input(_("Which one (enter or 0 to quit)? "))
176 # Verify it is on the right range
189 '''method that is called when salomeTools is called with --help option.
191 :return: The text to display for the log command description.
195 The log command gives access to the logs produced by the salomeTools commands.
201 def run(args, runner, logger):
202 '''method that is called when salomeTools is called with log parameter.
205 (options, args) = parser.parse_args(args)
207 # get the log directory.
208 logDir = src.get_log_path(runner.cfg)
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)
216 # If the clean options is invoked,
217 # do nothing but deleting the concerned files.
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:
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),
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),
241 os.path.basename(filePath)[:-len('.xml')] + '.pyconf')
242 remove_log_file(pyconfFilePath, logger)
245 logger.write(src.printcolors.printcSuccess("OK\n"))
246 logger.write("%i logs deleted.\n" % nbClean)
249 # determine the commands to show in the hat log
250 notShownCommands = list(runner.cfg.INTERNAL.log.not_shown_commands)
252 notShownCommands = []
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")
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
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)
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)
276 # If the last option is invoked, just, show the last log file
277 if options.last_terminal:
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)
283 # If the last option is invoked, just, show the last log file
285 lastLogFilePath = get_last_log_file(logDir,
286 notShownCommands + ["config"])
288 # Show the log corresponding to the selected command call
289 print_log_command_in_terminal(lastLogFilePath, logger)
291 # open the log xml file in the user editor
292 src.system.show_in_editor(runner.cfg.USER.browser,
293 lastLogFilePath, logger)
296 # If the user asks for a terminal display
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)
303 for filePath, __, date, __, hour, cmd, __ in lLogs:
304 showLog, cmdAppli, __ = src.logger.show_command_log(filePath, cmd,
305 runner.cfg.VARS.application, notShownCommands)
307 lLogsFiltered.append((filePath, date, hour, cmd, cmdAppli))
309 lLogsFiltered = sorted(lLogsFiltered)
310 nb_logs = len(lLogsFiltered)
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)
319 # ask the user what for what command he wants to be displayed
322 x = ask_value(nb_logs)
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)
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')
335 src.logger.update_hat_xml(logDir,
336 application = runner.cfg.VARS.application,
337 notShownCommands = notShownCommands)
339 logger.write(src.printcolors.printc("OK"), 3)
341 logger.write(src.printcolors.printc("KO"), 3)
342 logger.write(" problem update hat.xml", 3)
344 logger.write("\n", 3)
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)
351 logger.write("\nHat log File is %s\n" % xmlHatFilePath, 3)