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