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