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