]> SALOME platform Git repositories - tools/sat.git/blob - salomeTools.py
Salome HOME
link to remote machine logs in the matrix of jobs command
[tools/sat.git] / salomeTools.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 '''This file is the main entry file to salomeTools
20 '''
21
22 # python imports
23 import os
24 import sys
25 import imp
26 import types
27 import gettext
28
29 # salomeTools imports
30 import src
31
32 # get path to salomeTools sources
33 satdir  = os.path.dirname(os.path.realpath(__file__))
34 cmdsdir = os.path.join(satdir, 'commands')
35
36 # Make the src package accessible from all code
37 sys.path.append(satdir)
38 sys.path.append(cmdsdir)
39
40 import config
41
42 # load resources for internationalization
43 #es = gettext.translation('salomeTools', os.path.join(satdir, 'src', 'i18n'))
44 #es.install()
45 gettext.install('salomeTools', os.path.join(satdir, 'src', 'i18n'))
46
47 # The possible hooks : 
48 # pre is for hooks to be executed before commands
49 # post is for hooks to be executed after commands
50 C_PRE_HOOK = "pre"
51 C_POST_HOOK = "post"
52
53 def find_command_list(dirPath):
54     ''' Parse files in dirPath that end with .py : it gives commands list
55     
56     :param dirPath str: The directory path where to search the commands
57     :return: cmd_list : the list containing the commands name 
58     :rtype: list
59     '''
60     cmd_list = []
61     for item in os.listdir(dirPath):
62         if item.endswith('.py'):
63             cmd_list.append(item[:-len('.py')])
64     return cmd_list
65
66 # The list of valid salomeTools commands
67 #lCommand = ['config', 'compile', 'prepare']
68 lCommand = find_command_list(cmdsdir)
69
70 # Define all possible option for salomeTools command :  sat <option> <args>
71 parser = src.options.Options()
72 parser.add_option('h', 'help', 'boolean', 'help', 
73                   _("shows global help or help on a specific command."))
74 parser.add_option('o', 'overwrite', 'list', "overwrite", 
75                   _("overwrites a configuration parameters."))
76 parser.add_option('g', 'debug', 'boolean', 'debug_mode', 
77                   _("run salomeTools in debug mode."))
78 parser.add_option('v', 'verbose', 'int', "output_verbose_level", 
79                   _("change output verbose level (default is 3)."))
80 parser.add_option('b', 'batch', 'boolean', "batch", 
81                   _("batch mode (no question)."))
82 parser.add_option('t', 'all_in_terminal', 'boolean', "all_in_terminal", 
83                   _("All traces in the terminal (for example compilation logs)."))
84
85 class Sat(object):
86     '''The main class that stores all the commands of salomeTools
87     '''
88     def __init__(self, opt='', datadir=None):
89         '''Initialization
90         
91         :param opt str: The sat options 
92         :param: datadir str : the directory that contain all the external 
93                               data (like software pyconf and software scripts)
94         '''
95         # Read the salomeTools options (the list of possible options is 
96         # at the beginning of this file)
97         try:
98             (options, argus) = parser.parse_args(opt.split(' '))
99         except Exception as exc:
100             write_exception(exc)
101             sys.exit(-1)
102
103         # initialization of class attributes       
104         self.__dict__ = dict()
105         self.cfg = None # the config that will be read using pyconf module
106         self.arguments = opt
107         self.options = options # the options passed to salomeTools
108         self.datadir = datadir # default value will be <salomeTools root>/data
109         # set the commands by calling the dedicated function
110         self._setCommands(cmdsdir)
111         
112         # if the help option has been called, print help and exit
113         if options.help:
114             try:
115                 self.print_help(argus)
116                 sys.exit(0)
117             except Exception as exc:
118                 write_exception(exc)
119                 sys.exit(1)
120
121     def __getattr__(self, name):
122         ''' overwrite of __getattr__ function in order to display 
123             a customized message in case of a wrong call
124         
125         :param name str: The name of the attribute 
126         '''
127         if name in self.__dict__:
128             return self.__dict__[name]
129         else:
130             raise AttributeError(name + _(" is not a valid command"))
131     
132     def _setCommands(self, dirPath):
133         '''set class attributes corresponding to all commands that are 
134            in the dirPath directory
135         
136         :param dirPath str: The directory path containing the commands 
137         '''
138         # loop on the commands name
139         for nameCmd in lCommand:
140             
141             # Exception for the jobs command that require the paramiko module
142             if nameCmd == "jobs":
143                 try:
144                     import paramiko
145                 except:
146                     continue
147
148             # load the module that has name nameCmd in dirPath
149             (file_, pathname, description) = imp.find_module(nameCmd, [dirPath])
150             module = imp.load_module(nameCmd, file_, pathname, description)
151             
152             def run_command(args='', batch = False, verbose = -1, logger_add_link = None):
153                 '''The function that will load the configuration (all pyconf)
154                 and return the function run of the command corresponding to module
155                 
156                 :param args str: The directory path containing the commands 
157                 '''
158                 # Make sure the internationalization is available
159                 gettext.install('salomeTools', os.path.join(satdir, 'src', 'i18n'))
160                 
161                 # Get the arguments in a list and remove the empty elements
162                 argv_0 = args.split(" ")
163                 if argv_0 != ['']:
164                     while "" in argv_0: argv_0.remove("")
165                 
166                 # Format the argv list in order to prevent strings 
167                 # that contain a blank to be separated
168                 argv = []
169                 elem_old = ""
170                 for elem in argv_0:
171                     if argv == [] or elem_old.startswith("-") or elem.startswith("-"):
172                         argv.append(elem)
173                     else:
174                         argv[-1] += " " + elem
175                     elem_old = elem
176                            
177                 # if it is provided by the command line, get the application
178                 appliToLoad = None
179                 if argv != [''] and argv[0][0] != "-":
180                     appliToLoad = argv[0].rstrip('*')
181                     argv = argv[1:]
182    
183                 # read the configuration from all the pyconf files    
184                 cfgManager = config.ConfigManager()
185                 self.cfg = cfgManager.get_config(datadir=self.datadir, 
186                                                  application=appliToLoad, 
187                                                  options=self.options, 
188                                                  command=__nameCmd__)
189                 
190                 # Set the verbose mode if called
191                 if verbose > -1:
192                     verbose_save = self.options.output_verbose_level
193                     self.options.__setattr__("output_verbose_level", verbose)    
194
195                 # Set batch mode if called
196                 if batch:
197                     batch_save = self.options.batch
198                     self.options.__setattr__("batch", True)
199
200                 # set output level
201                 if self.options.output_verbose_level is not None:
202                     self.cfg.USER.output_verbose_level = self.options.output_verbose_level
203                 if self.cfg.USER.output_verbose_level < 1:
204                     self.cfg.USER.output_verbose_level = 0
205                 silent = (self.cfg.USER.output_verbose_level == 0)
206
207                 # create log file
208                 logger_command = src.logger.Logger(self.cfg, 
209                                                    silent_sysstd=silent,
210                                                    all_in_terminal=self.options.all_in_terminal)
211                                
212                 try:
213                     # Execute the hooks (if there is any) 
214                     # and run method of the command
215                     self.run_hook(__nameCmd__, C_PRE_HOOK, logger_command)
216                     res = __module__.run(argv, self, logger_command)
217                     self.run_hook(__nameCmd__, C_POST_HOOK, logger_command)
218                     
219                     # set res if it is not set in the command
220                     if res is None:
221                         res = 0
222                     
223                     # come back in the original batch mode if 
224                     # batch argument was called
225                     if batch:
226                         self.options.__setattr__("batch", batch_save)
227
228                     # come back in the original verbose mode if 
229                     # verbose argument was called                        
230                     if verbose > -1:
231                         self.options.__setattr__("output_verbose_level", 
232                                                  verbose_save)
233                     # put final attributes in xml log file 
234                     # (end time, total time, ...) and write it
235                     launchedCommand = ' '.join([self.cfg.VARS.salometoolsway +
236                                                 os.path.sep +
237                                                 'sat',
238                                                 __nameCmd__, 
239                                                 args])
240                     launchedCommand = launchedCommand.replace('"', "'")
241                     
242                     # Add a link to the parent command      
243                     if logger_add_link is not None:
244                         xmlLinks = logger_add_link.xmlFile.xmlroot.find(
245                                                                     "Links")
246                         src.xmlManager.add_simple_node(xmlLinks, 
247                                                        "link", 
248                                             text = logger_command.logFileName,
249                                             attrib = {"command" : __nameCmd__,
250                                                       "passed" : res,
251                                         "launchedCommand" : launchedCommand})
252                         logger_add_link.l_logFiles +=    logger_command.l_logFiles
253
254                 finally:
255                     launchedCommand = ' '.join([self.cfg.VARS.salometoolsway +
256                                                 os.path.sep +
257                                                 'sat',
258                                                 __nameCmd__, 
259                                                 args])
260                     launchedCommand = launchedCommand.replace('"', "'")
261                     
262                     # Put the final attributes corresponding to end time and
263                     # Write the file to the hard drive
264                     logger_command.end_write(
265                                         {"launchedCommand" : launchedCommand})
266                 
267                 return res
268
269             # Make sure that run_command will be redefined 
270             # at each iteration of the loop
271             globals_up = {}
272             globals_up.update(run_command.__globals__)
273             globals_up.update({'__nameCmd__': nameCmd, '__module__' : module})
274             func = types.FunctionType(run_command.__code__,
275                                       globals_up,
276                                       run_command.__name__,
277                                       run_command.__defaults__,
278                                       run_command.__closure__)
279
280             # set the attribute corresponding to the command
281             self.__setattr__(nameCmd, func)
282
283     def run_hook(self, cmd_name, hook_type, logger):
284         '''Execute a hook file for a given command regarding the fact 
285            it is pre or post
286         
287         :param cmd_name str: The the command on which execute the hook
288         :param hook_type str: pre or post
289         :param logger Logger: the logging instance to use for the prints
290         '''
291         # The hooks must be defined in the application pyconf
292         # So, if there is no application, do not do anything
293         if not src.config_has_application(self.cfg):
294             return
295
296         # The hooks must be defined in the application pyconf in the
297         # APPLICATION section, hook : { command : 'script_path.py'}
298         if "hook" not in self.cfg.APPLICATION \
299                     or cmd_name not in self.cfg.APPLICATION.hook:
300             return
301
302         # Get the hook_script path and verify that it exists
303         hook_script_path = self.cfg.APPLICATION.hook[cmd_name]
304         if not os.path.exists(hook_script_path):
305             raise src.SatException(_("Hook script not found: %s") % 
306                                    hook_script_path)
307         
308         # Try to execute the script, catch the exception if it fails
309         try:
310             # import the module (in the sense of python)
311             pymodule = imp.load_source(cmd_name, hook_script_path)
312             
313             # format a message to be printed at hook execution
314             msg = src.printcolors.printcWarning(_("Run hook script"))
315             msg = "%s: %s\n" % (msg, 
316                                 src.printcolors.printcInfo(hook_script_path))
317             
318             # run the function run_pre_hook if this function is called 
319             # before the command, run_post_hook if it is called after
320             if hook_type == C_PRE_HOOK and "run_pre_hook" in dir(pymodule):
321                 logger.write(msg, 1)
322                 pymodule.run_pre_hook(self.cfg, logger)
323             elif hook_type == C_POST_HOOK and "run_post_hook" in dir(pymodule):
324                 logger.write(msg, 1)
325                 pymodule.run_post_hook(self.cfg, logger)
326
327         except Exception as exc:
328             msg = _("Unable to run hook script: %s") % hook_script_path
329             msg += "\n" + str(exc)
330             raise src.SatException(msg)
331
332     def print_help(self, opt):
333         '''Prints help for a command. Function called when "sat -h <command>"
334         
335         :param argv str: the options passed (to get the command name)
336         '''
337         # if no command as argument (sat -h)
338         if len(opt)==0:
339             print_help()
340             return
341         # get command name
342         command = opt[0]
343         # read the configuration from all the pyconf files    
344         cfgManager = config.ConfigManager()
345         self.cfg = cfgManager.get_config(datadir=self.datadir)
346
347         # Check if this command exists
348         if not hasattr(self, command):
349             raise src.SatException(_("Command '%s' does not exist") % command)
350         
351         # Print salomeTools version
352         print_version()
353         
354         # load the module
355         module = self.get_module(command)
356
357         # print the description of the command that is done in the command file
358         if hasattr( module, "description" ) :
359             print(src.printcolors.printcHeader( _("Description:") ))
360             print(module.description() + '\n')
361
362         # print the description of the command options
363         if hasattr( module, "parser" ) :
364             module.parser.print_help()
365
366     def get_module(self, module):
367         '''Loads a command. Function called only by print_help
368         
369         :param module str: the command to load
370         '''
371         # Check if this command exists
372         if not hasattr(self, module):
373             raise src.SatException(_("Command '%s' does not exist") % module)
374
375         # load the module
376         (file_, pathname, description) = imp.find_module(module, [cmdsdir])
377         module = imp.load_module(module, file_, pathname, description)
378         return module
379  
380 def print_version():
381     '''prints salomeTools version (in src/internal_config/salomeTools.pyconf)
382     '''
383     # read the config 
384     cfgManager = config.ConfigManager()
385     cfg = cfgManager.get_config()
386     # print the key corresponding to salomeTools version
387     print(src.printcolors.printcHeader( _("Version: ") ) + 
388           cfg.INTERNAL.sat_version + '\n')
389
390
391 def print_help():
392     '''prints salomeTools general help
393     
394     :param options str: the options
395     '''
396     print_version()
397     
398     print(src.printcolors.printcHeader( _("Usage: ") ) + 
399           "sat [sat_options] <command> [product] [command_options]\n")
400
401     parser.print_help()
402
403     # display all the available commands.
404     print(src.printcolors.printcHeader(_("Available commands are:\n")))
405     for command in lCommand:
406         print(" - %s" % (command))
407         
408     # Explain how to get the help for a specific command
409     print(src.printcolors.printcHeader(_("\nGetting the help for a specific"
410                                     " command: ")) + "sat --help <command>\n")
411
412 def write_exception(exc):
413     '''write exception in case of error in a command
414     
415     :param exc exception: the exception to print
416     '''
417     sys.stderr.write("\n***** ")
418     sys.stderr.write(src.printcolors.printcError("salomeTools ERROR:"))
419     sys.stderr.write("\n" + str(exc) + "\n")
420
421 # ###############################
422 # MAIN : terminal command usage #
423 # ###############################
424 if __name__ == "__main__":  
425     # Initialize the code that will be returned by the terminal command 
426     code = 0
427     (options, args) = parser.parse_args(sys.argv[1:])
428     
429     # no arguments : print general help
430     if len(args) == 0:
431         print_help()
432         sys.exit(0)
433     
434     # instantiate the salomeTools class with correct options
435     sat = Sat(' '.join(sys.argv[1:]))
436     # the command called
437     command = args[0]
438     # get dynamically the command function to call
439     fun_command = sat.__getattr__(command)
440     # call the command with two cases : mode debug or not
441     if options.debug_mode:
442         # call classically the command and if it fails, 
443         # show exception and stack (usual python mode)
444         code = fun_command(' '.join(args[1:]))
445     else:
446         # catch exception in order to show less verbose but elegant message
447         try:
448             code = fun_command(' '.join(args[1:]))
449         except Exception as exc:
450             code = 1
451             write_exception(exc)
452     
453     # exit salomeTools with the right code (0 if no errors, else 1)
454     if code is None: code = 0
455     sys.exit(code)
456