Salome HOME
a07c5211cdd8be74fe74f0def2741b523f3024f3
[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
24 # Compatibility python 2/3 for input function
25 # input stays input for python 3 and input = raw_input for python 2
26 try: 
27     input = raw_input
28 except NameError: 
29     pass
30
31 import src
32
33 # Define all possible option for log command :  sat log <options>
34 parser = src.options.Options()
35 parser.add_option('t', 'terminal', 'boolean', 'terminal', "Optional: "
36                   "Terminal log.")
37 parser.add_option('l', 'last', 'boolean', 'last', "Show the log of the last "
38                   "Optional: launched command.")
39 parser.add_option('f', 'full', 'boolean', 'full', "Optional: Show the logs of "
40                   "ALL the launched commands.")
41 parser.add_option('c', 'clean', 'int', 'clean', "Optional: Erase the n most "
42                   "ancient log files.")
43 parser.add_option('n', 'no_browser', 'boolean', 'no_browser', "Optional: Do not"
44                   " launch the browser at the end of the command. Only update "
45                   "the hat file.")
46
47 def get_last_log_file(logDir, notShownCommands):
48     '''Used in case of last option. Get the last log command file path.
49     
50     :param logDir str: The directory where to search the log files
51     :param notShownCommands list: the list of commands to ignore
52     :return: the path to the last log file
53     :rtype: str
54     '''
55     last = (_, 0)
56     for fileName in os.listdir(logDir):
57         # YYYYMMDD_HHMMSS_namecmd.xml
58         sExpr = src.logger.log_macro_command_file_expression
59         oExpr = re.compile(sExpr)
60         if oExpr.search(fileName):
61             # get date and hour and format it
62             date_hour_cmd = fileName.split('_')
63             datehour = date_hour_cmd[0] + date_hour_cmd[1]
64             cmd = date_hour_cmd[2]
65             if cmd in notShownCommands:
66                 continue
67             if int(datehour) > last[1]:
68                 last = (fileName, int(datehour))
69     return os.path.join(logDir, last[0])
70
71 def remove_log_file(filePath, logger):
72     '''if it exists, print a warning and remove the input file
73     
74     :param filePath: the path of the file to delete
75     :param logger Logger: the logger instance to use for the print 
76     '''
77     if os.path.exists(filePath):
78         logger.write(src.printcolors.printcWarning("Removing ")
79                      + filePath + "\n", 5)
80         os.remove(filePath)
81
82 def print_log_command_in_terminal(filePath, logger):
83     '''Print the contain of filePath. It contains a command log in xml format.
84     
85     :param filePath: The command xml file from which extract the commands 
86                      context and traces
87     :param logger Logger: the logging instance to use in order to print.  
88     '''
89     logger.write(_("Reading ") + src.printcolors.printcHeader(filePath) + "\n", 5)
90     # Instantiate the ReadXmlFile class that reads xml files
91     xmlRead = src.xmlManager.ReadXmlFile(filePath)
92     # Get the attributes containing the context (user, OS, time, etc..)
93     dAttrText = xmlRead.get_attrib('Site')
94     # format dAttrText and print the context
95     lAttrText = []
96     for attrib in dAttrText:
97         lAttrText.append((attrib, dAttrText[attrib]))
98     logger.write("\n", 1)
99     src.print_info(logger, lAttrText)
100     # Get the traces
101     command_traces = xmlRead.get_node_text('Log')
102     # Print it if there is any
103     if command_traces:
104         logger.write(src.printcolors.printcHeader(
105                                     _("Here are the command traces :\n")), 1)
106         logger.write(command_traces, 1)
107         logger.write("\n", 1)
108
109 def ask_value(nb):
110     '''Ask for an int n. 0<n<nb
111     
112     :param nb int: The maximum value of the value to be returned by the user.
113     :return: the value entered by the user. Return -1 if it is not as expected
114     :rtype: int
115     '''
116     try:
117         # ask for a value
118         rep = input(_("Which one (enter or 0 to quit)? "))
119         # Verify it is on the right range
120         if len(rep) == 0:
121             x = 0
122         else:
123             x = int(rep)
124             if x > nb:
125                 x = -1
126     except:
127         x = -1
128     
129     return x
130
131 def description():
132     '''method that is called when salomeTools is called with --help option.
133     
134     :return: The text to display for the log command description.
135     :rtype: str
136     '''
137     return _("Gives access to the logs produced by the salomeTools commands.\n"
138              "\nexample:\nsat log")    
139
140 def run(args, runner, logger):
141     '''method that is called when salomeTools is called with log parameter.
142     '''
143     # Parse the options
144     (options, args) = parser.parse_args(args)
145
146     # get the log directory. 
147     logDir = runner.cfg.USER.log_dir
148     
149     # Print a header
150     nb_files_log_dir = len(glob.glob(os.path.join(logDir, "*")))
151     info = [("log directory", logDir), 
152             ("number of log files", nb_files_log_dir)]
153     src.print_info(logger, info)
154     
155     # If the clean options is invoked, 
156     # do nothing but deleting the concerned files.
157     if options.clean:
158         nbClean = options.clean
159         # get the list of files to remove
160         lLogs = src.logger.list_log_file(logDir, 
161                                    src.logger.log_all_command_file_expression)
162         nbLogFiles = len(lLogs)
163         # Delete all if the invoked number is bigger than the number of log files
164         if nbClean > nbLogFiles:
165             nbClean = nbLogFiles
166         # Get the list to delete and do the removing
167         lLogsToDelete = sorted(lLogs)[:nbClean]
168         for filePath, __, __, __, __, __, __ in lLogsToDelete:
169             # remove the xml log file
170             remove_log_file(filePath, logger)
171             # remove also the corresponding txt file in OUT directory
172             txtFilePath = os.path.join(os.path.dirname(filePath), 
173                             'OUT', 
174                             os.path.basename(filePath)[:-len('.xml')] + '.txt')
175             remove_log_file(txtFilePath, logger)
176             # remove also the corresponding pyconf (do not exist 2016-06) 
177             # file in OUT directory
178             pyconfFilePath = os.path.join(os.path.dirname(filePath), 
179                             'OUT', 
180                             os.path.basename(filePath)[:-len('.xml')] + '.pyconf')
181             remove_log_file(pyconfFilePath, logger)
182
183         
184         logger.write(src.printcolors.printcSuccess("OK\n"))
185         logger.write("%i logs deleted.\n" % nbClean)
186         return 0 
187
188     # determine the commands to show in the hat log
189     notShownCommands = list(runner.cfg.INTERNAL.log.not_shown_commands)
190     if options.full:
191         notShownCommands = []
192
193     # Find the stylesheets Directory and files
194     xslDir = os.path.join(runner.cfg.VARS.srcDir, 'xsl')
195     xslCommand = os.path.join(xslDir, "command.xsl")
196     xslHat = os.path.join(xslDir, "hat.xsl")
197     xsltest = os.path.join(xslDir, "test.xsl")
198     imgLogo = os.path.join(xslDir, "LOGO-SAT.png")
199     
200     # copy the stylesheets in the log directory
201     shutil.copy2(xslCommand, logDir)
202     shutil.copy2(xslHat, logDir)
203     src.ensure_path_exists(os.path.join(logDir, "TEST"))
204     shutil.copy2(xsltest, os.path.join(logDir, "TEST"))
205     shutil.copy2(imgLogo, logDir)
206
207     # If the last option is invoked, just, show the last log file
208     if options.last:
209         lastLogFilePath = get_last_log_file(logDir,
210                                             notShownCommands + ["config"])        
211         if options.terminal:
212             # Show the log corresponding to the selected command call
213             print_log_command_in_terminal(lastLogFilePath, logger)
214         else:
215             # open the log xml file in the user editor
216             src.system.show_in_editor(runner.cfg.USER.browser, 
217                                       lastLogFilePath, logger)
218         return 0
219
220     # If the user asks for a terminal display
221     if options.terminal:
222         # Parse the log directory in order to find 
223         # all the files corresponding to the commands
224         lLogs = src.logger.list_log_file(logDir, 
225                                    src.logger.log_macro_command_file_expression)
226         lLogsFiltered = []
227         for filePath, __, date, __, hour, cmd, __ in lLogs:
228             showLog, cmdAppli = src.logger.show_command_log(filePath, cmd, 
229                                 runner.cfg.VARS.application, notShownCommands)
230             if showLog:
231                 lLogsFiltered.append((filePath, date, hour, cmd, cmdAppli))
232             
233         lLogsFiltered = sorted(lLogsFiltered)
234         nb_logs = len(lLogsFiltered)
235         index = 0
236         # loop on all files and print it with date, time and command name 
237         for __, date, hour, cmd, cmdAppli in lLogsFiltered:          
238             num = src.printcolors.printcLabel("%2d" % (nb_logs - index))
239             logger.write("%s: %13s %s %s %s\n" % 
240                          (num, cmd, date, hour, cmdAppli), 1, False)
241             index += 1
242         
243         # ask the user what for what command he wants to be displayed
244         x = -1
245         while (x < 0):
246             x = ask_value(nb_logs)
247             if x > 0:
248                 index = len(lLogsFiltered) - int(x)
249                 # Show the log corresponding to the selected command call
250                 print_log_command_in_terminal(lLogsFiltered[index][0], logger)                
251                 x = 0
252         
253         return 0
254                     
255     # Create or update the hat xml that gives access to all the commands log files
256     logger.write(_("Generating the hat log file (can be long) ... "), 3)
257     xmlHatFilePath = os.path.join(logDir, 'hat.xml')
258     src.logger.update_hat_xml(runner.cfg.USER.log_dir, 
259                               application = runner.cfg.VARS.application, 
260                               notShownCommands = notShownCommands)
261     logger.write(src.printcolors.printc("OK"), 3)
262     logger.write("\n", 3)
263     
264     # open the hat xml in the user editor
265     if not options.no_browser:
266         logger.write(_("\nOpening the log file\n"), 3)
267         src.system.show_in_editor(runner.cfg.USER.browser, xmlHatFilePath, logger)
268     return 0