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