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